-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal.go
216 lines (181 loc) · 4.44 KB
/
signal.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
package solid
import (
"context"
"errors"
"sync/atomic"
)
var value struct{}
var (
ErrSignalNotAvailable = errors.New("signal not available")
)
type register struct {
signal *Signal
done chan struct{}
}
type Signal struct {
// keep track of the number of signals
// that have been broadcasted
count atomic.Int64
ch chan struct{}
boradcast *Broadcast
withHistory int64
}
func (s *Signal) trigger() {
select {
case s.ch <- value:
default:
s.count.Add(1)
}
}
func (s *Signal) hasMore() bool {
for {
current := s.count.Load()
if current == 0 {
return false
}
if s.count.CompareAndSwap(current, current-1) {
return true
}
}
}
// Wait blocks until a signal is received or the context is done
// if signal is created with withHistory=true, and broadcasted has already happened
// it will return immediately and not block. This is useful for cases where you want to
// know how many broadcasts have happened since the signal was created. if bloadcasted is closed or Signal is Done
// it will return ErrSignalNotAvailable
func (s *Signal) Wait(ctx context.Context) error {
if s.hasMore() {
return nil
}
select {
case _, ok := <-s.ch:
if !ok {
return ErrSignalNotAvailable
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Done closes the signal and removes it from the broadcaster
func (s *Signal) Done() {
s.boradcast.unsubscribe <- s
}
type Broadcast struct {
total int64
// Map to store all subscriber channels
subscribers map[*Signal]struct{}
// Channel to receive messages for broadcasting
input chan struct{}
// Channel to handle unsubscribe requests
unsubscribe chan *Signal
// Channel to handle new subscriptions
subscribe chan *register
// Channel to stop the broadcaster
done chan struct{}
}
// loop handles all broadcaster operations
func (b *Broadcast) loop() {
for {
select {
case <-b.input:
b.total++
// Broadcast message to all subscribers
for s := range b.subscribers {
s.trigger()
}
case reg := <-b.subscribe:
if reg.signal.withHistory > -1 {
total := b.total - reg.signal.withHistory
if total >= 0 {
reg.signal.count.Store(total)
}
}
// Add new subscriber
b.subscribers[reg.signal] = struct{}{}
// Signal that the CreateSignal that the signal is ready
close(reg.done)
case s := <-b.unsubscribe:
// Remove subscriber
delete(b.subscribers, s)
close(s.ch)
case <-b.done:
// Clean up all subscribers
for s := range b.subscribers {
delete(b.subscribers, s)
close(s.ch)
}
return
}
}
}
type SignalOptFunc func(s *Signal)
func WithBufferSize(value int) SignalOptFunc {
return func(s *Signal) {
s.ch = make(chan struct{}, value)
}
}
func WithHistory(count int64) SignalOptFunc {
return func(s *Signal) {
s.withHistory = count
}
}
// CreateSignal creates a new signal and subscribes it to the broadcaster
// bufferSize is the size of the channel buffer, usually 1 is enough but you can increase it if you want to
// please make sure to test and benchmark it upon increasing the buffer size.
// withHistory if set to true, the signal will keep track of the number of broadcasts that have happened since it was created
// this is useful for cases where you want to know how many broadcasts have happened since the signal was created
func (b *Broadcast) CreateSignal(opts ...SignalOptFunc) *Signal {
select {
case <-b.done:
return nil
default:
}
s := &Signal{
boradcast: b,
withHistory: -1,
}
for _, opt := range opts {
opt(s)
}
if s.ch == nil {
s.ch = make(chan struct{}, 1)
}
done := make(chan struct{})
b.subscribe <- ®ister{
signal: s,
done: done,
}
// need to do this to make sure the history and count sets before the signal is returned
<-done
return s
}
// Notify sends a signal to all subscribers and unblocks all waiting signals
func (s *Broadcast) Notify() {
s.input <- struct{}{}
}
// Close closes the broadcaster and all signals
func (b *Broadcast) Close() {
close(b.done)
}
type BroadCastOptFunc func(b *Broadcast)
func WithInitialTotal(total int64) BroadCastOptFunc {
return func(b *Broadcast) {
b.total = total
}
}
func NewBroadcast(opts ...BroadCastOptFunc) *Broadcast {
b := &Broadcast{
subscribers: make(map[*Signal]struct{}),
input: make(chan struct{}),
unsubscribe: make(chan *Signal),
subscribe: make(chan *register),
done: make(chan struct{}),
total: 0,
}
for _, opt := range opts {
opt(b)
}
go b.loop()
return b
}