/
subscriber.go
149 lines (122 loc) · 2.49 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package db
import (
"context"
"encoding/json"
"sync"
"time"
"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
runOnce sync.Once
closing chan struct{}
isClosed bool
}
func NewSubscriber(watcher *Watcher) *Subscriber {
return &Subscriber{
watcher: watcher,
closing: make(chan struct{}),
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.runOnce.Do(func() {
go s.consume(ctx)
})
go func() {
<-s.closing
close(out)
}()
return out, nil
}
func (s *Subscriber) Close() error {
if s.isClosed {
return nil
}
s.isClosed = true
close(s.closing)
return nil
}
func (s *Subscriber) consume(ctx context.Context) {
for {
select {
case <-s.closing:
return
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 {
if s.isClosed {
return
}
select {
case out <- msg:
case <-s.closing:
return
case <-ctx.Done():
return
}
select {
case <-msg.Acked():
return
case <-msg.Nacked():
msg := msg.Copy()
msg.SetContext(msgCtx)
time.Sleep(100 * time.Millisecond)
continue ResendLoop
case <-s.closing:
return
case <-ctx.Done():
return
}
}
}
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
}