forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel_medium.go
420 lines (379 loc) · 12.5 KB
/
channel_medium.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package centrifuge
import (
"errors"
"math"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/timers"
)
// ChannelMediumOptions is an EXPERIMENTAL way to enable using a channel medium layer in Centrifuge.
// Note, channel medium layer is very unstable at the moment – do not use it in production!
// Channel medium layer is an optional per-channel intermediary between Broker PUB/SUB and Client
// connections. This intermediary layer may be used for various per-channel tweaks and optimizations.
// Channel medium comes with memory overhead depending on ChannelMediumOptions. At the same time, it
// can provide significant benefits in terms of overall system efficiency and flexibility.
type ChannelMediumOptions struct {
// KeepLatestPublication enables keeping latest publication which was broadcasted to channel subscribers on
// this Node in the channel medium layer. This is helpful for supporting deltas in at most once scenario.
KeepLatestPublication bool
// SharedPositionSync when true delegates connection position checks to the channel medium. In that case
// check is only performed no more often than once in Config.ClientChannelPositionCheckDelay thus reducing
// the load on broker in cases when channel has many subscribers. When message loss is detected medium layer
// tells caller about this and also marks all channel subscribers with insufficient state flag. By default,
// medium is not used for sync – in that case each individual connection syncs position independently.
SharedPositionSync bool
// EnableQueue for incoming publications. This can be useful to reduce PUB/SUB message processing time
// (as we put it into a single medium layer queue instead of each individual connection queue), reduce
// channel broadcast contention (when one channel waits for broadcast of another channel to finish),
// and also opens a road for broadcast tweaks – such as BroadcastDelay and delta between several
// publications (deltas require both BroadcastDelay and KeepLatestPublication to be enabled). This costs
// additional goroutine.
enableQueue bool
// QueueMaxSize is a maximum size of the queue used in channel medium (in bytes). If zero, 16MB default
// is used. If max size reached, new publications will be dropped.
queueMaxSize int
// BroadcastDelay controls the delay before Publication broadcast. On time tick Centrifugo broadcasts
// only the latest publication in the channel if any. Useful to reduce/smooth the number of messages sent
// to clients when publication contains the entire state. If zero, all publications will be sent to clients
// without delay logic involved on channel medium level. BroadcastDelay option requires (!) EnableQueue to be
// enabled, as we can not afford delays during broadcast from the PUB/SUB layer. BroadcastDelay must not be
// used in channels with positioning/recovery on since it skips publications.
broadcastDelay time.Duration
}
func (o ChannelMediumOptions) isMediumEnabled() bool {
return o.SharedPositionSync || o.KeepLatestPublication || o.enableQueue || o.broadcastDelay > 0
}
// Keep global to save 8 byte per-channel. Must be only changed by tests.
var channelMediumTimeNow = time.Now
// channelMedium is initialized when first subscriber comes into channel, and dropped as soon as last
// subscriber leaves the channel on the Node.
type channelMedium struct {
channel string
node nodeSubset
options ChannelMediumOptions
mu sync.RWMutex
closeCh chan struct{}
// optional queue for publications.
messages *publicationQueue
// We must synchronize broadcast method between general publications and insufficient state notifications.
// Only used when queue is disabled.
broadcastMu sync.Mutex
// latestPublication is a publication last sent to connections on this Node.
latestPublication *Publication
// positionCheckTime is a time (Unix Nanoseconds) when last position check was performed.
positionCheckTime int64
}
type nodeSubset interface {
handlePublication(ch string, sp StreamPosition, pub, prevPub *Publication, localPrevPub *Publication) error
streamTop(ch string, historyMetaTTL time.Duration) (StreamPosition, error)
}
func newChannelMedium(channel string, node nodeSubset, options ChannelMediumOptions) (*channelMedium, error) {
if options.broadcastDelay > 0 && !options.enableQueue {
return nil, errors.New("broadcast delay can only be used with queue enabled")
}
c := &channelMedium{
channel: channel,
node: node,
options: options,
closeCh: make(chan struct{}),
positionCheckTime: channelMediumTimeNow().UnixNano(),
}
if options.enableQueue {
c.messages = newPublicationQueue(2)
go c.writer()
}
return c, nil
}
type queuedPub struct {
pub *Publication
sp StreamPosition
prevPub *Publication
delta bool
isInsufficientState bool
}
const defaultChannelLayerQueueMaxSize = 16 * 1024 * 1024
func (c *channelMedium) broadcastPublication(pub *Publication, sp StreamPosition, delta bool, prevPub *Publication) {
bp := queuedPub{pub: pub, sp: sp, prevPub: prevPub, delta: delta}
c.mu.Lock()
c.positionCheckTime = channelMediumTimeNow().UnixNano()
c.mu.Unlock()
if c.options.enableQueue {
queueMaxSize := defaultChannelLayerQueueMaxSize
if c.options.queueMaxSize > 0 {
queueMaxSize = c.options.queueMaxSize
}
if c.messages.Size() > queueMaxSize {
return
}
c.messages.Add(queuedPublication{Publication: bp})
} else {
c.broadcastMu.Lock()
defer c.broadcastMu.Unlock()
c.broadcast(bp)
}
}
func (c *channelMedium) broadcastInsufficientState() {
bp := queuedPub{prevPub: nil, isInsufficientState: true}
c.mu.Lock()
c.positionCheckTime = channelMediumTimeNow().UnixNano()
c.mu.Unlock()
if c.options.enableQueue {
// TODO: possibly support c.messages.dropQueued() for this path ?
c.messages.Add(queuedPublication{Publication: bp})
} else {
c.broadcastMu.Lock()
defer c.broadcastMu.Unlock()
c.broadcast(bp)
}
}
func (c *channelMedium) broadcast(qp queuedPub) {
pubToBroadcast := qp.pub
spToBroadcast := qp.sp
if qp.isInsufficientState {
// using math.MaxUint64 as a special offset to trigger insufficient state.
pubToBroadcast = &Publication{Offset: math.MaxUint64}
spToBroadcast.Offset = math.MaxUint64
}
prevPub := qp.prevPub
var localPrevPub *Publication
useLocalLatestPub := c.options.KeepLatestPublication && !qp.isInsufficientState
if useLocalLatestPub && qp.delta {
localPrevPub = c.latestPublication
}
if c.options.broadcastDelay > 0 && !c.options.KeepLatestPublication {
prevPub = nil
}
if qp.isInsufficientState {
prevPub = nil
}
_ = c.node.handlePublication(c.channel, spToBroadcast, pubToBroadcast, prevPub, localPrevPub)
if useLocalLatestPub {
c.latestPublication = qp.pub
}
}
func (c *channelMedium) writer() {
for {
if ok := c.waitSendPub(c.options.broadcastDelay); !ok {
return
}
}
}
func (c *channelMedium) waitSendPub(delay time.Duration) bool {
// Wait for message from the queue.
ok := c.messages.Wait()
if !ok {
return false
}
if delay > 0 {
tm := timers.AcquireTimer(delay)
select {
case <-tm.C:
case <-c.closeCh:
timers.ReleaseTimer(tm)
return false
}
timers.ReleaseTimer(tm)
}
msg, ok := c.messages.Remove()
if !ok {
return !c.messages.Closed()
}
if delay == 0 || msg.Publication.isInsufficientState {
c.broadcast(msg.Publication)
return true
}
messageCount := c.messages.Len()
for messageCount > 0 {
messageCount--
var ok bool
msg, ok = c.messages.Remove()
if !ok {
if c.messages.Closed() {
return false
}
break
}
if msg.Publication.isInsufficientState {
break
}
}
c.broadcast(msg.Publication)
return true
}
func (c *channelMedium) CheckPosition(historyMetaTTL time.Duration, clientPosition StreamPosition, checkDelay time.Duration) bool {
nowUnixNano := channelMediumTimeNow().UnixNano()
c.mu.Lock()
needCheckPosition := nowUnixNano-c.positionCheckTime >= checkDelay.Nanoseconds()
if needCheckPosition {
c.positionCheckTime = nowUnixNano
}
c.mu.Unlock()
if !needCheckPosition {
return true
}
_, validPosition, err := c.checkPositionWithRetry(historyMetaTTL, clientPosition)
if err != nil {
// Position will be checked again later.
return true
}
if !validPosition {
c.broadcastInsufficientState()
}
return validPosition
}
func (c *channelMedium) checkPositionWithRetry(historyMetaTTL time.Duration, clientPosition StreamPosition) (StreamPosition, bool, error) {
sp, validPosition, err := c.checkPositionOnce(historyMetaTTL, clientPosition)
if err != nil || !validPosition {
return c.checkPositionOnce(historyMetaTTL, clientPosition)
}
return sp, validPosition, err
}
func (c *channelMedium) checkPositionOnce(historyMetaTTL time.Duration, clientPosition StreamPosition) (StreamPosition, bool, error) {
streamTop, err := c.node.streamTop(c.channel, historyMetaTTL)
if err != nil {
return StreamPosition{}, false, err
}
c.mu.Lock()
defer c.mu.Unlock()
isValidPosition := streamTop.Epoch == clientPosition.Epoch && clientPosition.Offset == streamTop.Offset
return streamTop, isValidPosition, nil
}
func (c *channelMedium) close() {
close(c.closeCh)
}
type queuedPublication struct {
Publication queuedPub
}
// publicationQueue is an unbounded queue of queuedPublication.
// The queue is goroutine safe.
// Inspired by http://blog.dubbelboer.com/2015/04/25/go-faster-queue.html (MIT)
type publicationQueue struct {
mu sync.RWMutex
cond *sync.Cond
nodes []queuedPublication
head int
tail int
cnt int
size int
closed bool
initCap int
}
// newPublicationQueue returns a new queuedPublication queue with initial capacity.
func newPublicationQueue(initialCapacity int) *publicationQueue {
sq := &publicationQueue{
initCap: initialCapacity,
nodes: make([]queuedPublication, initialCapacity),
}
sq.cond = sync.NewCond(&sq.mu)
return sq
}
// Mutex must be held when calling.
func (q *publicationQueue) resize(n int) {
nodes := make([]queuedPublication, n)
if q.head < q.tail {
copy(nodes, q.nodes[q.head:q.tail])
} else {
copy(nodes, q.nodes[q.head:])
copy(nodes[len(q.nodes)-q.head:], q.nodes[:q.tail])
}
q.tail = q.cnt % n
q.head = 0
q.nodes = nodes
}
// Add an queuedPublication to the back of the queue
// will return false if the queue is closed.
// In that case the queuedPublication is dropped.
func (q *publicationQueue) Add(i queuedPublication) bool {
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return false
}
if q.cnt == len(q.nodes) {
// Also tested a growth rate of 1.5, see: http://stackoverflow.com/questions/2269063/buffer-growth-strategy
// In Go this resulted in a higher memory usage.
q.resize(q.cnt * 2)
}
q.nodes[q.tail] = i
q.tail = (q.tail + 1) % len(q.nodes)
if i.Publication.pub != nil {
q.size += len(i.Publication.pub.Data)
}
q.cnt++
q.cond.Signal()
q.mu.Unlock()
return true
}
// Close the queue and discard all entries in the queue
// all goroutines in wait() will return
func (q *publicationQueue) Close() {
q.mu.Lock()
defer q.mu.Unlock()
q.closed = true
q.cnt = 0
q.nodes = nil
q.size = 0
q.cond.Broadcast()
}
// Closed returns true if the queue has been closed
// The call cannot guarantee that the queue hasn't been
// closed while the function returns, so only "true" has a definite meaning.
func (q *publicationQueue) Closed() bool {
q.mu.RLock()
c := q.closed
q.mu.RUnlock()
return c
}
// Wait for a message to be added.
// If there are items on the queue will return immediately.
// Will return false if the queue is closed.
// Otherwise, returns true.
func (q *publicationQueue) Wait() bool {
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return false
}
if q.cnt != 0 {
q.mu.Unlock()
return true
}
q.cond.Wait()
q.mu.Unlock()
return true
}
// Remove will remove an queuedPublication from the queue.
// If false is returned, it either means 1) there were no items on the queue
// or 2) the queue is closed.
func (q *publicationQueue) Remove() (queuedPublication, bool) {
q.mu.Lock()
if q.cnt == 0 {
q.mu.Unlock()
return queuedPublication{}, false
}
i := q.nodes[q.head]
q.head = (q.head + 1) % len(q.nodes)
q.cnt--
if i.Publication.pub != nil {
q.size -= len(i.Publication.pub.Data)
}
if n := len(q.nodes) / 2; n >= q.initCap && q.cnt <= n {
q.resize(n)
}
q.mu.Unlock()
return i, true
}
// Len returns the current length of the queue.
func (q *publicationQueue) Len() int {
q.mu.RLock()
l := q.cnt
q.mu.RUnlock()
return l
}
// Size returns the current size of the queue.
func (q *publicationQueue) Size() int {
q.mu.RLock()
s := q.size
q.mu.RUnlock()
return s
}