-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrrpubsub.go
282 lines (227 loc) · 4.78 KB
/
rrpubsub.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
package rrpubsub
import (
"context"
"fmt"
"sync"
"time"
"github.com/gomodule/redigo/redis"
)
type state int
const (
initial state = iota
disconnected
connected
)
type eventType int
const (
connectedEvent eventType = iota
disconnectedEvent
messageEvent
)
type command struct {
cmd string
args []string
}
type event struct {
t eventType
c *redisConn
msg redis.Message
err error
}
const (
redisPingInterval time.Duration = 1 * time.Second
redisConnectTimeout time.Duration = 5 * time.Second
redisReadTimeout time.Duration = 10 * time.Second
redisWriteTimeout time.Duration = 5 * time.Second
)
type logger func(msg string)
type Conn interface {
Messages() <-chan redis.Message
Subscribe(channel ...string)
Unsubscribe(channel ...string)
Close() error
}
type conn struct {
// Received messages will be placed in this channel
messages chan redis.Message
network string
address string
options []redis.DialOption
lock sync.Mutex
channels map[string]interface{}
commands chan command
events chan event
state state
ctx context.Context
cf context.CancelFunc
wg sync.WaitGroup
conn *redisConn
backoff time.Duration
debug logger
}
// New returns a new connection that will use the given network and address with the
// specified options.
func New(ctx context.Context, network, address string, options ...redis.DialOption) Conn {
// Default dial options
opts := []redis.DialOption{
redis.DialConnectTimeout(redisConnectTimeout),
redis.DialReadTimeout(redisReadTimeout),
redis.DialWriteTimeout(redisWriteTimeout),
}
opts = append(opts, options...)
ctx, cf := context.WithCancel(ctx)
c := &conn{
messages: make(chan redis.Message, 100),
network: network,
address: address,
options: opts,
channels: make(map[string]interface{}),
commands: make(chan command, 10),
events: make(chan event, 10),
state: initial,
ctx: ctx,
cf: cf,
/*
debug: func(msg string) {
log.Println(msg)
},
*/
}
c.wg.Add(1)
c.logDebug("Starting")
go c.run()
// Initially disconnected
c.logDebug("Sending disconnected")
c.events <- event{t: disconnectedEvent}
return c
}
func (c *conn) Messages() <-chan redis.Message {
return c.messages
}
// Implements the main state machine and interacts with the underlying
// connection
func (c *conn) run() {
defer c.wg.Done()
defer close(c.messages)
c.logDebug("Starting main loop")
done := c.ctx.Done()
for {
select {
case <-done:
return
case cmd := <-c.commands:
switch c.state {
case disconnected:
// Do nothing!
case connected:
c.logDebug("CMD: %s, %#v", cmd.cmd, cmd.args)
c.conn.Do(cmd)
}
case ev := <-c.events:
switch ev.t {
case connectedEvent:
c.logDebug("Connected, subscribing to channels...")
c.state = connected
c.backoff = 0
c.subscribeChannels()
case disconnectedEvent:
if ev.c == c.conn {
if ev.err != nil {
c.logDebug("Disconnected: %s", ev.err.Error())
}
c.state = disconnected
c.flushCommands()
c.closeConnection()
c.connect()
}
case messageEvent:
c.messages <- ev.msg
}
}
}
}
func (c *conn) flushCommands() {
for {
select {
case <-c.commands:
default:
return
}
}
}
func (c *conn) subscribeChannels() {
c.lock.Lock()
defer c.lock.Unlock()
ch := make([]string, 0)
for k := range c.channels {
ch = append(ch, k)
}
if len(ch) == 0 {
return
}
c.commands <- command{
cmd: "SUBSCRIBE",
args: ch,
}
}
func (c *conn) closeConnection() {
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
}
func (c *conn) connect() {
if c.state == connected {
return
}
c.logDebug("Attempting to connect (sleeping %s)", c.backoff)
time.Sleep(c.backoff)
if c.backoff < 1*time.Second {
c.backoff += 100 * time.Millisecond
}
c.conn = newRedisConn(c.ctx, c.network, c.address, c.options, c.events)
go c.conn.Run()
}
// Close closes the connection.
func (c *conn) Close() error {
c.cf()
c.wg.Wait()
return nil
}
// Subscribe subscribes the connection to the specified channels.
func (c *conn) Subscribe(channels ...string) {
if len(channels) == 0 {
return
}
c.lock.Lock()
defer c.lock.Unlock()
for _, ch := range channels {
c.channels[ch] = struct{}{}
}
c.commands <- command{
cmd: "SUBSCRIBE",
args: channels,
}
}
// Unsubscribe unsubscribes the connection from the given channels, or from all
// of them if none is given.
func (c *conn) Unsubscribe(channel ...string) {
c.lock.Lock()
defer c.lock.Unlock()
if len(channel) == 0 {
c.channels = make(map[string]interface{})
} else {
for _, ch := range channel {
delete(c.channels, ch)
}
}
c.commands <- command{
cmd: "UNSUBSCRIBE",
args: channel,
}
}
func (c *conn) logDebug(msg string, args ...interface{}) {
if c.debug != nil {
c.debug(fmt.Sprintf(msg, args...))
}
}