-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.go
132 lines (107 loc) · 2.27 KB
/
subscriber.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
package db
import (
"context"
"encoding/json"
"sync"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/hashicorp/go-memdb"
)
var _ message.Subscriber = &Subscriber{}
type Subscriber struct {
mux sync.RWMutex
watcher *Watcher
subscriber map[string][]chan *message.Message
startOnce sync.Once
}
func NewSubscriber(watcher *Watcher) *Subscriber {
return &Subscriber{
watcher: watcher,
subscriber: make(map[string][]chan *message.Message),
}
}
func (s *Subscriber) Subscribe(ctx context.Context, topic string) (<-chan *message.Message, error) {
s.mux.Lock()
defer s.mux.Unlock()
if _, ok := s.subscriber[topic]; !ok {
s.subscriber[topic] = make([]chan *message.Message, 0)
}
out := make(chan *message.Message)
s.subscriber[topic] = append(s.subscriber[topic], out)
s.startOnce.Do(func() {
go s.consume(ctx)
})
return out, nil
}
func (s *Subscriber) Close() error {
s.mux.Lock()
defer s.mux.Unlock()
for _, subs := range s.subscriber {
for _, sub := range subs {
close(sub)
}
}
s.watcher.Close()
return nil
}
func (s *Subscriber) consume(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case change := <-s.watcher.ch:
s.dispatch(ctx, change)
}
}
}
func (s *Subscriber) dispatch(ctx context.Context, change *memdb.Change) {
s.mux.RLock()
defer s.mux.RUnlock()
if change == nil {
return
}
subscribers, ok := s.subscriber[change.Table]
if !ok {
return
}
for _, out := range subscribers {
event, err := databaseChangeToMessage(change)
if err != nil {
continue
}
s.send(ctx, out, event)
}
}
func (s *Subscriber) send(ctx context.Context, out chan *message.Message, msg *message.Message) {
msgCtx, cancel := context.WithCancel(ctx)
msg.SetContext(msgCtx)
defer cancel()
ResendLoop:
for {
select {
case <-ctx.Done():
return
case out <- msg:
}
select {
case <-ctx.Done():
return
case <-msg.Acked():
return
case <-msg.Nacked():
msg := msg.Copy()
msg.SetContext(msgCtx)
continue ResendLoop
}
}
}
func databaseChangeToMessage(change *memdb.Change) (*message.Message, error) {
payload, err := json.Marshal(change)
if err != nil {
return nil, err
}
return message.NewMessage(
watermill.NewUUID(),
payload,
), nil
}