forked from tidwall/redcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redcon.go
567 lines (514 loc) · 12.2 KB
/
redcon.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
// Package redcon implements a Redis compatible server framework
package redcon
import (
"bytes"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/panjf2000/gnet/v2"
"github.com/leslie-fei/gnettls/tls"
"github.com/leslie-fei/gnettls"
"github.com/tidwall/btree"
"github.com/tidwall/match"
)
type Action int
var (
errUnbalancedQuotes = &errProtocol{"unbalanced quotes in request"}
errInvalidBulkLength = &errProtocol{"invalid bulk length"}
errInvalidMultiBulkLength = &errProtocol{"invalid multibulk length"}
errDetached = errors.New("detached")
errIncompleteCommand = errors.New("incomplete command")
errTooMuchData = errors.New("too much data")
)
const maxBufferCap = 262144
type errProtocol struct {
msg string
}
func (err *errProtocol) Error() string {
return "Protocol error: " + err.msg
}
const (
None Action = iota
Close
Shutdown
)
type Conn struct {
gnet.Conn
buf bytes.Buffer
}
// Command represent a command
type Command struct {
// Raw is a encoded RESP message.
Raw []byte
// Args is a series of arguments that make up the command.
Args [][]byte
}
func parseInt(b []byte) (int, bool) {
if len(b) == 1 && b[0] >= '0' && b[0] <= '9' {
return int(b[0] - '0'), true
}
var n int
var sign bool
var i int
if len(b) > 0 && b[0] == '-' {
sign = true
i++
}
for ; i < len(b); i++ {
if b[i] < '0' || b[i] > '9' {
return 0, false
}
n = n*10 + int(b[i]-'0')
}
if sign {
n *= -1
}
return n, true
}
func (c *Conn) WriteArray(count int) {
c.buf.Write(resp.AppendArray(nil, count))
}
func (c *Conn) WriteBulkString(bulk string) {
c.buf.Write(resp.AppendBulkString(nil, bulk))
}
func (c *Conn) WriteString(str string) {
c.buf.Write(resp.AppendString(nil, str))
}
func (c *Conn) WriteInt(num int) {
c.buf.Write(resp.AppendInt(nil, int64(num)))
}
func (c *Conn) WriteNull() {
c.buf.Write(resp.AppendNull(nil))
}
func (c *Conn) Flush() error {
_, err := c.Conn.Write(c.buf.Bytes())
c.buf.Reset()
return err
}
func (c *Conn) ReadCommand() (resp.Command, error) {
data, err := c.Conn.Next(-1)
if err != nil {
return resp.Command{}, err
}
c.buf.Write(data)
cmds, _, err := resp.ReadCommands(c.buf.Bytes())
if err != nil {
return resp.Command{}, err
}
if len(cmds) > 0 {
cmd := cmds[0]
c.buf.Next(len(cmd.Raw))
return cmd, nil
}
return resp.Command{}, fmt.Errorf("no command")
}
func (c *Conn) WriteError(msg string) {
c.buf.Write(resp.AppendError(nil, msg))
}
type Options struct {
Multicore bool
LockOSThread bool
ReadBufferCap int
LB gnet.LoadBalancing
NumEventLoop int
ReusePort bool
Ticker bool
TCPKeepAlive int
TCPNoDelay gnet.TCPSocketOpt
SocketRecvBuffer int
SocketSendBuffer int
TLSConfig *tls.Config
}
func NewRedHub(
onOpened func(c *Conn) (out []byte, action Action),
onClosed func(c *Conn, err error) (action Action),
handler func(cmd resp.Command, out []byte) ([]byte, Action),
) *redHub {
return &redHub{
redHubBufMap: make(map[gnet.Conn]*connBuffer),
connSync: sync.RWMutex{},
onOpened: onOpened,
onClosed: onClosed,
handler: handler,
pubsub: NewPubSub(),
}
}
type redHub struct {
gnet.BuiltinEventEngine
eng gnet.Engine
onOpened func(c *Conn) (out []byte, action Action)
onClosed func(c *Conn, err error) (action Action)
handler func(cmd resp.Command, out []byte) ([]byte, Action)
redHubBufMap map[gnet.Conn]*connBuffer
connSync sync.RWMutex
pubsub *PubSub
}
type connBuffer struct {
buf bytes.Buffer
command []resp.Command
}
func (rs *redHub) OnBoot(eng gnet.Engine) gnet.Action {
rs.eng = eng
return gnet.None
}
func (rs *redHub) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) {
rs.connSync.Lock()
defer rs.connSync.Unlock()
rs.redHubBufMap[c] = new(connBuffer)
rs.onOpened(&Conn{Conn: c})
return
}
func (rs *redHub) OnClose(c gnet.Conn, err error) (action gnet.Action) {
rs.connSync.Lock()
defer rs.connSync.Unlock()
delete(rs.redHubBufMap, c)
rs.onClosed(&Conn{Conn: c}, err)
return gnet.None
}
func (rs *redHub) OnTraffic(c gnet.Conn) gnet.Action {
rs.connSync.RLock()
defer rs.connSync.RUnlock()
cb, ok := rs.redHubBufMap[c]
if !ok {
out := resp.AppendError(nil, "ERR Client is closed")
c.Write(out)
return gnet.Close
}
frame, _ := c.Next(-1)
cb.buf.Write(frame)
cmds, lastbyte, err := resp.ReadCommands(cb.buf.Bytes())
if err != nil {
out := resp.AppendError(nil, "ERR "+err.Error())
c.Write(out)
return gnet.None
}
cb.command = append(cb.command, cmds...)
cb.buf.Reset()
if len(lastbyte) == 0 {
var status Action
var out []byte
for len(cb.command) > 0 {
cmd := cb.command[0]
if len(cb.command) == 1 {
cb.command = nil
} else {
cb.command = cb.command[1:]
}
cmd.Conn = &Conn{Conn: c}
out, status = rs.handler(cmd, out)
c.Write(out)
switch status {
case Close:
return gnet.Close
}
}
} else {
cb.buf.Write(lastbyte)
}
return gnet.None
}
func ListenAndServe(addr string, options Options, rh *redHub) error {
opts := []gnet.Option{
gnet.WithMulticore(options.Multicore),
gnet.WithLockOSThread(options.LockOSThread),
gnet.WithReadBufferCap(options.ReadBufferCap),
gnet.WithLoadBalancing(options.LB),
gnet.WithNumEventLoop(options.NumEventLoop),
gnet.WithReusePort(options.ReusePort),
gnet.WithTicker(options.Ticker),
gnet.WithTCPKeepAlive(time.Duration(options.TCPKeepAlive) * time.Second),
gnet.WithTCPNoDelay(options.TCPNoDelay),
gnet.WithSocketRecvBuffer(options.SocketRecvBuffer),
gnet.WithSocketSendBuffer(options.SocketSendBuffer),
}
if options.TLSConfig != nil {
return gnettls.Run(rh, addr, options.TLSConfig, opts...)
}
return gnet.Run(rh, addr, opts...)
}
// PubSub related code
type PubSub struct {
mu sync.RWMutex
nextid uint64
initd bool
chans *btree.BTree
conns map[*Conn]*pubSubConn
}
func NewPubSub() *PubSub {
return &PubSub{
chans: btree.New(byEntry),
conns: make(map[*Conn]*pubSubConn),
}
}
type pubSubConn struct {
id uint64
mu sync.Mutex
conn *Conn
dconn *Conn
entries map[*pubSubEntry]bool
}
type pubSubEntry struct {
pattern bool
sconn *pubSubConn
channel string
}
func byEntry(a, b interface{}) bool {
aa := a.(*pubSubEntry)
bb := b.(*pubSubEntry)
if !aa.pattern && bb.pattern {
return true
}
if aa.pattern && !bb.pattern {
return false
}
if aa.channel < bb.channel {
return true
}
if aa.channel > bb.channel {
return false
}
var aid uint64
var bid uint64
if aa.sconn != nil {
aid = aa.sconn.id
}
if bb.sconn != nil {
bid = bb.sconn.id
}
return aid < bid
}
func (ps *PubSub) Subscribe(conn *Conn, channel string) {
ps.subscribe(conn, false, channel)
}
func (ps *PubSub) Psubscribe(conn *Conn, channel string) {
ps.subscribe(conn, true, channel)
}
func (ps *PubSub) Publish(channel, message string) int {
ps.mu.RLock()
defer ps.mu.RUnlock()
if !ps.initd {
return 0
}
var sent int
pivot := &pubSubEntry{pattern: false, channel: channel}
ps.chans.Ascend(pivot, func(item interface{}) bool {
entry := item.(*pubSubEntry)
if entry.channel != pivot.channel || entry.pattern != pivot.pattern {
return false
}
entry.sconn.writeMessage(entry.pattern, "", channel, message)
sent++
return true
})
pivot = &pubSubEntry{pattern: true}
ps.chans.Ascend(pivot, func(item interface{}) bool {
entry := item.(*pubSubEntry)
if match.Match(channel, entry.channel) {
entry.sconn.writeMessage(entry.pattern, entry.channel, channel, message)
sent++
}
return true
})
return sent
}
func (sconn *pubSubConn) writeMessage(pat bool, pchan, channel, msg string) {
sconn.mu.Lock()
defer sconn.mu.Unlock()
if pat {
sconn.dconn.WriteArray(4)
sconn.dconn.WriteBulkString("pmessage")
sconn.dconn.WriteBulkString(pchan)
sconn.dconn.WriteBulkString(channel)
sconn.dconn.WriteBulkString(msg)
} else {
sconn.dconn.WriteArray(3)
sconn.dconn.WriteBulkString("message")
sconn.dconn.WriteBulkString(channel)
sconn.dconn.WriteBulkString(msg)
}
sconn.dconn.Flush()
}
func (sconn *pubSubConn) bgrunner(ps *PubSub) {
defer func() {
ps.mu.Lock()
defer ps.mu.Unlock()
for entry := range sconn.entries {
ps.chans.Delete(entry)
}
delete(ps.conns, sconn.conn)
sconn.mu.Lock()
defer sconn.mu.Unlock()
sconn.dconn.Close()
}()
for {
cmd, err := sconn.dconn.ReadCommand()
if err != nil {
return
}
if len(cmd.Args) == 0 {
continue
}
switch strings.ToLower(string(cmd.Args[0])) {
case "psubscribe", "subscribe":
if len(cmd.Args) < 2 {
sconn.mu.Lock()
sconn.dconn.WriteError(fmt.Sprintf("ERR wrong number of arguments for '%s'", cmd.Args[0]))
sconn.dconn.Flush()
sconn.mu.Unlock()
continue
}
command := strings.ToLower(string(cmd.Args[0]))
for i := 1; i < len(cmd.Args); i++ {
if command == "psubscribe" {
ps.Psubscribe(sconn.conn, string(cmd.Args[i]))
} else {
ps.Subscribe(sconn.conn, string(cmd.Args[i]))
}
}
case "unsubscribe", "punsubscribe":
pattern := strings.ToLower(string(cmd.Args[0])) == "punsubscribe"
if len(cmd.Args) == 1 {
ps.unsubscribe(sconn.conn, pattern, true, "")
} else {
for i := 1; i < len(cmd.Args); i++ {
channel := string(cmd.Args[i])
ps.unsubscribe(sconn.conn, pattern, false, channel)
}
}
case "quit":
sconn.mu.Lock()
sconn.dconn.WriteString("OK")
sconn.dconn.Flush()
sconn.dconn.Close()
sconn.mu.Unlock()
return
case "ping":
var msg string
switch len(cmd.Args) {
case 1:
case 2:
msg = string(cmd.Args[1])
default:
sconn.mu.Lock()
sconn.dconn.WriteError(fmt.Sprintf("ERR wrong number of arguments for '%s'", cmd.Args[0]))
sconn.dconn.Flush()
sconn.mu.Unlock()
continue
}
sconn.mu.Lock()
sconn.dconn.WriteArray(2)
sconn.dconn.WriteBulkString("pong")
sconn.dconn.WriteBulkString(msg)
sconn.dconn.Flush()
sconn.mu.Unlock()
default:
sconn.mu.Lock()
sconn.dconn.WriteError(fmt.Sprintf("ERR Can't execute '%s': only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT are allowed in this context", cmd.Args[0]))
sconn.dconn.Flush()
sconn.mu.Unlock()
}
}
}
func (ps *PubSub) subscribe(conn *Conn, pattern bool, channel string) {
ps.mu.Lock()
defer ps.mu.Unlock()
if !ps.initd {
ps.conns = make(map[*Conn]*pubSubConn)
ps.chans = btree.New(byEntry)
ps.initd = true
}
sconn, ok := ps.conns[conn]
if !ok {
ps.nextid++
sconn = &pubSubConn{
id: ps.nextid,
conn: conn,
dconn: conn,
entries: make(map[*pubSubEntry]bool),
}
ps.conns[conn] = sconn
}
sconn.mu.Lock()
defer sconn.mu.Unlock()
entry := &pubSubEntry{
pattern: pattern,
channel: channel,
sconn: sconn,
}
ps.chans.Set(entry)
sconn.entries[entry] = true
sconn.dconn.WriteArray(3)
if pattern {
sconn.dconn.WriteBulkString("psubscribe")
} else {
sconn.dconn.WriteBulkString("subscribe")
}
sconn.dconn.WriteBulkString(channel)
var count int
for entry := range sconn.entries {
if entry.pattern == pattern {
count++
}
}
sconn.dconn.WriteInt(count)
sconn.dconn.Flush()
if !ok {
go sconn.bgrunner(ps)
}
}
func (ps *PubSub) unsubscribe(conn *Conn, pattern, all bool, channel string) {
ps.mu.Lock()
defer ps.mu.Unlock()
sconn := ps.conns[conn]
sconn.mu.Lock()
defer sconn.mu.Unlock()
removeEntry := func(entry *pubSubEntry) {
if entry != nil {
ps.chans.Delete(entry)
delete(sconn.entries, entry)
}
sconn.dconn.WriteArray(3)
if pattern {
sconn.dconn.WriteBulkString("punsubscribe")
} else {
sconn.dconn.WriteBulkString("unsubscribe")
}
if entry != nil {
sconn.dconn.WriteBulkString(entry.channel)
} else {
sconn.dconn.WriteNull()
}
var count int
for entry := range sconn.entries {
if entry.pattern == pattern {
count++
}
}
sconn.dconn.WriteInt(count)
}
if all {
var entries []*pubSubEntry
for entry := range sconn.entries {
if entry.pattern == pattern {
entries = append(entries, entry)
}
}
if len(entries) == 0 {
removeEntry(nil)
} else {
for _, entry := range entries {
removeEntry(entry)
}
}
} else {
for entry := range sconn.entries {
if entry.pattern == pattern && entry.channel == channel {
removeEntry(entry)
break
}
}
}
sconn.dconn.Flush()
}