-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub_test.go
More file actions
74 lines (59 loc) · 1.51 KB
/
pubsub_test.go
File metadata and controls
74 lines (59 loc) · 1.51 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
package flow
import (
"context"
"sync"
)
// pubsub stub
type subscription struct {
h PubSubHandler
unsubscribe func() error
}
func (s *subscription) Unsubscribe(ctx context.Context) error {
return s.unsubscribe()
}
type pubsubRecorder struct {
subMtx sync.Mutex
subs map[string][]*subscription // stream => subscriptions
}
func newPubsubRecorder() *pubsubRecorder {
return &pubsubRecorder{
subs: make(map[string][]*subscription),
}
}
func (r *pubsubRecorder) Publish(ctx context.Context, stream string, data []byte) error {
r.subMtx.Lock()
subs := r.subs[stream]
r.subMtx.Unlock()
for _, sub := range subs {
sub.h(ctx, stream, data)
}
return nil
}
func (r *pubsubRecorder) Subscribe(ctx context.Context, stream, group string, h PubSubHandler) (Subscription, error) {
sub := &subscription{h: h}
sub.unsubscribe = func() error { return r.unsubscribe(stream, sub) }
r.subMtx.Lock()
r.subs[stream] = append(r.subs[stream], sub)
r.subMtx.Unlock()
return sub, nil
}
func (r *pubsubRecorder) SubscribeChan(ctx context.Context, stream string) (<-chan frame, Subscription) {
ch := make(chan frame)
sub, _ := r.Subscribe(ctx, stream, "", func(_ context.Context, _ string, data []byte) {
ch <- data
})
return ch, sub
}
func (r *pubsubRecorder) unsubscribe(stream string, sub *subscription) error {
r.subMtx.Lock()
defer r.subMtx.Unlock()
subs := r.subs[stream]
for i, s := range subs {
if s == sub {
subs = append(subs[:i], subs[i+1:]...)
break
}
}
r.subs[stream] = subs
return nil
}