Debian Codegraph @

broker_redis.go

raw
1 package centrifuge
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "runtime"
8 "strconv"
9 "strings"
10 "sync"
11 "sync/atomic"
12 "time"
13
14 "github.com/centrifugal/centrifuge/internal/timers"
15
16 "github.com/centrifugal/protocol"
17 "github.com/gomodule/redigo/redis"
18 )
19
20 const (
21 // redisPubSubWorkerChannelSize sets buffer size of channel to which we send all
22 // messages received from Redis PUB/SUB connection to process in separate goroutine.
23 redisPubSubWorkerChannelSize = 512
24 // redisSubscribeBatchLimit is a maximum number of channels to include in a single
25 // batch subscribe call.
26 redisSubscribeBatchLimit = 512
27 // redisPublishBatchLimit is a maximum limit of publish requests one batched publish
28 // operation can contain.
29 redisPublishBatchLimit = 512
30 // redisControlChannelSuffix is a suffix for control channel.
31 redisControlChannelSuffix = ".control"
32 // redisNodeChannelPrefix is a suffix for node channel.
33 redisNodeChannelPrefix = ".node."
34 // redisPingChannelSuffix is a suffix for ping channel.
35 redisPingChannelSuffix = ".ping"
36 // redisClientChannelPrefix is a prefix before channel name for client messages.
37 redisClientChannelPrefix = ".client."
38 )
39
40 var _ Broker = (*RedisBroker)(nil)
41
42 // RedisBroker uses Redis to implement Broker functionality.
43 // This broker allows to scale Centrifuge-based server to many instances and
44 // load balance client connections between them.
45 // RedisBroker additionally supports Redis Sentinel, client-side consistent
46 // sharding and can work with Redis Cluster (including client-side sharding
47 // between different Redis Clusters to scale PUB/SUB).
48 type RedisBroker struct {
49 controlRound uint64 // Keep atomic on struct top for 32-bit architectures.
50 node *Node
51 sharding bool
52 config RedisBrokerConfig
53 shards []*RedisShard
54 historyListScript *redis.Script
55 historyStreamScript *redis.Script
56 addHistoryListScript *redis.Script
57 addHistoryStreamScript *redis.Script
58 messagePrefix string
59 pingChannel string
60 controlChannel string
61 nodeChannel string
62 }
63
64 // DefaultRedisBrokerPrefix is a default value for RedisBrokerConfig.Prefix.
65 const DefaultRedisBrokerPrefix = "centrifuge"
66
67 type RedisBrokerConfig struct {
68 // Prefix to use before every channel name and key in Redis. By default
69 // DefaultRedisBrokerPrefix will be used.
70 Prefix string
71
72 // HistoryMetaTTL sets a time of stream meta key expiration in Redis. Stream
73 // meta key is a Redis HASH that contains top offset in channel and epoch value.
74 // By default stream meta keys do not expire.
75 //
76 // Though in some cases – when channels created for а short time and then
77 // not used anymore – created stream meta keys can stay in memory while
78 // not actually useful. For example you can have a personal user channel but
79 // after using your app for a while user left it forever. In long-term
80 // perspective this can be an unwanted memory leak. Setting a reasonable
81 // value to this option (usually much bigger than history retention period)
82 // can help. In this case unused channel stream meta data will eventually expire.
83 //
84 // TODO v1: since we have epoch, things should also properly work without meta
85 // information at all (but we loose possibility of long-term recover in stream
86 // without new messages). We can make this optional and disabled by default at
87 // least.
88 HistoryMetaTTL time.Duration
89
90 // UseStreams allows to enable usage of Redis streams instead of list data
91 // structure to keep history. Redis streams are more effective in terms of
92 // missed publication recovery and history pagination since we don't need
93 // to load entire structure to process memory (as we do in case of Redis Lists).
94 // TODO v1: use by default?
95 UseStreams bool
96
97 // PubSubNumWorkers sets how many PUB/SUB message processing workers will
98 // be started. By default runtime.NumCPU() workers used.
99 PubSubNumWorkers int
100
101 // Shards is a list of Redis shards to use. At least one shard must be provided.
102 Shards []*RedisShard
103 }
104
105 // NewRedisBroker initializes Redis Broker.
106 func NewRedisBroker(n *Node, config RedisBrokerConfig) (*RedisBroker, error) {
107 if len(config.Shards) == 0 {
108 return nil, errors.New("broker: no Redis shards provided in configuration")
109 }
110
111 if len(config.Shards) > 1 {
112 n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("broker: Redis sharding enabled: %d shards", len(config.Shards))))
113 }
114
115 if config.Prefix == "" {
116 config.Prefix = DefaultRedisBrokerPrefix
117 }
118
119 b := &RedisBroker{
120 node: n,
121 shards: config.Shards,
122 config: config,
123 sharding: len(config.Shards) > 1,
124 historyListScript: redis.NewScript(2, historySource),
125 historyStreamScript: redis.NewScript(2, historyStreamSource),
126 addHistoryListScript: redis.NewScript(2, addHistorySource),
127 addHistoryStreamScript: redis.NewScript(2, addHistoryStreamSource),
128 }
129
130 for i := range config.Shards {
131 config.Shards[i].registerScripts(
132 b.historyListScript,
133 b.historyStreamScript,
134 b.addHistoryListScript,
135 b.addHistoryStreamScript,
136 )
137 }
138
139 b.messagePrefix = config.Prefix + redisClientChannelPrefix
140 b.pingChannel = config.Prefix + redisPingChannelSuffix
141 b.nodeChannel = string(b.nodeChannelID(n.ID()))
142 b.controlChannel = config.Prefix + redisControlChannelSuffix
143 return b, nil
144 }
145
146 const (
147 // Add to history and optionally publish.
148 // KEYS[1] - history list key
149 // KEYS[2] - sequence meta hash key
150 // ARGV[1] - message payload
151 // ARGV[2] - history size ltrim right bound
152 // ARGV[3] - history lifetime
153 // ARGV[4] - channel to publish message to if needed
154 // ARGV[5] - history meta key expiration time
155 addHistorySource = `
156 redis.replicate_commands()
157 local epoch
158 if redis.call('exists', KEYS[2]) ~= 0 then
159 epoch = redis.call("hget", KEYS[2], "e")
160 end
161 if epoch == false or epoch == nil then
162 epoch = redis.call('time')[1]
163 redis.call("hset", KEYS[2], "e", epoch)
164 end
165 local offset = redis.call("hincrby", KEYS[2], "s", 1)
166 if ARGV[5] ~= '0' then
167 redis.call("expire", KEYS[2], ARGV[5])
168 end
169 local payload = "__" .. "p1:" .. offset .. ":" .. epoch .. "__" .. ARGV[1]
170 redis.call("lpush", KEYS[1], payload)
171 redis.call("ltrim", KEYS[1], 0, ARGV[2])
172 redis.call("expire", KEYS[1], ARGV[3])
173 if ARGV[4] ~= '' then
174 redis.call("publish", ARGV[4], payload)
175 end
176 return {offset, epoch}
177 `
178
179 // addHistoryStreamSource contains Lua script to save data to Redis stream and
180 // publish it into channel.
181 // KEYS[1] - history stream key
182 // KEYS[2] - stream meta hash key
183 // ARGV[1] - message payload
184 // ARGV[2] - stream size
185 // ARGV[3] - stream lifetime
186 // ARGV[4] - channel to publish message to if needed
187 // ARGV[5] - history meta key expiration time
188 addHistoryStreamSource = `
189 redis.replicate_commands()
190 local epoch
191 if redis.call('exists', KEYS[2]) ~= 0 then
192 epoch = redis.call("hget", KEYS[2], "e")
193 end
194 if epoch == false or epoch == nil then
195 epoch = redis.call('time')[1]
196 redis.call("hset", KEYS[2], "e", epoch)
197 end
198 local offset = redis.call("hincrby", KEYS[2], "s", 1)
199 if ARGV[5] ~= '0' then
200 redis.call("expire", KEYS[2], ARGV[5])
201 end
202 redis.call("xadd", KEYS[1], "MAXLEN", ARGV[2], offset, "d", ARGV[1])
203 redis.call("expire", KEYS[1], ARGV[3])
204 if ARGV[4] ~= '' then
205 local payload = "__" .. "p1:" .. offset .. ":" .. epoch .. "__" .. ARGV[1]
206 redis.call("publish", ARGV[4], payload)
207 end
208 return {offset, epoch}
209 `
210
211 // Retrieve channel history information.
212 // KEYS[1] - history list key
213 // KEYS[2] - list meta hash key
214 // ARGV[1] - include publications into response
215 // ARGV[2] - publications list right bound
216 // ARGV[3] - list meta hash key expiration time
217 historySource = `
218 redis.replicate_commands()
219 local offset = redis.call("hget", KEYS[2], "s")
220 local epoch
221 if redis.call('exists', KEYS[2]) ~= 0 then
222 epoch = redis.call("hget", KEYS[2], "e")
223 end
224 if epoch == false or epoch == nil then
225 epoch = redis.call('time')[1]
226 redis.call("hset", KEYS[2], "e", epoch)
227 end
228 if ARGV[3] ~= '0' then
229 redis.call("expire", KEYS[2], ARGV[3])
230 end
231 local pubs = nil
232 if ARGV[1] ~= "0" then
233 pubs = redis.call("lrange", KEYS[1], 0, ARGV[2])
234 end
235 return {offset, epoch, pubs}
236 `
237
238 // historyStreamSource ...
239 // KEYS[1] - history stream key
240 // KEYS[2] - stream meta hash key
241 // ARGV[1] - include publications into response
242 // ARGV[2] - offset
243 // ARGV[3] - limit
244 // ARGV[4] - stream meta hash key expiration time
245 historyStreamSource = `
246 redis.replicate_commands()
247 local offset = redis.call("hget", KEYS[2], "s")
248 local epoch
249 if redis.call('exists', KEYS[2]) ~= 0 then
250 epoch = redis.call("hget", KEYS[2], "e")
251 end
252 if epoch == false or epoch == nil then
253 epoch = redis.call('time')[1]
254 redis.call("hset", KEYS[2], "e", epoch)
255 end
256 if ARGV[4] ~= '0' then
257 redis.call("expire", KEYS[2], ARGV[4])
258 end
259 local pubs = nil
260 if ARGV[1] ~= "0" then
261 if ARGV[3] ~= "0" then
262 pubs = redis.call("xrange", KEYS[1], ARGV[2], "+", "COUNT", ARGV[3])
263 else
264 pubs = redis.call("xrange", KEYS[1], ARGV[2], "+")
265 end
266 end
267 return {offset, epoch, pubs}
268 `
269 )
270
271 func (b *RedisBroker) getShard(channel string) *RedisShard {
272 if !b.sharding {
273 return b.shards[0]
274 }
275 return b.shards[consistentIndex(channel, len(b.shards))]
276 }
277
278 // Run – see Broker.Run.
279 func (b *RedisBroker) Run(h BrokerEventHandler) error {
280 for _, shard := range b.shards {
281 err := b.runShard(shard, h)
282 if err != nil {
283 return err
284 }
285 }
286 return nil
287 }
288
289 func (b *RedisBroker) runShard(shard *RedisShard, h BrokerEventHandler) error {
290 go runForever(func() {
291 b.runPublishPipeline(shard)
292 })
293 go runForever(func() {
294 b.runPubSubPing(shard)
295 })
296 go runForever(func() {
297 b.runPubSub(shard, h)
298 })
299 go runForever(func() {
300 b.runControlPubSub(shard, h)
301 })
302 return nil
303 }
304
305 // Publish - see Broker.Publish.
306 func (b *RedisBroker) Publish(ch string, data []byte, opts PublishOptions) (StreamPosition, error) {
307 return b.publish(b.getShard(ch), ch, data, opts)
308 }
309
310 func (b *RedisBroker) publish(s *RedisShard, ch string, data []byte, opts PublishOptions) (StreamPosition, error) {
311 protoPub := &protocol.Publication{
312 Data: data,
313 Info: infoToProto(opts.ClientInfo),
314 }
315 byteMessage, err := protoPub.Marshal()
316 if err != nil {
317 return StreamPosition{}, err
318 }
319
320 publishChannel := b.messageChannelID(ch)
321
322 if opts.HistorySize <= 0 || opts.HistoryTTL <= 0 {
323 // Fast path – publish without history.
324 eChan := make(chan error, 1)
325
326 pr := pubRequest{
327 channel: publishChannel,
328 message: byteMessage,
329 err: eChan,
330 }
331 select {
332 case s.pubCh <- pr:
333 default:
334 timer := timers.AcquireTimer(s.readTimeout())
335 defer timers.ReleaseTimer(timer)
336 select {
337 case s.pubCh <- pr:
338 case <-timer.C:
339 return StreamPosition{}, errRedisOpTimeout
340 }
341 }
342 return StreamPosition{}, <-eChan
343 }
344
345 historyMetaKey := b.historyMetaKey(s, ch)
346 historyMetaTTLSeconds := int(b.config.HistoryMetaTTL.Seconds())
347
348 var streamKey channelID
349 var size int
350 var script *redis.Script
351 if b.config.UseStreams {
352 streamKey = b.historyStreamKey(s, ch)
353 size = opts.HistorySize
354 script = b.addHistoryStreamScript
355 } else {
356 streamKey = b.historyListKey(s, ch)
357 size = opts.HistorySize - 1
358 script = b.addHistoryListScript
359 }
360 dr := s.newDataRequest("", script, streamKey, []interface{}{streamKey, historyMetaKey, byteMessage, size, int(opts.HistoryTTL.Seconds()), publishChannel, historyMetaTTLSeconds})
361 resp := s.getDataResponse(dr)
362 if resp.err != nil {
363 return StreamPosition{}, resp.err
364 }
365 replies, ok := resp.reply.([]interface{})
366 if !ok || len(replies) != 2 {
367 return StreamPosition{}, errors.New("wrong Redis reply")
368 }
369 index, err := redis.Uint64(replies[0], nil)
370 if err != nil {
371 return StreamPosition{}, errors.New("wrong Redis reply offset")
372 }
373 epoch, err := redis.String(replies[1], nil)
374 if err != nil {
375 return StreamPosition{}, errors.New("wrong Redis reply epoch")
376 }
377 return StreamPosition{Offset: index, Epoch: epoch}, nil
378 }
379
380 // PublishJoin - see Broker.PublishJoin.
381 func (b *RedisBroker) PublishJoin(ch string, info *ClientInfo) error {
382 return b.publishJoin(b.getShard(ch), ch, info)
383 }
384
385 func (b *RedisBroker) publishJoin(s *RedisShard, ch string, info *ClientInfo) error {
386 eChan := make(chan error, 1)
387
388 byteMessage, err := infoToProto(info).Marshal()
389 if err != nil {
390 return err
391 }
392
393 chID := b.messageChannelID(ch)
394
395 pr := pubRequest{
396 channel: chID,
397 message: append(joinTypePrefix, byteMessage...),
398 err: eChan,
399 }
400 select {
401 case s.pubCh <- pr:
402 default:
403 timer := timers.AcquireTimer(s.readTimeout())
404 defer timers.ReleaseTimer(timer)
405 select {
406 case s.pubCh <- pr:
407 case <-timer.C:
408 return errRedisOpTimeout
409 }
410 }
411 return <-eChan
412 }
413
414 // PublishLeave - see Broker.PublishLeave.
415 func (b *RedisBroker) PublishLeave(ch string, info *ClientInfo) error {
416 return b.publishLeave(b.getShard(ch), ch, info)
417 }
418
419 func (b *RedisBroker) publishLeave(s *RedisShard, ch string, info *ClientInfo) error {
420 eChan := make(chan error, 1)
421
422 byteMessage, err := infoToProto(info).Marshal()
423 if err != nil {
424 return err
425 }
426
427 chID := b.messageChannelID(ch)
428
429 pr := pubRequest{
430 channel: chID,
431 message: append(leaveTypePrefix, byteMessage...),
432 err: eChan,
433 }
434 select {
435 case s.pubCh <- pr:
436 default:
437 timer := timers.AcquireTimer(s.readTimeout())
438 defer timers.ReleaseTimer(timer)
439 select {
440 case s.pubCh <- pr:
441 case <-timer.C:
442 return errRedisOpTimeout
443 }
444 }
445 return <-eChan
446 }
447
448 // PublishControl - see Broker.PublishControl.
449 func (b *RedisBroker) PublishControl(data []byte, nodeID string) error {
450 currentRound := atomic.AddUint64(&b.controlRound, 1)
451 index := currentRound % uint64(len(b.shards))
452 s := b.shards[index]
453 return b.publishControl(s, data, nodeID)
454 }
455
456 func (b *RedisBroker) publishControl(s *RedisShard, data []byte, nodeID string) error {
457 eChan := make(chan error, 1)
458
459 var chID channelID
460 if nodeID == "" {
461 chID = channelID(b.controlChannel)
462 } else {
463 chID = b.nodeChannelID(nodeID)
464 }
465
466 pr := pubRequest{
467 channel: chID,
468 message: data,
469 err: eChan,
470 }
471 select {
472 case s.pubCh <- pr:
473 default:
474 timer := timers.AcquireTimer(s.readTimeout())
475 defer timers.ReleaseTimer(timer)
476 select {
477 case s.pubCh <- pr:
478 case <-timer.C:
479 return errRedisOpTimeout
480 }
481 }
482 return <-eChan
483 }
484
485 // Subscribe - see Broker.Subscribe.
486 func (b *RedisBroker) Subscribe(ch string) error {
487 return b.subscribe(b.getShard(ch), ch)
488 }
489
490 func (b *RedisBroker) subscribe(s *RedisShard, ch string) error {
491 if b.node.LogEnabled(LogLevelDebug) {
492 b.node.Log(NewLogEntry(LogLevelDebug, "subscribe node on channel", map[string]interface{}{"channel": ch}))
493 }
494 r := newSubRequest([]channelID{b.messageChannelID(ch)}, true)
495 return s.sendSubscribe(r)
496 }
497
498 // Unsubscribe - see Broker.Unsubscribe.
499 func (b *RedisBroker) Unsubscribe(ch string) error {
500 return b.unsubscribe(b.getShard(ch), ch)
501 }
502
503 func (b *RedisBroker) unsubscribe(s *RedisShard, ch string) error {
504 if b.node.LogEnabled(LogLevelDebug) {
505 b.node.Log(NewLogEntry(LogLevelDebug, "unsubscribe node from channel", map[string]interface{}{"channel": ch}))
506 }
507 r := newSubRequest([]channelID{b.messageChannelID(ch)}, false)
508 return s.sendSubscribe(r)
509 }
510
511 // History - see Broker.History.
512 func (b *RedisBroker) History(ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) {
513 return b.history(b.getShard(ch), ch, filter)
514 }
515
516 func (b *RedisBroker) history(s *RedisShard, ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) {
517 if b.config.UseStreams {
518 return b.historyStream(s, ch, filter)
519 }
520 return b.historyList(s, ch, filter)
521 }
522
523 // RemoveHistory - see Broker.RemoveHistory.
524 func (b *RedisBroker) RemoveHistory(ch string) error {
525 return b.removeHistory(b.getShard(ch), ch)
526 }
527
528 func (b *RedisBroker) removeHistory(s *RedisShard, ch string) error {
529 var key channelID
530 if b.config.UseStreams {
531 key = b.historyStreamKey(s, ch)
532 } else {
533 key = b.historyListKey(s, ch)
534 }
535 dr := s.newDataRequest("DEL", nil, key, []interface{}{key})
536 resp := s.getDataResponse(dr)
537 return resp.err
538 }
539
540 func (b *RedisBroker) messageChannelID(ch string) channelID {
541 return channelID(b.messagePrefix + ch)
542 }
543
544 func (b *RedisBroker) nodeChannelID(nodeID string) channelID {
545 return channelID(b.config.Prefix + redisNodeChannelPrefix + nodeID)
546 }
547
548 func (b *RedisBroker) historyListKey(s *RedisShard, ch string) channelID {
549 if s.useCluster {
550 ch = "{" + ch + "}"
551 }
552 return channelID(b.config.Prefix + ".list." + ch)
553 }
554
555 func (b *RedisBroker) historyStreamKey(s *RedisShard, ch string) channelID {
556 if s.useCluster {
557 ch = "{" + ch + "}"
558 }
559 return channelID(b.config.Prefix + ".stream." + ch)
560 }
561
562 func (b *RedisBroker) historyMetaKey(s *RedisShard, ch string) channelID {
563 if s.useCluster {
564 ch = "{" + ch + "}"
565 }
566 if b.config.UseStreams {
567 return channelID(b.config.Prefix + ".stream.meta." + ch)
568 }
569 return channelID(b.config.Prefix + ".list.meta." + ch)
570 }
571
572 func (b *RedisBroker) runPubSub(s *RedisShard, eventHandler BrokerEventHandler) {
573 numWorkers := b.config.PubSubNumWorkers
574 if numWorkers == 0 {
575 numWorkers = runtime.NumCPU()
576 }
577
578 b.node.Log(NewLogEntry(LogLevelDebug, fmt.Sprintf("running Redis PUB/SUB, num workers: %d", numWorkers), map[string]interface{}{"shard": s.string()}))
579 defer func() {
580 b.node.Log(NewLogEntry(LogLevelDebug, "stopping Redis PUB/SUB", map[string]interface{}{"shard": s.string()}))
581 }()
582
583 poolConn := s.pool.Get()
584 if poolConn.Err() != nil {
585 // At this moment test on borrow could already return an error,
586 // we can't work with broken connection.
587 _ = poolConn.Close()
588 return
589 }
590
591 conn := redis.PubSubConn{Conn: poolConn}
592
593 done := make(chan struct{})
594 var doneOnce sync.Once
595 closeDoneOnce := func() {
596 doneOnce.Do(func() {
597 close(done)
598 })
599 }
600 defer closeDoneOnce()
601
602 // Run subscriber goroutine.
603 go func() {
604 b.node.Log(NewLogEntry(LogLevelDebug, "starting RedisBroker Subscriber", map[string]interface{}{"shard": s.string()}))
605 defer func() {
606 b.node.Log(NewLogEntry(LogLevelDebug, "stopping RedisBroker Subscriber", map[string]interface{}{"shard": s.string()}))
607 }()
608 for {
609 select {
610 case <-done:
611 _ = conn.Close()
612 return
613 case r := <-s.subCh:
614 isSubscribe := r.subscribe
615 channelBatch := []subRequest{r}
616
617 chIDs := make([]interface{}, 0, len(r.channels))
618 for _, ch := range r.channels {
619 chIDs = append(chIDs, ch)
620 }
621
622 var otherR *subRequest
623
624 loop:
625 for len(chIDs) < redisSubscribeBatchLimit {
626 select {
627 case r := <-s.subCh:
628 if r.subscribe != isSubscribe {
629 // We can not mix subscribe and unsubscribe request into one batch
630 // so must stop here. As we consumed a subRequest value from channel
631 // we should take care of it later.
632 otherR = &r
633 break loop
634 }
635 channelBatch = append(channelBatch, r)
636 for _, ch := range r.channels {
637 chIDs = append(chIDs, ch)
638 }
639 default:
640 break loop
641 }
642 }
643
644 var opErr error
645 if isSubscribe {
646 opErr = conn.Subscribe(chIDs...)
647 } else {
648 opErr = conn.Unsubscribe(chIDs...)
649 }
650
651 if opErr != nil {
652 for _, r := range channelBatch {
653 r.done(opErr)
654 }
655 if otherR != nil {
656 otherR.done(opErr)
657 }
658 // Close conn, this should cause Receive to return with err below
659 // and whole runPubSub method to restart.
660 _ = conn.Close()
661 return
662 }
663 for _, r := range channelBatch {
664 r.done(nil)
665 }
666 if otherR != nil {
667 chIDs := make([]interface{}, 0, len(otherR.channels))
668 for _, ch := range otherR.channels {
669 chIDs = append(chIDs, ch)
670 }
671 var opErr error
672 if otherR.subscribe {
673 opErr = conn.Subscribe(chIDs...)
674 } else {
675 opErr = conn.Unsubscribe(chIDs...)
676 }
677 if opErr != nil {
678 otherR.done(opErr)
679 // Close conn, this should cause Receive to return with err below
680 // and whole runPubSub method to restart.
681 _ = conn.Close()
682 return
683 }
684 otherR.done(nil)
685 }
686 }
687 }
688 }()
689
690 // Run workers to spread received message processing work over worker goroutines.
691 workers := make(map[int]chan redis.Message)
692 for i := 0; i < numWorkers; i++ {
693 workerCh := make(chan redis.Message, redisPubSubWorkerChannelSize)
694 workers[i] = workerCh
695 go func(ch chan redis.Message) {
696 for {
697 select {
698 case <-done:
699 return
700 case n := <-ch:
701 switch n.Channel {
702 case b.pingChannel:
703 // Do nothing - this message just maintains connection open.
704 default:
705 err := b.handleRedisClientMessage(eventHandler, channelID(n.Channel), n.Data)
706 if err != nil {
707 b.node.Log(NewLogEntry(LogLevelError, "error handling client message", map[string]interface{}{"error": err.Error()}))
708 continue
709 }
710 }
711 }
712 }
713 }(workerCh)
714 }
715
716 go func() {
717 chIDs := make([]channelID, 1)
718 chIDs[0] = channelID(b.pingChannel)
719
720 for _, ch := range b.node.Hub().Channels() {
721 if b.getShard(ch) == s {
722 chIDs = append(chIDs, b.messageChannelID(ch))
723 }
724 }
725
726 batch := make([]channelID, 0)
727
728 for i, ch := range chIDs {
729 if len(batch) > 0 && i%redisSubscribeBatchLimit == 0 {
730 r := newSubRequest(batch, true)
731 err := s.sendSubscribe(r)
732 if err != nil {
733 b.node.Log(NewLogEntry(LogLevelError, "error subscribing", map[string]interface{}{"error": err.Error()}))
734 closeDoneOnce()
735 return
736 }
737 batch = nil
738 }
739 batch = append(batch, ch)
740 }
741 if len(batch) > 0 {
742 r := newSubRequest(batch, true)
743 err := s.sendSubscribe(r)
744 if err != nil {
745 b.node.Log(NewLogEntry(LogLevelError, "error subscribing", map[string]interface{}{"error": err.Error()}))
746 closeDoneOnce()
747 return
748 }
749 }
750 }()
751
752 for {
753 switch n := conn.ReceiveWithTimeout(10 * time.Second).(type) {
754 case redis.Message:
755 // Add message to worker channel preserving message order - i.b. messages
756 // from the same channel will be processed in the same worker.
757 workers[index(n.Channel, numWorkers)] <- n
758 case redis.Subscription:
759 case error:
760 b.node.Log(NewLogEntry(LogLevelError, "Redis receiver error", map[string]interface{}{"error": n.Error()}))
761 return
762 }
763 }
764 }
765
766 func (b *RedisBroker) runControlPubSub(s *RedisShard, eventHandler BrokerEventHandler) {
767 numWorkers := runtime.NumCPU()
768
769 b.node.Log(NewLogEntry(LogLevelDebug, fmt.Sprintf("running Redis control PUB/SUB, num workers: %d", numWorkers), map[string]interface{}{"shard": s.string()}))
770 defer func() {
771 b.node.Log(NewLogEntry(LogLevelDebug, "stopping Redis control PUB/SUB", map[string]interface{}{"shard": s.string()}))
772 }()
773
774 poolConn := s.pool.Get()
775 if poolConn.Err() != nil {
776 // At this moment test on borrow could already return an error,
777 // we can't work with broken connection.
778 _ = poolConn.Close()
779 return
780 }
781
782 conn := redis.PubSubConn{Conn: poolConn}
783
784 done := make(chan struct{})
785 var doneOnce sync.Once
786 closeDoneOnce := func() {
787 doneOnce.Do(func() {
788 close(done)
789 })
790 }
791 defer closeDoneOnce()
792
793 controlChannel := b.controlChannel
794 nodeChannel := b.nodeChannel
795 pingChannel := b.pingChannel
796
797 // Run workers to spread message processing work over worker goroutines.
798 workCh := make(chan redis.Message)
799 for i := 0; i < numWorkers; i++ {
800 go func() {
801 for {
802 select {
803 case <-done:
804 return
805 case n := <-workCh:
806 switch n.Channel {
807 case pingChannel:
808 // Do nothing - this message just maintains connection open.
809 default:
810 err := eventHandler.HandleControl(n.Data)
811 if err != nil {
812 b.node.Log(NewLogEntry(LogLevelError, "error handling control message", map[string]interface{}{"error": err.Error()}))
813 continue
814 }
815 }
816 }
817 }
818 }()
819 }
820
821 err := conn.Subscribe(controlChannel, nodeChannel, pingChannel)
822 if err != nil {
823 b.node.Log(NewLogEntry(LogLevelError, "control channel subscribe error", map[string]interface{}{"error": err.Error()}))
824 return
825 }
826
827 for {
828 switch n := conn.ReceiveWithTimeout(10 * time.Second).(type) {
829 case redis.Message:
830 // Add message to worker channel preserving message order - i.b. messages
831 // from the same channel will be processed in the same worker.
832 workCh <- n
833 case redis.Subscription:
834 case error:
835 b.node.Log(NewLogEntry(LogLevelError, "Redis receiver error", map[string]interface{}{"error": n.Error()}))
836 return
837 }
838 }
839 }
840
841 func (b *RedisBroker) extractChannel(chID channelID) string {
842 return strings.TrimPrefix(string(chID), b.messagePrefix)
843 }
844
845 // Define prefixes to distinguish Join and Leave messages coming from PUB/SUB.
846 var (
847 joinTypePrefix = []byte("__j__")
848 leaveTypePrefix = []byte("__l__")
849 )
850
851 func (b *RedisBroker) handleRedisClientMessage(eventHandler BrokerEventHandler, chID channelID, data []byte) error {
852 pushData, pushType, sp, ok := extractPushData(data)
853 if !ok {
854 return fmt.Errorf("malformed PUB/SUB data: %s", data)
855 }
856 channel := b.extractChannel(chID)
857 if pushType == pubPushType {
858 var pub protocol.Publication
859 err := pub.Unmarshal(pushData)
860 if err != nil {
861 return err
862 }
863 if pub.Offset == 0 {
864 // When adding to history and publishing happens atomically in RedisBroker
865 // position info is prepended to Publication payload. In this case we should attach
866 // it to unmarshalled Publication.
867 pub.Offset = sp.Offset
868 }
869 _ = eventHandler.HandlePublication(channel, pubFromProto(&pub), sp)
870 } else if pushType == joinPushType {
871 var info protocol.ClientInfo
872 err := info.Unmarshal(pushData)
873 if err != nil {
874 return err
875 }
876 _ = eventHandler.HandleJoin(channel, infoFromProto(&info))
877 } else if pushType == leavePushType {
878 var info protocol.ClientInfo
879 err := info.Unmarshal(pushData)
880 if err != nil {
881 return err
882 }
883 _ = eventHandler.HandleLeave(channel, infoFromProto(&info))
884 }
885 return nil
886 }
887
888 func (b *RedisBroker) runPubSubPing(s *RedisShard) {
889 pingTicker := time.NewTicker(time.Second)
890 defer pingTicker.Stop()
891 for {
892 <-pingTicker.C
893 // Publish periodically to maintain PUB/SUB connection alive and allow
894 // PUB/SUB connection to close early if no data received for a period of time.
895 conn := s.pool.Get()
896 err := conn.Send("PUBLISH", b.pingChannel, nil)
897 if err != nil {
898 b.node.Log(NewLogEntry(LogLevelError, "error publish ping to Redis channel", map[string]interface{}{"error": err.Error()}))
899 _ = conn.Close()
900 return
901 }
902 _ = conn.Close()
903 }
904 }
905
906 func (b *RedisBroker) runPublishPipeline(s *RedisShard) {
907 var prs []pubRequest
908
909 for {
910 pr := <-s.pubCh
911 prs = append(prs, pr)
912
913 loop:
914 for len(prs) < redisPublishBatchLimit {
915 select {
916 case pr := <-s.pubCh:
917 prs = append(prs, pr)
918 default:
919 break loop
920 }
921 }
922 conn := s.pool.Get()
923 for i := range prs {
924 _ = conn.Send("PUBLISH", prs[i].channel, prs[i].message)
925 }
926 err := conn.Flush()
927 if err != nil {
928 for i := range prs {
929 prs[i].done(err)
930 }
931 b.node.Log(NewLogEntry(LogLevelError, "error flushing publish pipeline", map[string]interface{}{"error": err.Error()}))
932 _ = conn.Close()
933 return
934 }
935 for i := range prs {
936 _, err := conn.Receive()
937 prs[i].done(err)
938 }
939 if conn.Err() != nil {
940 _ = conn.Close()
941 return
942 }
943 _ = conn.Close()
944 prs = nil
945 }
946 }
947
948 func (s *RedisShard) sendSubscribe(r subRequest) error {
949 select {
950 case s.subCh <- r:
951 default:
952 timer := timers.AcquireTimer(s.readTimeout())
953 defer timers.ReleaseTimer(timer)
954 select {
955 case s.subCh <- r:
956 case <-timer.C:
957 return errRedisOpTimeout
958 }
959 }
960 return r.result()
961 }
962
963 func extractHistoryResponse(reply interface{}, useStreams bool, includePubs bool) (StreamPosition, []*Publication, error) {
964 results := reply.([]interface{})
965
966 offset, err := redis.Uint64(results[0], nil)
967 if err != nil {
968 if err != redis.ErrNil {
969 return StreamPosition{}, nil, err
970 }
971 offset = 0
972 }
973
974 epoch, err := redis.String(results[1], nil)
975 if err != nil {
976 return StreamPosition{}, nil, err
977 }
978
979 streamPosition := StreamPosition{Offset: offset, Epoch: epoch}
980
981 if includePubs {
982 var publications []*Publication
983 if useStreams {
984 publications, err = sliceOfPubsStream(results[2], nil)
985 } else {
986 publications, err = sliceOfPubsList(results[2], nil)
987 }
988 if err != nil {
989 return StreamPosition{}, nil, err
990 }
991 return streamPosition, publications, nil
992 }
993
994 return streamPosition, nil, nil
995 }
996
997 func (b *RedisBroker) historyStream(s *RedisShard, ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) {
998 historyKey := b.historyStreamKey(s, ch)
999 historyMetaKey := b.historyMetaKey(s, ch)
1000
1001 var includePubs = true
1002 var offset uint64
1003 if filter.Since != nil {
1004 offset = filter.Since.Offset + 1
1005 }
1006 var limit int
1007 if filter.Limit == 0 {
1008 includePubs = false
1009 }
1010 if filter.Limit > 0 {
1011 limit = filter.Limit
1012 }
1013
1014 historyMetaTTLSeconds := int(b.config.HistoryMetaTTL.Seconds())
1015
1016 dr := s.newDataRequest("", b.historyStreamScript, historyKey, []interface{}{historyKey, historyMetaKey, includePubs, offset, limit, historyMetaTTLSeconds})
1017 resp := s.getDataResponse(dr)
1018 if resp.err != nil {
1019 return nil, StreamPosition{}, resp.err
1020 }
1021
1022 latestPosition, publications, err := extractHistoryResponse(resp.reply, b.config.UseStreams, includePubs)
1023 if err != nil {
1024 return nil, StreamPosition{}, err
1025 }
1026
1027 return publications, latestPosition, nil
1028 }
1029
1030 func (b *RedisBroker) historyList(s *RedisShard, ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) {
1031 historyKey := b.historyListKey(s, ch)
1032 historyMetaKey := b.historyMetaKey(s, ch)
1033
1034 var includePubs = true
1035 var rightBound = -1
1036 if filter.Limit == 0 {
1037 rightBound = 0
1038 includePubs = false
1039 }
1040
1041 historyMetaTTLSeconds := int(b.config.HistoryMetaTTL.Seconds())
1042
1043 dr := s.newDataRequest("", b.historyListScript, historyKey, []interface{}{historyKey, historyMetaKey, includePubs, rightBound, historyMetaTTLSeconds})
1044 resp := s.getDataResponse(dr)
1045 if resp.err != nil {
1046 return nil, StreamPosition{}, resp.err
1047 }
1048
1049 latestPosition, publications, err := extractHistoryResponse(resp.reply, b.config.UseStreams, includePubs)
1050 if err != nil {
1051 return nil, StreamPosition{}, err
1052 }
1053
1054 since := filter.Since
1055 if since == nil {
1056 if filter.Limit >= 0 && len(publications) >= filter.Limit {
1057 return publications[:filter.Limit], latestPosition, nil
1058 }
1059 return publications, latestPosition, nil
1060 }
1061
1062 if latestPosition.Offset == since.Offset && since.Epoch == latestPosition.Epoch {
1063 return nil, latestPosition, nil
1064 }
1065
1066 if latestPosition.Offset < since.Offset {
1067 return nil, latestPosition, nil
1068 }
1069
1070 nextOffset := since.Offset + 1
1071
1072 position := -1
1073
1074 for i := 0; i < len(publications); i++ {
1075 pub := publications[i]
1076 if pub.Offset == since.Offset {
1077 position = i + 1
1078 break
1079 }
1080 if pub.Offset == nextOffset {
1081 position = i
1082 break
1083 }
1084 }
1085
1086 if position > -1 {
1087 pubs := publications[position:]
1088 if filter.Limit >= 0 {
1089 limit := filter.Limit
1090 if limit > len(pubs) {
1091 limit = len(pubs)
1092 }
1093 return pubs[:limit], latestPosition, nil
1094 }
1095 return pubs, latestPosition, nil
1096 }
1097
1098 if filter.Limit >= 0 {
1099 limit := filter.Limit
1100 if limit > len(publications) {
1101 limit = len(publications)
1102 }
1103 return publications[:limit], latestPosition, nil
1104 }
1105 return publications, latestPosition, nil
1106 }
1107
1108 type pushType int
1109
1110 const (
1111 pubPushType pushType = 0
1112 joinPushType pushType = 1
1113 leavePushType pushType = 2
1114 )
1115
1116 var (
1117 metaSep = []byte("__")
1118 contentSep = ":"
1119 )
1120
1121 // See tests for supported format examples.
1122 func extractPushData(data []byte) ([]byte, pushType, StreamPosition, bool) {
1123 var offset uint64
1124 var epoch string
1125 if !bytes.HasPrefix(data, metaSep) {
1126 return data, pubPushType, StreamPosition{Epoch: epoch, Offset: offset}, true
1127 }
1128 nextMetaSepPos := bytes.Index(data[len(metaSep):], metaSep)
1129 if nextMetaSepPos <= 0 {
1130 return data, pubPushType, StreamPosition{Epoch: epoch, Offset: offset}, false
1131 }
1132 content := data[len(metaSep) : len(metaSep)+nextMetaSepPos]
1133 contentType := content[0]
1134
1135 rest := data[len(metaSep)+nextMetaSepPos+len(metaSep):]
1136
1137 switch contentType {
1138 case 'j':
1139 return rest, joinPushType, StreamPosition{}, true
1140 case 'l':
1141 return rest, leavePushType, StreamPosition{}, true
1142 }
1143
1144 stringContent := string(content)
1145
1146 if contentType == 'p' {
1147 // new format p1:offset:epoch
1148 stringContent = stringContent[3:] // offset:epoch
1149 epochDelimiterPos := strings.Index(stringContent, contentSep)
1150 if epochDelimiterPos <= 0 {
1151 return rest, pubPushType, StreamPosition{Epoch: epoch, Offset: offset}, false
1152 }
1153 var err error
1154 offset, err = strconv.ParseUint(stringContent[:epochDelimiterPos], 10, 64)
1155 epoch = stringContent[epochDelimiterPos+1:]
1156 return rest, pubPushType, StreamPosition{Epoch: epoch, Offset: offset}, err == nil
1157 }
1158
1159 // old format with offset only: __offset__
1160 var err error
1161 offset, err = strconv.ParseUint(stringContent, 10, 64)
1162 return rest, pubPushType, StreamPosition{Epoch: epoch, Offset: offset}, err == nil
1163 }
1164
1165 func sliceOfPubsStream(result interface{}, err error) ([]*Publication, error) {
1166 values, err := redis.Values(result, err)
1167 if err != nil {
1168 return nil, err
1169 }
1170 pubs := make([]*Publication, 0, len(values))
1171
1172 for i := 0; i < len(values); i++ {
1173 streamElementValues, err := redis.Values(values[i], nil)
1174 if err != nil {
1175 return nil, err
1176 }
1177
1178 if len(streamElementValues) != 2 {
1179 return nil, errors.New("malformed reply: number of streamElementValues is not 2")
1180 }
1181
1182 offsetStr, err := redis.String(streamElementValues[0], nil)
1183 if err != nil {
1184 return nil, err
1185 }
1186 hyphenPos := strings.Index(offsetStr, "-") // ex. "4-0", 4 is our offset.
1187 if hyphenPos <= 0 {
1188 return nil, fmt.Errorf("unexpected offset format: %s", offsetStr)
1189 }
1190 offset, err := strconv.ParseUint(offsetStr[:hyphenPos], 10, 64)
1191 if err != nil {
1192 return nil, err
1193 }
1194
1195 val := streamElementValues[1]
1196 payloadElementValues, err := redis.Values(val, nil)
1197 if err != nil {
1198 return nil, err
1199 }
1200
1201 if len(payloadElementValues) < 2 {
1202 return nil, errors.New("malformed reply: number of payloadElementValues less than 2")
1203 }
1204
1205 pushData, ok := payloadElementValues[1].([]byte)
1206 if !ok {
1207 return nil, errors.New("error getting []byte push data")
1208 }
1209
1210 var pub protocol.Publication
1211 err = pub.Unmarshal(pushData)
1212 if err != nil {
1213 return nil, fmt.Errorf("can not unmarshal value to Publication: %v", err)
1214 }
1215 pub.Offset = offset
1216 pubs = append(pubs, pubFromProto(&pub))
1217 }
1218 return pubs, nil
1219 }
1220
1221 func sliceOfPubsList(result interface{}, err error) ([]*Publication, error) {
1222 values, err := redis.Values(result, err)
1223 if err != nil {
1224 return nil, err
1225 }
1226 pubs := make([]*Publication, 0, len(values))
1227
1228 for i := len(values) - 1; i >= 0; i-- {
1229 value, okValue := values[i].([]byte)
1230 if !okValue {
1231 return nil, errors.New("error getting Message value")
1232 }
1233
1234 pushData, _, sp, ok := extractPushData(value)
1235 if !ok {
1236 return nil, fmt.Errorf("malformed publication value: %s", value)
1237 }
1238
1239 var pub protocol.Publication
1240 err = pub.Unmarshal(pushData)
1241 if err != nil {
1242 return nil, fmt.Errorf("can not unmarshal value to Pub: %v", err)
1243 }
1244 pub.Offset = sp.Offset
1245 pubs = append(pubs, pubFromProto(&pub))
1246 }
1247 return pubs, nil
1248 }