forked from testground/sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
167 lines (136 loc) · 2.91 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
package sync
import (
"context"
"fmt"
"sync"
"time"
)
type subscription struct {
sync.Mutex
ctx context.Context
outCh chan string
doneCh chan error
last int
closed bool
}
func (s *subscription) write(d time.Duration, msg string) error {
s.Lock()
defer s.Unlock()
if s.closed {
return fmt.Errorf("subscription already closed")
}
ctx, cancel := context.WithTimeout(s.ctx, d)
defer cancel()
select {
case s.outCh <- msg:
// Increment last for the next ID.
s.last++
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *subscription) close() {
s.Lock()
defer s.Unlock()
if s.closed {
return
}
s.closed = true
s.doneCh <- s.ctx.Err()
close(s.doneCh)
close(s.outCh)
}
type pubsub struct {
// ctx includes the context of the caller's context, wrapped
// by cancelation through cancel.
ctx context.Context
cancel context.CancelFunc
// lastmod tracks the last time this pubsub instance was accessed
// i.e., the last time something, or someone, subscribed or published.
lastmod time.Time
// wg tracks if the worker for this pubsub instance is done or not.
// The worker stops when the context is canceled.
wg sync.WaitGroup
// msgs tracks all the messages published to this pubsub instance.
// It is needed so when new subscriptions are created, we can send
// all messages retroactively, in order.
msgs []string
msgsMu sync.RWMutex
// subs tracks the subscriptions for this pubsub instance.
subs []*subscription
subsMu sync.RWMutex
}
func (ps *pubsub) subscribe(ctx context.Context) *subscription {
ps.subsMu.Lock()
defer ps.subsMu.Unlock()
sub := &subscription{
ctx: ctx,
closed: false,
outCh: make(chan string),
doneCh: make(chan error, 1),
last: 0,
}
ps.lastmod = time.Now()
ps.subs = append(ps.subs, sub)
return sub
}
func (ps *pubsub) publish(msg string) int {
ps.msgsMu.Lock()
defer ps.msgsMu.Unlock()
ps.lastmod = time.Now()
ps.msgs = append(ps.msgs, msg)
return len(ps.msgs)
}
func (ps *pubsub) worker() {
ticker := time.NewTicker(100 * time.Millisecond)
ps.wg.Add(1)
defer ps.wg.Done()
for {
select {
case <-ticker.C:
ps.writeMessages()
case <-ps.ctx.Done():
ps.cancel()
return
}
}
}
func (ps *pubsub) writeMessages() {
ps.subsMu.RLock()
defer ps.subsMu.RUnlock()
for _, sub := range ps.subs {
func() {
ps.msgsMu.RLock()
defer ps.msgsMu.RUnlock()
for _, msg := range ps.msgs[sub.last:] {
err := sub.write(time.Minute, msg)
if err != nil {
log.Warnf("cannot send message to subscriber: %w", err)
break
}
}
}()
}
}
func (ps *pubsub) isDone() bool {
ps.subsMu.RLock()
defer ps.subsMu.RUnlock()
for _, sub := range ps.subs {
if sub.ctx.Err() == nil {
return false
} else if !sub.closed {
sub.close()
}
}
return true
}
func (ps *pubsub) close() {
ps.cancel()
ps.subsMu.Lock()
defer ps.subsMu.Unlock()
for _, sub := range ps.subs {
sub.close()
}
ps.wg.Wait()
}