-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsubscriptions.go
More file actions
267 lines (230 loc) · 6.75 KB
/
subscriptions.go
File metadata and controls
267 lines (230 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package goro
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/dghubble/sling"
"github.com/satori/go.uuid"
)
const (
readCount = 10 // 10 events
longPollTimeout = "10" // 10 seconds
)
type embedParams struct {
Embed string `url:"embed,omitempty"`
}
type catchupSubscription struct {
stream string
start int64
slinger Slinger
}
// NewCatchupSubscription creates a Subscriber that starts reading a stream from a specific event and then
// catches up to the head of the stream.
func NewCatchupSubscription(slinger Slinger, stream string, startFrom int64) Subscriber {
return &catchupSubscription{
stream: stream,
start: startFrom,
slinger: slinger,
}
}
// Subscribe implements the Subscriber interface
func (s *catchupSubscription) Subscribe(ctx context.Context) <-chan StreamMessage {
stream := make(chan StreamMessage)
response := struct {
Events Events `json:"entries"`
}{}
go func() {
defer close(stream)
next := s.start
for {
path := fmt.Sprintf("/streams/%s/%d/forward/%d", s.stream, next, readCount)
res, err := s.slinger.
Sling().
Get(path).
Add("Accept", "application/vnd.eventstore.atom+json").
Set("ES-LongPoll", longPollTimeout).
QueryStruct(&embedParams{
Embed: "body",
}).
ReceiveSuccess(&response)
if err != nil {
stream <- StreamMessage{
Error: err,
}
return
}
err = relevantError(res.StatusCode)
if err != nil {
stream <- StreamMessage{
Error: err,
}
return
}
sort.Sort(response.Events)
for _, event := range response.Events {
select {
case <-ctx.Done():
return
case stream <- StreamMessage{
Event: event,
}:
}
}
select {
case <-ctx.Done():
return
default:
next += int64(len(response.Events))
}
}
}()
return stream
}
type persistentSubscription struct {
stream string
subscriptionName string
slinger Slinger
}
// PersistentSubscriptionSettings represents the settings for creating and updating a Persistent subscription.
// You can read more about those settings in the Event Store documentation [here](https://eventstore.org/docs/http-api/4.0.2/competing-consumers/#creating-a-persistent-subscription).
type PersistentSubscriptionSettings struct {
ResolveLinkTos bool `json:"resolveLinktos,omitempty"`
StartFrom int64 `json:"startFrom,omitempty"`
ExtraStatistics bool `json:"extraStatistics,omitempty"`
CheckPointAfterMilliseconds int64 `json:"checkPointAfterMilliseconds,omitempty"`
LiveBufferSize int `json:"liveBufferSize,omitempty"`
ReadBatchSize int `json:"readBatchSize,omitempty"`
BufferSize int `json:"bufferSize,omitempty"`
MaxCheckPointCount int `json:"maxCheckPointCount,omitempty"`
MaxRetryCount int `json:"maxRetryCount,omitempty"`
MaxSubscriberCount int `json:"maxSubscriberCount,omitempty"`
MessageTimeoutMilliseconds int64 `json:"messageTimeoutMilliseconds,omitempty"`
MinCheckPointCount int `json:"minCheckPointCount,omitempty"`
NamedConsumerStrategy string `json:"namedConsumerStrategy,omitempty"`
}
// NewPersistentSubscription creates a new subscription that implements the competing consumers pattern
func NewPersistentSubscription(slinger Slinger, stream, subscriptionName string, settings PersistentSubscriptionSettings) (Subscriber, error) {
s := &persistentSubscription{
slinger: slinger,
subscriptionName: subscriptionName,
stream: stream,
}
res, err := s.slinger.
Sling().
Put(fmt.Sprintf("/subscriptions/%s/%s", stream, subscriptionName)).
BodyJSON(settings).
ReceiveSuccess(nil)
if err != nil {
return nil, err
}
return s, relevantError(res.StatusCode)
}
// UpdatePersistentSubscription updates an existing subscription if it's Persistent
func UpdatePersistentSubscription(subscription Subscriber, newSettings PersistentSubscriptionSettings) (Subscriber, error) {
s, ok := subscription.(*persistentSubscription)
if !ok {
return nil, errors.New("not a Persistent Subscription")
}
res, err := s.slinger.
Sling().
Post(fmt.Sprintf("/subscriptions/%s/%s", s.stream, s.subscriptionName)).
BodyJSON(newSettings).
ReceiveSuccess(nil)
if err != nil {
return nil, err
}
return subscription, relevantError(res.StatusCode)
}
// Subscribe implements the Subscriber interface
func (s *persistentSubscription) Subscribe(ctx context.Context) <-chan StreamMessage {
stream := make(chan StreamMessage)
response := struct {
Events Events `json:"entries"`
}{}
go func() {
defer close(stream)
for {
path := fmt.Sprintf("/subscriptions/%s/%s/%d", s.stream, s.subscriptionName, readCount)
res, err := s.slinger.
Sling().
Get(path).
// By default, reading a stream via a persistent subscription will return a
// single event per request and will not embed the event properties as part
// of the response.
Add("Accept", "application/vnd.eventstore.competingatom+json").
QueryStruct(&embedParams{
Embed: "body",
}).
ReceiveSuccess(&response)
if err != nil {
stream <- StreamMessage{
Error: err,
}
return
}
err = relevantError(res.StatusCode)
if err != nil {
stream <- StreamMessage{
Error: err,
}
return
}
sort.Sort(response.Events)
for _, event := range response.Events {
select {
case <-ctx.Done():
return
case stream <- StreamMessage{
Event: event,
Acknowledger: persistentSubscriptionAcknowledger{
eventID: event.ID,
stream: s.stream,
subscriptionName: s.subscriptionName,
sling: s.slinger.Sling(),
},
}:
}
}
select {
case <-ctx.Done():
return
default:
}
}
}()
return stream
}
type persistentSubscriptionAcknowledger struct {
eventID uuid.UUID
stream string
subscriptionName string
sling *sling.Sling
}
func (a persistentSubscriptionAcknowledger) path() string {
path := "/subscriptions/{stream}/{subscription_name}"
path = strings.Replace(path, "{stream}", a.stream, -1)
path = strings.Replace(path, "{subscription_name}", a.subscriptionName, -1)
return path
}
func (a persistentSubscriptionAcknowledger) Ack() error {
path := a.path()
res, err := a.sling.Post(path + "/ack/" + a.eventID.String()).ReceiveSuccess(nil)
if err != nil {
return err
}
return relevantError(res.StatusCode)
}
func (a persistentSubscriptionAcknowledger) Nack(action Action) error {
path := a.path()
res, err := a.sling.Post(path + "/nack/" + a.eventID.String()).QueryStruct(struct {
Action Action `url:"action"`
}{
Action: action,
}).ReceiveSuccess(nil)
if err != nil {
return err
}
return relevantError(res.StatusCode)
}