-
Notifications
You must be signed in to change notification settings - Fork 9
/
redis.go
320 lines (267 loc) · 7.06 KB
/
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
package broadcaster
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/gomodule/redigo/redis"
"github.com/rubenv/rrpubsub"
"go.uber.org/atomic"
)
type redisBackend struct {
conn redis.Pool
pubSub rrpubsub.Conn
pubSubHost string
prefix string
timeout int
controlChannel string
listening *atomic.Bool
controlWait sync.WaitGroup
dialOptions []redis.DialOption
subscriptions map[string]bool
subscriptionsLock sync.Mutex
Messages chan redis.Message
}
const (
redisSleep time.Duration = 1 * time.Second
redisPingInterval time.Duration = 3 * time.Second
redisConnectTimeout time.Duration = 5 * time.Second
redisReadTimeout time.Duration = 5 * time.Minute
redisWriteTimeout time.Duration = 5 * time.Second
)
func newRedisBackend(redisHost, pubSubHost, controlChannel, prefix string, timeout time.Duration) (*redisBackend, error) {
r := newConnectionRetrier(nil)
opts := []redis.DialOption{
redis.DialConnectTimeout(redisConnectTimeout),
redis.DialReadTimeout(redisReadTimeout),
redis.DialWriteTimeout(redisWriteTimeout),
}
b := &redisBackend{
conn: redis.Pool{
MaxIdle: 3,
IdleTimeout: 60 * time.Second,
Dial: func() (redis.Conn, error) {
var conn redis.Conn
err := r.Run(func() error {
c, err := redis.Dial("tcp", redisHost, opts...)
if err != nil {
return err
}
conn = c
return nil
})
return conn, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) > redisPingInterval {
_, err := c.Do("PING")
return err
}
return nil
},
},
dialOptions: opts,
prefix: prefix,
pubSubHost: pubSubHost,
timeout: int(timeout.Seconds()) + 1,
controlChannel: controlChannel,
subscriptions: make(map[string]bool),
Messages: make(chan redis.Message, 250),
listening: atomic.NewBool(false),
}
b.controlWait.Add(1)
go b.listen()
return b, nil
}
func (b *redisBackend) listen() {
b.connect()
for {
msg, ok := <-b.pubSub.Messages()
if !ok {
return
}
b.Messages <- msg
}
}
func (b *redisBackend) connect() {
b.listening.Store(false)
b.pubSub = rrpubsub.New(context.Background(), "tcp", b.pubSubHost, b.dialOptions...)
b.pubSub.Subscribe(b.controlChannel)
b.subscriptionsLock.Lock()
for k, _ := range b.subscriptions {
b.pubSub.Subscribe(k)
}
b.subscriptionsLock.Unlock()
b.listening.Store(true)
b.controlWait.Done()
}
func (b *redisBackend) key(name string, args ...interface{}) string {
if len(args) > 0 {
return b.prefix + fmt.Sprintf(name, args...)
} else {
return b.prefix + name
}
}
func (b *redisBackend) GetConnected() (int, error) {
conn := b.conn.Get()
defer conn.Close()
c, err := conn.Do("GET", b.key("connected"))
if err != nil {
return 0, err
}
if c == nil {
return 0, nil
}
r, err := redis.Int(c, err)
if err != nil && err != redis.ErrNil {
return 0, err
}
return r, nil
}
func (b *redisBackend) StoreSession(token string, auth ClientMessage) error {
// No need to store these
delete(auth, "__token")
delete(auth, "__type")
data, err := json.Marshal(auth)
if err != nil {
return err
}
conn := b.conn.Get()
defer conn.Close()
conn.Send("MULTI")
conn.Send("SETEX", b.key("sess:"+token), b.timeout, string(data))
conn.Send("INCR", b.key("connected"))
_, err = conn.Do("EXEC")
return err
}
func (b *redisBackend) DeleteSession(token string) error {
conn := b.conn.Get()
defer conn.Close()
conn.Send("MULTI")
conn.Send("DEL", b.key("sess:%s", token))
conn.Send("DEL", b.key("channels:%s", token))
conn.Send("DECR", b.key("connected"))
_, err := conn.Do("EXEC")
return err
}
func (b *redisBackend) GetSession(token string) (ClientMessage, error) {
conn := b.conn.Get()
defer conn.Close()
s, err := redis.Bytes(conn.Do("GET", b.key("sess:"+token)))
if err != nil {
return nil, err
}
data := ClientMessage{}
err = json.Unmarshal(s, &data)
if err != nil {
return nil, err
}
return data, nil
}
func (b *redisBackend) IsConnected(token string) (bool, error) {
conn := b.conn.Get()
defer conn.Close()
r, err := conn.Do("EXISTS", b.key("sess:"+token))
if err != nil {
return false, err
}
return r.(int64) == 1, nil
}
func (b *redisBackend) Subscribe(channel string) {
b.controlWait.Wait()
b.subscriptionsLock.Lock()
defer b.subscriptionsLock.Unlock()
b.subscriptions[channel] = true
b.pubSub.Subscribe(channel)
}
func (b *redisBackend) Unsubscribe(channel string) {
b.controlWait.Wait()
b.subscriptionsLock.Lock()
defer b.subscriptionsLock.Unlock()
delete(b.subscriptions, channel)
b.pubSub.Unsubscribe(channel)
}
// Records channel subscription and broadcasts it to listeners
func (b *redisBackend) LongpollSubscribe(token, channel string) error {
conn := b.conn.Get()
defer conn.Close()
key := b.key("channels:%s", token)
conn.Send("MULTI")
conn.Send("HSET", key, channel, "1")
conn.Send("EXPIRE", key, b.timeout)
conn.Send("PUBLISH", b.controlChannel, fmt.Sprintf("subscribe %s %s", token, channel))
_, err := conn.Do("EXEC")
return err
}
// Records channel unsubscription and broadcasts it to listeners
func (b *redisBackend) LongpollUnsubscribe(token, channel string) error {
conn := b.conn.Get()
defer conn.Close()
key := b.key("channels:%s", token)
conn.Send("MULTI")
conn.Send("HDEL", key, channel)
conn.Send("PUBLISH", b.controlChannel, fmt.Sprintf("unsubscribe %s %s", token, channel))
_, err := conn.Do("EXEC")
return err
}
func (b *redisBackend) LongpollGetChannels(token string) ([]string, error) {
conn := b.conn.Get()
defer conn.Close()
key := b.key("channels:%s", token)
return redis.Strings(conn.Do("HKEYS", key))
}
func (b *redisBackend) LongpollPing(token string) error {
conn := b.conn.Get()
defer conn.Close()
// Use double expire time: the initial waiting time of the request +
// allowed lingering time.
conn.Send("MULTI")
conn.Send("EXPIRE", b.key("channels:%s", token), b.timeout*2)
conn.Send("EXPIRE", b.key("sess:%s", token), b.timeout*2)
_, err := conn.Do("EXEC")
return err
}
func (b *redisBackend) LongpollBacklog(token string, m ClientMessage) error {
conn := b.conn.Get()
defer conn.Close()
// No need to store type
delete(m, "__type")
data, err := json.Marshal(m)
if err != nil {
return err
}
key := b.key("backlog:%s", token)
conn.Send("MULTI")
conn.Send("RPUSH", key, data)
conn.Send("EXPIRE", key, b.timeout)
_, err = conn.Do("EXEC")
return err
}
func (b *redisBackend) LongpollTransfer(token string, seq string) error {
conn := b.conn.Get()
defer conn.Close()
_, err := conn.Do("PUBLISH", b.controlChannel, fmt.Sprintf("transfer %s %s", token, seq))
return err
}
func (b *redisBackend) LongpollGetBacklog(token string, result chan ClientMessage) {
conn := b.conn.Get()
defer conn.Close()
key := b.key("backlog:%s", token)
for {
s, err := redis.Bytes(conn.Do("LPOP", key))
if err != nil {
return
}
data := ClientMessage{}
err = json.Unmarshal(s, &data)
if err != nil {
return
}
data["__type"] = MessageMessage
result <- data
}
}
func (b *redisBackend) IsListening() bool {
return b.listening.Load()
}