-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathpubsub.go
384 lines (301 loc) · 9.39 KB
/
pubsub.go
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package gochannel
import (
"context"
"sync"
"github.com/lithammer/shortuuid/v3"
"github.com/pkg/errors"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/message"
)
// Config holds the GoChannel Pub/Sub's configuration options.
type Config struct {
// Output channel buffer size.
OutputChannelBuffer int64
// If persistent is set to true, when subscriber subscribes to the topic,
// it will receive all previously produced messages.
//
// All messages are persisted to the memory (simple slice),
// so be aware that with large amount of messages you can go out of the memory.
Persistent bool
// When true, Publish will block until subscriber Ack's the message.
// If there are no subscribers, Publish will not block (also when Persistent is true).
BlockPublishUntilSubscriberAck bool
}
// GoChannel is the simplest Pub/Sub implementation.
// It is based on Golang's channels which are sent within the process.
//
// GoChannel has no global state,
// that means that you need to use the same instance for Publishing and Subscribing!
//
// When GoChannel is persistent, messages order is not guaranteed.
type GoChannel struct {
config Config
logger watermill.LoggerAdapter
subscribersWg sync.WaitGroup
subscribers map[string][]*subscriber
subscribersLock sync.RWMutex
subscribersByTopicLock sync.Map // map of *sync.Mutex
closed bool
closedLock sync.Mutex
closing chan struct{}
persistedMessages map[string][]*message.Message
persistedMessagesLock sync.RWMutex
}
// NewGoChannel creates new GoChannel Pub/Sub.
//
// This GoChannel is not persistent.
// That means if you send a message to a topic to which no subscriber is subscribed, that message will be discarded.
func NewGoChannel(config Config, logger watermill.LoggerAdapter) *GoChannel {
if logger == nil {
logger = watermill.NopLogger{}
}
return &GoChannel{
config: config,
subscribers: make(map[string][]*subscriber),
subscribersByTopicLock: sync.Map{},
logger: logger.With(watermill.LogFields{
"pubsub_uuid": shortuuid.New(),
}),
closing: make(chan struct{}),
persistedMessages: map[string][]*message.Message{},
}
}
// Publish in GoChannel is NOT blocking until all consumers consume.
// Messages will be sent in background.
//
// Messages may be persisted or not, depending on persistent attribute.
func (g *GoChannel) Publish(topic string, messages ...*message.Message) error {
if g.isClosed() {
return errors.New("Pub/Sub closed")
}
messagesToPublish := make(message.Messages, len(messages))
for i, msg := range messages {
messagesToPublish[i] = msg.Copy()
}
g.subscribersLock.RLock()
defer g.subscribersLock.RUnlock()
subLock, _ := g.subscribersByTopicLock.LoadOrStore(topic, &sync.Mutex{})
subLock.(*sync.Mutex).Lock()
defer subLock.(*sync.Mutex).Unlock()
if g.config.Persistent {
g.persistedMessagesLock.Lock()
if _, ok := g.persistedMessages[topic]; !ok {
g.persistedMessages[topic] = make([]*message.Message, 0)
}
g.persistedMessages[topic] = append(g.persistedMessages[topic], messagesToPublish...)
g.persistedMessagesLock.Unlock()
}
for i := range messagesToPublish {
msg := messagesToPublish[i]
ackedBySubscribers, err := g.sendMessage(topic, msg)
if err != nil {
return err
}
if g.config.BlockPublishUntilSubscriberAck {
g.waitForAckFromSubscribers(msg, ackedBySubscribers)
}
}
return nil
}
func (g *GoChannel) waitForAckFromSubscribers(msg *message.Message, ackedByConsumer <-chan struct{}) {
logFields := watermill.LogFields{"message_uuid": msg.UUID}
g.logger.Debug("Waiting for subscribers ack", logFields)
select {
case <-ackedByConsumer:
g.logger.Trace("Message acked by subscribers", logFields)
case <-g.closing:
g.logger.Trace("Closing Pub/Sub before ack from subscribers", logFields)
}
}
func (g *GoChannel) sendMessage(topic string, message *message.Message) (<-chan struct{}, error) {
subscribers := g.topicSubscribers(topic)
ackedBySubscribers := make(chan struct{})
logFields := watermill.LogFields{"message_uuid": message.UUID, "topic": topic}
if len(subscribers) == 0 {
close(ackedBySubscribers)
g.logger.Info("No subscribers to send message", logFields)
return ackedBySubscribers, nil
}
go func(subscribers []*subscriber) {
wg := &sync.WaitGroup{}
for i := range subscribers {
subscriber := subscribers[i]
wg.Add(1)
go func() {
subscriber.sendMessageToSubscriber(message, logFields)
wg.Done()
}()
}
wg.Wait()
close(ackedBySubscribers)
}(subscribers)
return ackedBySubscribers, nil
}
// Subscribe returns channel to which all published messages are sent.
// Messages are not persisted. If there are no subscribers and message is produced it will be gone.
//
// There are no consumer groups support etc. Every consumer will receive every produced message.
func (g *GoChannel) Subscribe(ctx context.Context, topic string) (<-chan *message.Message, error) {
g.closedLock.Lock()
if g.closed {
g.closedLock.Unlock()
return nil, errors.New("Pub/Sub closed")
}
g.subscribersWg.Add(1)
g.closedLock.Unlock()
g.subscribersLock.Lock()
subLock, _ := g.subscribersByTopicLock.LoadOrStore(topic, &sync.Mutex{})
subLock.(*sync.Mutex).Lock()
s := &subscriber{
ctx: ctx,
uuid: watermill.NewUUID(),
outputChannel: make(chan *message.Message, g.config.OutputChannelBuffer),
logger: g.logger,
closing: make(chan struct{}),
}
go func(s *subscriber, g *GoChannel) {
select {
case <-ctx.Done():
// unblock
case <-g.closing:
// unblock
}
s.Close()
g.subscribersLock.Lock()
defer g.subscribersLock.Unlock()
subLock, _ := g.subscribersByTopicLock.Load(topic)
subLock.(*sync.Mutex).Lock()
defer subLock.(*sync.Mutex).Unlock()
g.removeSubscriber(topic, s)
g.subscribersWg.Done()
}(s, g)
if !g.config.Persistent {
defer g.subscribersLock.Unlock()
defer subLock.(*sync.Mutex).Unlock()
g.addSubscriber(topic, s)
return s.outputChannel, nil
}
go func(s *subscriber) {
defer g.subscribersLock.Unlock()
defer subLock.(*sync.Mutex).Unlock()
g.persistedMessagesLock.RLock()
messages, ok := g.persistedMessages[topic]
g.persistedMessagesLock.RUnlock()
if ok {
for i := range messages {
msg := g.persistedMessages[topic][i]
logFields := watermill.LogFields{"message_uuid": msg.UUID, "topic": topic}
go s.sendMessageToSubscriber(msg, logFields)
}
}
g.addSubscriber(topic, s)
}(s)
return s.outputChannel, nil
}
func (g *GoChannel) addSubscriber(topic string, s *subscriber) {
if _, ok := g.subscribers[topic]; !ok {
g.subscribers[topic] = make([]*subscriber, 0)
}
g.subscribers[topic] = append(g.subscribers[topic], s)
}
func (g *GoChannel) removeSubscriber(topic string, toRemove *subscriber) {
removed := false
for i, sub := range g.subscribers[topic] {
if sub == toRemove {
g.subscribers[topic] = append(g.subscribers[topic][:i], g.subscribers[topic][i+1:]...)
removed = true
break
}
}
if !removed {
panic("cannot remove subscriber, not found " + toRemove.uuid)
}
}
func (g *GoChannel) topicSubscribers(topic string) []*subscriber {
subscribers, ok := g.subscribers[topic]
if !ok {
return nil
}
// let's do a copy to avoid race conditions and deadlocks due to lock
subscribersCopy := make([]*subscriber, len(subscribers))
copy(subscribersCopy, subscribers)
return subscribersCopy
}
func (g *GoChannel) isClosed() bool {
g.closedLock.Lock()
defer g.closedLock.Unlock()
return g.closed
}
// Close closes the GoChannel Pub/Sub.
func (g *GoChannel) Close() error {
g.closedLock.Lock()
defer g.closedLock.Unlock()
if g.closed {
return nil
}
g.closed = true
close(g.closing)
g.logger.Debug("Closing Pub/Sub, waiting for subscribers", nil)
g.subscribersWg.Wait()
g.logger.Info("Pub/Sub closed", nil)
g.persistedMessages = nil
return nil
}
type subscriber struct {
ctx context.Context
uuid string
sending sync.Mutex
outputChannel chan *message.Message
logger watermill.LoggerAdapter
closed bool
closing chan struct{}
}
func (s *subscriber) Close() {
if s.closed {
return
}
close(s.closing)
s.logger.Debug("Closing subscriber, waiting for sending lock", nil)
// ensuring that we are not sending to closed channel
s.sending.Lock()
defer s.sending.Unlock()
s.logger.Debug("GoChannel Pub/Sub Subscriber closed", nil)
s.closed = true
close(s.outputChannel)
}
func (s *subscriber) sendMessageToSubscriber(msg *message.Message, logFields watermill.LogFields) {
s.sending.Lock()
defer s.sending.Unlock()
ctx, cancelCtx := context.WithCancel(s.ctx)
defer cancelCtx()
SendToSubscriber:
for {
// copy the message to prevent ack/nack propagation to other consumers
// also allows to make retries on a fresh copy of the original message
msgToSend := msg.Copy()
msgToSend.SetContext(ctx)
s.logger.Trace("Sending msg to subscriber", logFields)
if s.closed {
s.logger.Info("Pub/Sub closed, discarding msg", logFields)
return
}
select {
case s.outputChannel <- msgToSend:
s.logger.Trace("Sent message to subscriber", logFields)
case <-s.closing:
s.logger.Trace("Closing, message discarded", logFields)
return
}
select {
case <-msgToSend.Acked():
s.logger.Trace("Message acked", logFields)
return
case <-msgToSend.Nacked():
s.logger.Trace("Nack received, resending message", logFields)
continue SendToSubscriber
case <-s.closing:
s.logger.Trace("Closing, message discarded", logFields)
return
}
}
}