forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine_redis.go
2001 lines (1790 loc) · 52.7 KB
/
engine_redis.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package centrifuge
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"hash/fnv"
"net"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/recovery"
"github.com/centrifugal/centrifuge/internal/timers"
"github.com/FZambia/sentinel"
"github.com/centrifugal/protocol"
"github.com/gomodule/redigo/redis"
"github.com/mna/redisc"
)
const (
// redisPubSubWorkerChannelSize sets buffer size of channel to which we send all
// messages received from Redis PUB/SUB connection to process in separate goroutine.
redisPubSubWorkerChannelSize = 1024
// redisSubscribeBatchLimit is a maximum number of channels to include in a single subscribe
// call. Redis documentation doesn't specify a maximum allowed but we think it probably makes
// sense to keep a sane limit given how many subscriptions a single Centrifugo instance might
// be handling.
redisSubscribeBatchLimit = 512
// redisPublishBatchLimit is a maximum limit of publish requests one batched publish
// operation can contain.
redisPublishBatchLimit = 512
// redisDataBatchLimit is a max amount of data requests in one batch.
redisDataBatchLimit = 64
)
const (
defaultPrefix = "centrifuge"
defaultReadTimeout = time.Second
defaultWriteTimeout = time.Second
defaultConnectTimeout = time.Second
defaultPoolSize = 128
)
type (
// channelID is unique channel identifier in Redis.
channelID string
)
var errRedisOpTimeout = errors.New("operation timed out")
const (
// redisControlChannelSuffix is a suffix for control channel.
redisControlChannelSuffix = ".control"
// redisPingChannelSuffix is a suffix for ping channel.
redisPingChannelSuffix = ".ping"
// redisClientChannelPrefix is a prefix before channel name for client messages.
redisClientChannelPrefix = ".client."
)
// RedisEngine uses Redis to implement Engine functionality.
// This engine allows to scale Centrifuge based server to many instances and
// load balance client connections between them.
// Redis engine supports additionally supports Sentinel, client-side sharding
// and can work with Redis Cluster (or client-side shard between different
// Redis Clusters).
type RedisEngine struct {
node *Node
sharding bool
config RedisEngineConfig
shards []*shard
}
var _ Engine = (*RedisEngine)(nil)
type redisConnPool interface {
Get() redis.Conn
}
// shard has everything to connect to Redis instance.
type shard struct {
node *Node
engine *RedisEngine
config RedisShardConfig
pool redisConnPool
subCh chan subRequest
pubCh chan pubRequest
dataCh chan dataRequest
addPresenceScript *redis.Script
remPresenceScript *redis.Script
presenceScript *redis.Script
historyScript *redis.Script
addHistoryScript *redis.Script
addHistoryStreamScript *redis.Script
historyStreamScript *redis.Script
messagePrefix string
HistoryMetaTTL time.Duration
useStreams bool
}
// RedisEngineConfig is a config for Redis Engine.
type RedisEngineConfig struct {
// PublishOnHistoryAdd is an option to control Redis Engine behaviour in terms of
// adding to history and publishing message to channel. Redis Engine have a role
// of Broker, HistoryManager and PresenceManager, this option is a tip to engine
// implementation about the fact that Redis Engine used as both Broker and
// HistoryManager. In this case we have a possibility to save Publications into
// channel history stream and publish into PUB/SUB Redis channel via single RTT.
PublishOnHistoryAdd bool
// HistoryMetaTTL sets a time of stream meta key expiration in Redis. Stream
// meta key is a Redis HASH that contains top offset in channel and epoch value.
// By default stream meta keys do not expire.
//
// Though in some cases – when channels created for а short time and then
// not used anymore – created stream meta keys can stay in memory while
// not actually useful. For example you can have a personal user channel but
// after using your app for a while user left it forever. In long-term
// perspective this can be an unwanted memory leak. Setting a reasonable
// value to this option (usually much bigger than history retention period)
// can help. In this case unused channel stream meta data will eventually expire.
//
// TODO v1: maybe make this channel namespace option?
// TODO v1: since we have epoch things should also properly work without meta
// information at all (but we loose possibility of long-term recover in stream
// without new messages).
HistoryMetaTTL time.Duration
// UseStreams allows to enable usage of Redis streams instead of list data
// structure to keep history. Redis streams are more effective in terms of
// missed publication recovery and history pagination since we don't need
// to load entire structure to process memory (as we do in case of Redis Lists).
// TODO v1: use by default?
UseStreams bool
// Shards is a list of Redis instance configs.
Shards []RedisShardConfig
}
// RedisShardConfig is struct with Redis Engine options.
type RedisShardConfig struct {
// Host is Redis server host.
Host string
// Port is Redis server port.
Port int
// Password is password to use when connecting to Redis database. If empty then password not used.
Password string
// DB is Redis database number. If not set then database 0 used.
DB int
// Whether to use TLS connection or not.
UseTLS bool
// Whether to skip hostname verification as part of TLS handshake.
TLSSkipVerify bool
// Connection TLS configuration.
TLSConfig *tls.Config
// MasterName is a name of Redis instance master Sentinel monitors.
MasterName string
// SentinelAddrs is a slice of Sentinel addresses.
SentinelAddrs []string
// ClusterAddrs is a slice of seed cluster addrs for this shard.
ClusterAddrs []string
// Prefix to use before every channel name and key in Redis.
Prefix string
// IdleTimeout is timeout after which idle connections to Redis will be closed.
IdleTimeout time.Duration
// PubSubNumWorkers sets how many PUB/SUB message processing workers will be started.
// By default we start runtime.NumCPU() workers.
PubSubNumWorkers int
// ReadTimeout is a timeout on read operations. Note that at moment it should be greater
// than node ping publish interval in order to prevent timing out Pubsub connection's
// Receive call.
ReadTimeout time.Duration
// WriteTimeout is a timeout on write operations.
WriteTimeout time.Duration
// ConnectTimeout is a timeout on connect operation.
ConnectTimeout time.Duration
}
// subRequest is an internal request to subscribe or unsubscribe from one or more channels
type subRequest struct {
channels []channelID
subscribe bool
err chan error
}
// newSubRequest creates a new request to subscribe or unsubscribe form a channel.
func newSubRequest(chIDs []channelID, subscribe bool) subRequest {
return subRequest{
channels: chIDs,
subscribe: subscribe,
err: make(chan error, 1),
}
}
// done should only be called once for subRequest.
func (sr *subRequest) done(err error) {
sr.err <- err
}
func (sr *subRequest) result() error {
return <-sr.err
}
func makePoolFactory(s *shard, n *Node, conf RedisShardConfig) func(addr string, options ...redis.DialOption) (*redis.Pool, error) {
password := conf.Password
db := conf.DB
useSentinel := conf.MasterName != "" && len(conf.SentinelAddrs) > 0
var lastMu sync.Mutex
var lastMaster string
poolSize := defaultPoolSize
maxIdle := poolSize
var sntnl *sentinel.Sentinel
if useSentinel {
sntnl = &sentinel.Sentinel{
Addrs: conf.SentinelAddrs,
MasterName: conf.MasterName,
Dial: func(addr string) (redis.Conn, error) {
timeout := 300 * time.Millisecond
opts := []redis.DialOption{
redis.DialConnectTimeout(timeout),
redis.DialReadTimeout(timeout),
redis.DialWriteTimeout(timeout),
}
c, err := redis.Dial("tcp", addr, opts...)
if err != nil {
n.Log(NewLogEntry(LogLevelError, "error dialing to Sentinel", map[string]interface{}{"error": err.Error()}))
return nil, err
}
return c, nil
},
}
// Periodically discover new Sentinels.
go func() {
if err := sntnl.Discover(); err != nil {
n.Log(NewLogEntry(LogLevelError, "error discover Sentinel", map[string]interface{}{"error": err.Error()}))
}
for {
<-time.After(30 * time.Second)
if err := sntnl.Discover(); err != nil {
n.Log(NewLogEntry(LogLevelError, "error discover Sentinel", map[string]interface{}{"error": err.Error()}))
}
}
}()
}
return func(serverAddr string, dialOpts ...redis.DialOption) (*redis.Pool, error) {
pool := &redis.Pool{
MaxIdle: maxIdle,
MaxActive: poolSize,
Wait: true,
IdleTimeout: conf.IdleTimeout,
Dial: func() (redis.Conn, error) {
var err error
if useSentinel {
serverAddr, err = sntnl.MasterAddr()
if err != nil {
return nil, err
}
lastMu.Lock()
if serverAddr != lastMaster {
n.Log(NewLogEntry(LogLevelInfo, "Redis master discovered", map[string]interface{}{"addr": serverAddr}))
lastMaster = serverAddr
}
lastMu.Unlock()
}
c, err := redis.Dial("tcp", serverAddr, dialOpts...)
if err != nil {
n.Log(NewLogEntry(LogLevelError, "error dialing to Redis", map[string]interface{}{"error": err.Error()}))
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
_ = c.Close()
n.Log(NewLogEntry(LogLevelError, "error auth in Redis", map[string]interface{}{"error": err.Error()}))
return nil, err
}
}
if db != 0 {
if _, err := c.Do("SELECT", db); err != nil {
_ = c.Close()
n.Log(NewLogEntry(LogLevelError, "error selecting Redis db", map[string]interface{}{"error": err.Error()}))
return nil, err
}
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if useSentinel {
if !sentinel.TestRole(c, "master") {
return errors.New("failed master role check")
}
return nil
}
if s.useCluster() {
// No need in this optimization outside cluster
// use case due to utilization of pipelining.
if time.Since(t) < time.Second {
return nil
}
}
_, err := c.Do("PING")
return err
},
}
return pool, nil
}
}
func getDialOpts(conf RedisShardConfig) []redis.DialOption {
var readTimeout = defaultReadTimeout
if conf.ReadTimeout != 0 {
readTimeout = conf.ReadTimeout
}
var writeTimeout = defaultWriteTimeout
if conf.WriteTimeout != 0 {
writeTimeout = conf.WriteTimeout
}
var connectTimeout = defaultConnectTimeout
if conf.ConnectTimeout != 0 {
connectTimeout = conf.ConnectTimeout
}
dialOpts := []redis.DialOption{
redis.DialConnectTimeout(connectTimeout),
redis.DialReadTimeout(readTimeout),
redis.DialWriteTimeout(writeTimeout),
}
if conf.UseTLS {
dialOpts = append(dialOpts, redis.DialUseTLS(true))
if conf.TLSConfig != nil {
dialOpts = append(dialOpts, redis.DialTLSConfig(conf.TLSConfig))
}
if conf.TLSSkipVerify {
dialOpts = append(dialOpts, redis.DialTLSSkipVerify(true))
}
}
return dialOpts
}
func newPool(s *shard, n *Node, conf RedisShardConfig) (redisConnPool, error) {
host := conf.Host
port := conf.Port
password := conf.Password
db := conf.DB
useSentinel := conf.MasterName != "" && len(conf.SentinelAddrs) > 0
usingPassword := password != ""
poolFactory := makePoolFactory(s, n, conf)
if !s.useCluster() {
serverAddr := net.JoinHostPort(host, strconv.Itoa(port))
if !useSentinel {
n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: %s/%d, using password: %v", serverAddr, db, usingPassword)))
} else {
n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: Sentinel for name: %s, db: %d, using password: %v", conf.MasterName, db, usingPassword)))
}
pool, _ := poolFactory(serverAddr, getDialOpts(conf)...)
return pool, nil
}
// OK, we should work with cluster.
n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: cluster addrs: %+v, using password: %v", conf.ClusterAddrs, usingPassword)))
cluster := &redisc.Cluster{
DialOptions: getDialOpts(conf),
StartupNodes: conf.ClusterAddrs,
CreatePool: poolFactory,
}
// Initialize cluster mapping.
if err := cluster.Refresh(); err != nil {
return nil, err
}
return cluster, nil
}
// NewRedisEngine initializes Redis Engine.
func NewRedisEngine(n *Node, config RedisEngineConfig) (*RedisEngine, error) {
var shards = make([]*shard, 0, len(config.Shards))
if len(config.Shards) == 0 {
return nil, errors.New("no Redis shards provided in configuration")
}
if len(config.Shards) > 1 {
n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis sharding enabled: %d shards", len(config.Shards))))
}
for _, conf := range config.Shards {
prefix := conf.Prefix
if prefix == "" {
conf.Prefix = defaultPrefix
}
shard, err := newShard(n, conf)
if err != nil {
return nil, err
}
shard.HistoryMetaTTL = config.HistoryMetaTTL
shard.useStreams = config.UseStreams
shards = append(shards, shard)
}
e := &RedisEngine{
node: n,
shards: shards,
config: config,
sharding: len(shards) > 1,
}
return e, nil
}
const (
// Add to history and optionally publish.
// KEYS[1] - history list key
// KEYS[2] - sequence meta hash key
// ARGV[1] - message payload
// ARGV[2] - history size ltrim right bound
// ARGV[3] - history lifetime
// ARGV[4] - channel to publish message to if needed
// ARGV[5] - history meta key expiration time
addHistorySource = `
redis.replicate_commands()
local epoch
if redis.call('exists', KEYS[2]) ~= 0 then
epoch = redis.call("hget", KEYS[2], "e")
else
epoch = redis.call('time')[1]
redis.call("hset", KEYS[2], "e", epoch)
end
local offset = redis.call("hincrby", KEYS[2], "s", 1)
if ARGV[5] ~= '0' then
redis.call("expire", KEYS[2], ARGV[5])
end
local payload = "__" .. offset .. "__" .. ARGV[1]
redis.call("lpush", KEYS[1], payload)
redis.call("ltrim", KEYS[1], 0, ARGV[2])
redis.call("expire", KEYS[1], ARGV[3])
if ARGV[4] ~= '' then
redis.call("publish", ARGV[4], payload)
end
return {offset, epoch}
`
// addHistoryStreamSource contains Lua script to save data to Redis stream and
// publish it into channel.
// KEYS[1] - history stream key
// KEYS[2] - stream meta hash key
// ARGV[1] - message payload
// ARGV[2] - stream size
// ARGV[3] - stream lifetime
// ARGV[4] - channel to publish message to if needed
// ARGV[5] - history meta key expiration time
addHistoryStreamSource = `
redis.replicate_commands()
local epoch
if redis.call('exists', KEYS[2]) ~= 0 then
epoch = redis.call("hget", KEYS[2], "e")
else
epoch = redis.call('time')[1]
redis.call("hset", KEYS[2], "e", epoch)
end
local offset = redis.call("hincrby", KEYS[2], "s", 1)
if ARGV[5] ~= '0' then
redis.call("expire", KEYS[2], ARGV[5])
end
redis.call("xadd", KEYS[1], "MAXLEN", ARGV[2], offset, "d", ARGV[1])
redis.call("expire", KEYS[1], ARGV[3])
if ARGV[4] ~= '' then
local payload = "__" .. offset .. "__" .. ARGV[1]
redis.call("publish", ARGV[4], payload)
end
return {offset, epoch}
`
// Retrieve channel history information.
// KEYS[1] - history list key
// KEYS[2] - stream meta hash key
// ARGV[1] - include publications into response
// ARGV[2] - publications list right bound
// ARGV[3] - sequence key expiration time
historySource = `
redis.replicate_commands()
local offset = redis.call("hget", KEYS[2], "s")
if ARGV[3] ~= '0' and offset ~= false then
redis.call("expire", KEYS[2], ARGV[3])
end
local epoch
if redis.call('exists', KEYS[2]) ~= 0 then
epoch = redis.call("hget", KEYS[2], "e")
else
epoch = redis.call('time')[1]
redis.call("hset", KEYS[2], "e", epoch)
end
local pubs = nil
if ARGV[1] ~= "0" then
pubs = redis.call("lrange", KEYS[1], 0, ARGV[2])
end
return {offset, epoch, pubs}
`
// historyStreamSource ...
// KEYS[1] - history stream key
// KEYS[2] - stream meta hash key
// ARGV[1] - include publications into response
// ARGV[2] - offset
// ARGV[3] - limit
// ARGV[4] - sequence key expiration time
historyStreamSource = `
redis.replicate_commands()
local offset = redis.call("hget", KEYS[2], "s")
if ARGV[3] ~= '0' and offset ~= false then
redis.call("expire", KEYS[2], ARGV[3])
end
local epoch
if redis.call('exists', KEYS[2]) ~= 0 then
epoch = redis.call("hget", KEYS[2], "e")
else
epoch = redis.call('time')[1]
redis.call("hset", KEYS[2], "e", epoch)
end
local pubs = nil
if ARGV[1] ~= "0" then
if ARGV[3] ~= "0" then
pubs = redis.call("xrange", KEYS[1], ARGV[2], "+", "COUNT", ARGV[3])
else
pubs = redis.call("xrange", KEYS[1], ARGV[2], "+")
end
end
return {offset, epoch, pubs}
`
// Add/update client presence information.
// KEYS[1] - presence set key
// KEYS[2] - presence hash key
// ARGV[1] - key expire seconds
// ARGV[2] - expire at for set member
// ARGV[3] - client ID
// ARGV[4] - info payload
addPresenceSource = `
redis.call("zadd", KEYS[1], ARGV[2], ARGV[3])
redis.call("hset", KEYS[2], ARGV[3], ARGV[4])
redis.call("expire", KEYS[1], ARGV[1])
redis.call("expire", KEYS[2], ARGV[1])
`
// Remove client presence.
// KEYS[1] - presence set key
// KEYS[2] - presence hash key
// ARGV[1] - client ID
remPresenceSource = `
redis.call("hdel", KEYS[2], ARGV[1])
redis.call("zrem", KEYS[1], ARGV[1])
`
// Get presence information.
// KEYS[1] - presence set key
// KEYS[2] - presence hash key
// ARGV[1] - current timestamp in seconds
presenceSource = `
local expired = redis.call("zrangebyscore", KEYS[1], "0", ARGV[1])
if #expired > 0 then
for num = 1, #expired do
redis.call("hdel", KEYS[2], expired[num])
end
redis.call("zremrangebyscore", KEYS[1], "0", ARGV[1])
end
return redis.call("hgetall", KEYS[2])
`
)
func (e *RedisEngine) getShard(channel string) *shard {
if !e.sharding {
return e.shards[0]
}
return e.shards[consistentIndex(channel, len(e.shards))]
}
// Run runs engine after node initialized.
func (e *RedisEngine) Run(h BrokerEventHandler) error {
for _, shard := range e.shards {
shard.engine = e
err := shard.Run(h)
if err != nil {
return err
}
}
return nil
}
// Publish - see engine interface description.
func (e *RedisEngine) Publish(ch string, pub *protocol.Publication, opts *ChannelOptions) error {
return e.getShard(ch).Publish(ch, pub, opts)
}
// PublishJoin - see engine interface description.
func (e *RedisEngine) PublishJoin(ch string, join *protocol.Join, opts *ChannelOptions) error {
return e.getShard(ch).PublishJoin(ch, join, opts)
}
// PublishLeave - see engine interface description.
func (e *RedisEngine) PublishLeave(ch string, leave *protocol.Leave, opts *ChannelOptions) error {
return e.getShard(ch).PublishLeave(ch, leave, opts)
}
// PublishControl - see engine interface description.
func (e *RedisEngine) PublishControl(data []byte) error {
var err error
for _, shard := range e.shards {
err = shard.PublishControl(data)
if err != nil {
continue
}
return nil
}
return fmt.Errorf("publish control error, all shards failed: last error: %v", err)
}
// Subscribe - see engine interface description.
func (e *RedisEngine) Subscribe(ch string) error {
return e.getShard(ch).Subscribe(ch)
}
// Unsubscribe - see engine interface description.
func (e *RedisEngine) Unsubscribe(ch string) error {
return e.getShard(ch).Unsubscribe(ch)
}
// AddPresence - see engine interface description.
func (e *RedisEngine) AddPresence(ch string, uid string, info *protocol.ClientInfo, exp time.Duration) error {
expire := int(exp.Seconds())
return e.getShard(ch).AddPresence(ch, uid, info, expire)
}
// RemovePresence - see engine interface description.
func (e *RedisEngine) RemovePresence(ch string, uid string) error {
return e.getShard(ch).RemovePresence(ch, uid)
}
// Presence - see engine interface description.
func (e *RedisEngine) Presence(ch string) (map[string]*protocol.ClientInfo, error) {
return e.getShard(ch).Presence(ch)
}
// PresenceStats - see engine interface description.
func (e *RedisEngine) PresenceStats(ch string) (PresenceStats, error) {
return e.getShard(ch).PresenceStats(ch)
}
// History - see engine interface description.
func (e *RedisEngine) History(ch string, filter HistoryFilter) ([]*protocol.Publication, StreamPosition, error) {
return e.getShard(ch).History(ch, filter)
}
// AddHistory - see engine interface description.
func (e *RedisEngine) AddHistory(ch string, pub *protocol.Publication, opts *ChannelOptions) (StreamPosition, bool, error) {
streamTop, err := e.getShard(ch).AddHistory(ch, pub, opts, e.config.PublishOnHistoryAdd)
return streamTop, e.config.PublishOnHistoryAdd, err
}
// RemoveHistory - see engine interface description.
func (e *RedisEngine) RemoveHistory(ch string) error {
return e.getShard(ch).RemoveHistory(ch)
}
// Channels - see engine interface description.
func (e *RedisEngine) Channels() ([]string, error) {
channelMap := map[string]struct{}{}
for _, shard := range e.shards {
shardChannels, err := shard.Channels()
if err != nil {
return nil, err
}
if !e.sharding {
// We have all channels on one shard.
return shardChannels, nil
}
for _, ch := range shardChannels {
channelMap[ch] = struct{}{}
}
}
channels := make([]string, 0, len(channelMap))
for ch := range channelMap {
channels = append(channels, ch)
}
return channels, nil
}
// newShard initializes new Redis shard.
func newShard(n *Node, conf RedisShardConfig) (*shard, error) {
shard := &shard{
node: n,
config: conf,
addPresenceScript: redis.NewScript(2, addPresenceSource),
remPresenceScript: redis.NewScript(2, remPresenceSource),
presenceScript: redis.NewScript(2, presenceSource),
historyScript: redis.NewScript(2, historySource),
addHistoryScript: redis.NewScript(2, addHistorySource),
addHistoryStreamScript: redis.NewScript(2, addHistoryStreamSource),
historyStreamScript: redis.NewScript(2, historyStreamSource),
}
pool, err := newPool(shard, n, conf)
if err != nil {
return nil, err
}
shard.pool = pool
shard.subCh = make(chan subRequest)
shard.pubCh = make(chan pubRequest)
shard.dataCh = make(chan dataRequest)
shard.messagePrefix = conf.Prefix + redisClientChannelPrefix
if !shard.useCluster() {
// Only need data pipeline in non-cluster scenario.
go shard.runForever(func() {
shard.runDataPipeline()
})
}
return shard, nil
}
func (s *shard) useCluster() bool {
return len(s.config.ClusterAddrs) != 0
}
func (s *shard) controlChannelID() channelID {
return channelID(s.config.Prefix + redisControlChannelSuffix)
}
func (s *shard) pingChannelID() channelID {
return channelID(s.config.Prefix + redisPingChannelSuffix)
}
func (s *shard) messageChannelID(ch string) channelID {
return channelID(s.messagePrefix + ch)
}
func (s *shard) presenceHashKey(ch string) channelID {
if s.useCluster() {
ch = "{" + ch + "}"
}
return channelID(s.config.Prefix + ".presence.data." + ch)
}
func (s *shard) presenceSetKey(ch string) channelID {
if s.useCluster() {
ch = "{" + ch + "}"
}
return channelID(s.config.Prefix + ".presence.expire." + ch)
}
func (s *shard) historyListKey(ch string) channelID {
if s.useCluster() {
ch = "{" + ch + "}"
}
return channelID(s.config.Prefix + ".history.list." + ch)
}
func (s *shard) historyStreamKey(ch string) channelID {
if s.useCluster() {
ch = "{" + ch + "}"
}
return channelID(s.config.Prefix + ".history.stream." + ch)
}
func (s *shard) historyMetaKey(ch string) channelID {
if s.useCluster() {
ch = "{" + ch + "}"
}
if s.useStreams {
return channelID(s.config.Prefix + ".stream.meta." + ch)
}
// TODO v1: rename to list.meta.
return channelID(s.config.Prefix + ".seq.meta." + ch)
}
// Run Redis shard.
func (s *shard) Run(h BrokerEventHandler) error {
go s.runForever(func() {
s.runPublishPipeline()
})
go s.runForever(func() {
s.runPubSubPing()
})
go s.runForever(func() {
s.runPubSub(h)
})
return nil
}
func (s *shard) readTimeout() time.Duration {
var readTimeout = defaultReadTimeout
if s.config.ReadTimeout != 0 {
readTimeout = s.config.ReadTimeout
}
return readTimeout
}
// runForever keeps another function running indefinitely.
// The reason this loop is not inside the function itself is
// so that defer can be used to cleanup nicely.
func (s *shard) runForever(fn func()) {
for {
fn()
// Sleep for a while to prevent busy loop when reconnecting to Redis.
time.Sleep(300 * time.Millisecond)
}
}
func (s *shard) runPubSub(eventHandler BrokerEventHandler) {
numWorkers := s.config.PubSubNumWorkers
if numWorkers == 0 {
numWorkers = runtime.NumCPU()
}
s.node.Log(NewLogEntry(LogLevelDebug, fmt.Sprintf("running Redis PUB/SUB, num workers: %d", numWorkers)))
defer func() {
s.node.Log(NewLogEntry(LogLevelDebug, "stopping Redis PUB/SUB"))
}()
poolConn := s.pool.Get()
if poolConn.Err() != nil {
// At this moment test on borrow could already return an error,
// we can't work with broken connection.
_ = poolConn.Close()
return
}
conn := redis.PubSubConn{Conn: poolConn}
done := make(chan struct{})
var doneOnce sync.Once
closeDoneOnce := func() {
doneOnce.Do(func() {
close(done)
})
}
defer closeDoneOnce()
// Run subscriber goroutine.
go func() {
s.node.Log(NewLogEntry(LogLevelDebug, "starting RedisEngine Subscriber"))
defer func() {
s.node.Log(NewLogEntry(LogLevelDebug, "stopping RedisEngine Subscriber"))
}()
for {
select {
case <-done:
_ = conn.Close()
return
case r := <-s.subCh:
isSubscribe := r.subscribe
channelBatch := []subRequest{r}
chIDs := make([]interface{}, 0, len(r.channels))
for _, ch := range r.channels {
chIDs = append(chIDs, ch)
}
var otherR *subRequest
loop:
for len(chIDs) < redisSubscribeBatchLimit {
select {
case r := <-s.subCh:
if r.subscribe != isSubscribe {
// We can not mix subscribe and unsubscribe request into one batch
// so must stop here. As we consumed a subRequest value from channel
// we should take care of it later.
otherR = &r
break loop
}
channelBatch = append(channelBatch, r)
for _, ch := range r.channels {
chIDs = append(chIDs, ch)
}
default:
break loop
}
}
var opErr error
if isSubscribe {
opErr = conn.Subscribe(chIDs...)
} else {
opErr = conn.Unsubscribe(chIDs...)
}
if opErr != nil {
for _, r := range channelBatch {
r.done(opErr)
}
if otherR != nil {
otherR.done(opErr)
}
// Close conn, this should cause Receive to return with err below
// and whole runPubSub method to restart.
_ = conn.Close()
return
}
for _, r := range channelBatch {
r.done(nil)
}
if otherR != nil {
chIDs := make([]interface{}, 0, len(otherR.channels))
for _, ch := range otherR.channels {
chIDs = append(chIDs, ch)
}
var opErr error
if otherR.subscribe {
opErr = conn.Subscribe(chIDs...)
} else {
opErr = conn.Unsubscribe(chIDs...)
}
if opErr != nil {
otherR.done(opErr)
// Close conn, this should cause Receive to return with err below
// and whole runPubSub method to restart.
_ = conn.Close()
return
}
otherR.done(nil)
}
}
}
}()
controlChannel := s.controlChannelID()
pingChannel := s.pingChannelID()
// Run workers to spread received message processing work over worker goroutines.
workers := make(map[int]chan redis.Message)
for i := 0; i < numWorkers; i++ {
workerCh := make(chan redis.Message, redisPubSubWorkerChannelSize)
workers[i] = workerCh
go func(ch chan redis.Message) {
for {
select {
case <-done:
return
case n := <-ch:
chID := channelID(n.Channel)
switch chID {
case controlChannel:
err := eventHandler.HandleControl(n.Data)
if err != nil {
s.node.Log(NewLogEntry(LogLevelError, "error handling control message", map[string]interface{}{"error": err.Error()}))
continue
}
case pingChannel:
// Do nothing - this message just maintains connection open.
default:
err := s.handleRedisClientMessage(eventHandler, chID, n.Data)
if err != nil {
s.node.Log(NewLogEntry(LogLevelError, "error handling client message", map[string]interface{}{"error": err.Error()}))
continue
}
}
}
}
}(workerCh)
}
go func() {
chIDs := make([]channelID, 2)
chIDs[0] = controlChannel
chIDs[1] = pingChannel
for _, ch := range s.node.Hub().Channels() {
if s.engine.getShard(ch) == s {
chIDs = append(chIDs, s.messageChannelID(ch))
}
}
batch := make([]channelID, 0)
for i, ch := range chIDs {
if len(batch) > 0 && i%redisSubscribeBatchLimit == 0 {
r := newSubRequest(batch, true)
err := s.sendSubscribe(r)
if err != nil {
s.node.Log(NewLogEntry(LogLevelError, "error subscribing", map[string]interface{}{"error": err.Error()}))
closeDoneOnce()
return
}
batch = nil
}
batch = append(batch, ch)