-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
763 lines (719 loc) · 18.2 KB
/
server.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
// Package redcon implements a Redis compatible server framework
package newredis
import (
"bufio"
"errors"
"io"
"net"
"strconv"
"sync"
)
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")
)
type errProtocol struct {
msg string
}
func (err *errProtocol) Error() string {
return "Protocol error: " + err.msg
}
// Conn represents a client connection
type Conn interface {
// RemoteAddr returns the remote address of the client connection.
RemoteAddr() string
// Close closes the connection.
Close() error
// WriteError writes an error to the client.
WriteError(msg string)
// WriteString writes a string to the client.
WriteString(str string)
// WriteBulk writes bulk bytes to the client.
WriteBulk(bulk []byte)
// WriteBulkString writes a bulk string to the client.
WriteBulkString(bulk string)
// WriteInt writes an integer to the client.
WriteInt(num int)
// WriteInt64 writes a 64-but signed integer to the client.
WriteInt64(num int64)
// WriteArray writes an array header. You must then write addtional
// sub-responses to the client to complete the response.
// For example to write two strings:
//
// c.WriteArray(2)
// c.WriteBulk("item 1")
// c.WriteBulk("item 2")
WriteArray(count int)
// WriteNull writes a null to the client
WriteNull()
// WriteRaw writes raw data to the client.
WriteRaw(data []byte)
// Context returns a user-defined context
Context() interface{}
// SetContext sets a user-defined context
SetContext(v interface{})
// SetReadBuffer updates the buffer read size for the connection
SetReadBuffer(bytes int)
// Detach return a connection that is detached from the server.
// Useful for operations like PubSub.
//
// dconn := conn.Detach()
// go func(){
// defer dconn.Close()
// cmd, err := dconn.ReadCommand()
// if err != nil{
// fmt.Printf("read failed: %v\n", err)
// return
// }
// fmt.Printf("received command: %v", cmd)
// hconn.WriteString("OK")
// if err := dconn.Flush(); err != nil{
// fmt.Printf("write failed: %v\n", err)
// return
// }
// }()
Detach() DetachedConn
// ReadPipeline returns all commands in current pipeline, if any
// The commands are removed from the pipeline.
ReadPipeline() []Command
// PeekPipeline returns all commands in current pipeline, if any.
// The commands remain in the pipeline.
PeekPipeline() []Command
// NetConn returns the base net.Conn connection
NetConn() net.Conn
}
// NewServerNetworkType returns a new Redcon server. The network net must be
// a stream-oriented network: "tcp", "tcp4", "tcp6", "unix" or "unixpacket"
func NewServerNetwork(
config *Config,
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) *Server {
s := &Server{
conf: config,
accept: accept,
closed: closed,
conns: make(map[*conn]bool),
}
s.db = NewMemdb(s)
InitNewWal(s)
return s
}
// Close stops listening on the TCP address.
// Already Accepted connections will be closed.
func (s *Server) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.ln == nil {
return errors.New("not serving")
}
s.done = true
return s.ln.Close()
}
// ListenAndServe serves incoming connections.
func (s *Server) ListenAndServe() error {
return s.ListenServeAndSignal(nil)
}
// ListenAndServe creates a new server and binds to addr configured on "tcp" network net.
func ListenAndServe(conf *Config,
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
return ListenAndServeNetwork(conf, accept, closed)
}
// ListenAndServe creates a new server and binds to addr. The network net must be
// a stream-oriented network: "tcp", "tcp4", "tcp6", "unix" or "unixpacket"
func ListenAndServeNetwork(
conf *Config,
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
return NewServerNetwork(conf, accept, closed).ListenAndServe()
}
// ListenServeAndSignal serves incoming connections and passes nil or error
// when listening. signal can be nil.
func (s *Server) ListenServeAndSignal(signal chan error) error {
ln, err := net.Listen(s.conf.net, s.conf.laddr)
if err != nil {
if signal != nil {
signal <- err
}
return err
}
if signal != nil {
signal <- nil
}
s.mu.Lock()
s.ln = ln
s.mu.Unlock()
defer func() {
ln.Close()
func() {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.conns {
c.Close()
}
s.conns = nil
}()
}()
for {
lnconn, err := ln.Accept()
if err != nil {
s.mu.Lock()
done := s.done
s.mu.Unlock()
if done {
return nil
}
return err
}
c := &conn{conn: lnconn, addr: lnconn.RemoteAddr().String(),
wr: NewWriter(lnconn), rd: NewReader(lnconn)}
s.mu.Lock()
s.conns[c] = true
s.mu.Unlock()
if s.accept != nil && !s.accept(c) {
s.mu.Lock()
delete(s.conns, c)
s.mu.Unlock()
c.Close()
continue
}
go handle(s, c)
}
}
// handle manages the server connection.
func handle(s *Server, c *conn) {
var err error
defer func() {
if err != errDetached {
// do not close the connection when a detach is detected.
c.conn.Close()
}
func() {
// remove the conn from the server
s.mu.Lock()
defer s.mu.Unlock()
delete(s.conns, c)
if s.closed != nil {
if err == io.EOF {
err = nil
}
s.closed(c, err)
}
}()
}()
err = func() error {
// read commands and feed back to the client
for {
// read pipeline commands
cmds, err := c.rd.readCommands(nil)
if err != nil {
if err, ok := err.(*errProtocol); ok {
// All protocol errors should attempt a response to
// the client. Ignore write errors.
c.wr.WriteError("ERR " + err.Error())
c.wr.Flush()
}
return err
}
c.cmds = cmds
for len(c.cmds) > 0 {
cmd := c.cmds[0]
if len(c.cmds) == 1 {
c.cmds = nil
} else {
c.cmds = c.cmds[1:]
}
//s.handler(s,c, cmd)
DoCmd(s, c, cmd)
}
if c.detached {
// client has been detached
return errDetached
}
if c.closed {
return nil
}
if err := c.wr.Flush(); err != nil {
return err
}
}
}()
}
// conn represents a client connection
type conn struct {
conn net.Conn
wr *Writer
rd *Reader
addr string
ctx interface{}
detached bool
closed bool
cmds []Command
}
func (c *conn) Close() error {
c.wr.Flush()
c.closed = true
return c.conn.Close()
}
func (c *conn) Context() interface{} { return c.ctx }
func (c *conn) SetContext(v interface{}) { c.ctx = v }
func (c *conn) SetReadBuffer(n int) {}
func (c *conn) WriteString(str string) { c.wr.WriteString(str) }
func (c *conn) WriteBulk(bulk []byte) { c.wr.WriteBulk(bulk) }
func (c *conn) WriteBulkString(bulk string) { c.wr.WriteBulkString(bulk) }
func (c *conn) WriteInt(num int) { c.wr.WriteInt(num) }
func (c *conn) WriteInt64(num int64) { c.wr.WriteInt64(num) }
func (c *conn) WriteError(msg string) { c.wr.WriteError(msg) }
func (c *conn) WriteArray(count int) { c.wr.WriteArray(count) }
func (c *conn) WriteNull() { c.wr.WriteNull() }
func (c *conn) WriteRaw(data []byte) { c.wr.WriteRaw(data) }
func (c *conn) RemoteAddr() string { return c.addr }
func (c *conn) ReadPipeline() []Command {
cmds := c.cmds
c.cmds = nil
return cmds
}
func (c *conn) PeekPipeline() []Command {
return c.cmds
}
func (c *conn) NetConn() net.Conn {
return c.conn
}
// BaseWriter returns the underlying connection writer, if any
func BaseWriter(c Conn) *Writer {
if c, ok := c.(*conn); ok {
return c.wr
}
return nil
}
// DetachedConn represents a connection that is detached from the server
type DetachedConn interface {
// Conn is the original connection
Conn
// ReadCommand reads the next client command.
ReadCommand() (Command, error)
// Flush flushes any writes to the network.
Flush() error
}
// Detach removes the current connection from the server loop and returns
// a detached connection. This is useful for operations such as PubSub.
// The detached connection must be closed by calling Close() when done.
// All writes such as WriteString() will not be written to the client
// until Flush() is called.
func (c *conn) Detach() DetachedConn {
c.detached = true
cmds := c.cmds
c.cmds = nil
return &detachedConn{conn: c, cmds: cmds}
}
type detachedConn struct {
*conn
cmds []Command
}
// Flush writes and Write* calls to the client.
func (dc *detachedConn) Flush() error {
return dc.conn.wr.Flush()
}
// ReadCommand read the next command from the client.
func (dc *detachedConn) ReadCommand() (Command, error) {
if dc.closed {
return Command{}, errors.New("closed")
}
if len(dc.cmds) > 0 {
cmd := dc.cmds[0]
if len(dc.cmds) == 1 {
dc.cmds = nil
} else {
dc.cmds = dc.cmds[1:]
}
return cmd, nil
}
cmd, err := dc.rd.ReadCommand()
if err != nil {
return Command{}, err
}
return cmd, nil
}
// 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
}
// Server defines a server for clients for managing client connections.
type Server struct {
mu sync.Mutex
/*net string
laddr string*/
conf *Config
handler func(s *Server, conn Conn, cmd Command)
accept func(conn Conn) bool
closed func(conn Conn, err error)
conns map[*conn]bool
ln net.Listener
done bool
db *Memdb
w *Wal
}
// Writer allows for writing RESP messages.
type Writer struct {
w io.Writer
b []byte
}
// NewWriter creates a new RESP writer.
func NewWriter(wr io.Writer) *Writer {
return &Writer{
w: wr,
}
}
// WriteNull writes a null to the client
func (w *Writer) WriteNull() {
w.b = append(w.b, '$', '-', '1', '\r', '\n')
}
// WriteArray writes an array header. You must then write addtional
// sub-responses to the client to complete the response.
// For example to write two strings:
//
// c.WriteArray(2)
// c.WriteBulk("item 1")
// c.WriteBulk("item 2")
func (w *Writer) WriteArray(count int) {
w.b = append(w.b, '*')
w.b = strconv.AppendInt(w.b, int64(count), 10)
w.b = append(w.b, '\r', '\n')
}
// WriteBulk writes bulk bytes to the client.
func (w *Writer) WriteBulk(bulk []byte) {
w.b = append(w.b, '$')
w.b = strconv.AppendInt(w.b, int64(len(bulk)), 10)
w.b = append(w.b, '\r', '\n')
w.b = append(w.b, bulk...)
w.b = append(w.b, '\r', '\n')
}
// WriteBulkString writes a bulk string to the client.
func (w *Writer) WriteBulkString(bulk string) {
w.b = append(w.b, '$')
w.b = strconv.AppendInt(w.b, int64(len(bulk)), 10)
w.b = append(w.b, '\r', '\n')
w.b = append(w.b, bulk...)
w.b = append(w.b, '\r', '\n')
}
// Buffer returns the unflushed buffer. This is a copy so changes
// to the resulting []byte will not affect the writer.
func (w *Writer) Buffer() []byte {
return append([]byte(nil), w.b...)
}
// SetBuffer replaces the unflushed buffer with new bytes.
func (w *Writer) SetBuffer(raw []byte) {
w.b = w.b[:0]
w.b = append(w.b, raw...)
}
// Flush writes all unflushed Write* calls to the underlying writer.
func (w *Writer) Flush() error {
if _, err := w.w.Write(w.b); err != nil {
return err
}
w.b = w.b[:0]
return nil
}
// WriteError writes an error to the client.
func (w *Writer) WriteError(msg string) {
w.b = append(w.b, '-')
w.b = append(w.b, msg...)
w.b = append(w.b, '\r', '\n')
}
// WriteString writes a string to the client.
func (w *Writer) WriteString(msg string) {
w.b = append(w.b, '+')
w.b = append(w.b, msg...)
w.b = append(w.b, '\r', '\n')
}
// WriteInt writes an integer to the client.
func (w *Writer) WriteInt(num int) {
w.WriteInt64(int64(num))
}
// WriteInt64 writes a 64-bit signed integer to the client.
func (w *Writer) WriteInt64(num int64) {
w.b = append(w.b, ':')
w.b = strconv.AppendInt(w.b, num, 10)
w.b = append(w.b, '\r', '\n')
}
// WriteRaw writes raw data to the client.
func (w *Writer) WriteRaw(data []byte) {
w.b = append(w.b, data...)
}
// Reader represent a reader for RESP or telnet commands.
type Reader struct {
rd *bufio.Reader
buf []byte
start int
end int
cmds []Command
}
// NewReader returns a command reader which will read RESP or telnet commands.
func NewReader(rd io.Reader) *Reader {
return &Reader{
rd: bufio.NewReader(rd),
buf: make([]byte, 4096),
}
}
func parseInt(b []byte) (int, error) {
// shortcut atoi for 0-99. fails for negative numbers.
switch len(b) {
case 1:
if b[0] >= '0' && b[0] <= '9' {
return int(b[0] - '0'), nil
}
case 2:
if b[0] >= '0' && b[0] <= '9' && b[1] >= '0' && b[1] <= '9' {
return int(b[0]-'0')*10 + int(b[1]-'0'), nil
}
}
// fallback to standard library
n, err := strconv.ParseUint(string(b), 10, 64)
return int(n), err
}
func (rd *Reader) readCommands(leftover *int) ([]Command, error) {
var cmds []Command
b := rd.buf[rd.start:rd.end]
if rd.end-rd.start == 0 && len(rd.buf) > 4096 {
rd.buf = rd.buf[:4096]
rd.start = 0
rd.end = 0
}
if len(b) > 0 {
// we have data, yay!
// but is this enough data for a complete command? or multiple?
next:
switch b[0] {
default:
// just a plain text command
for i := 0; i < len(b); i++ {
if b[i] == '\n' {
var line []byte
if i > 0 && b[i-1] == '\r' {
line = b[:i-1]
} else {
line = b[:i]
}
var cmd Command
var quote bool
var quotech byte
var escape bool
outer:
for {
nline := make([]byte, 0, len(line))
for i := 0; i < len(line); i++ {
c := line[i]
if !quote {
if c == ' ' {
if len(nline) > 0 {
cmd.Args = append(cmd.Args, nline)
}
line = line[i+1:]
continue outer
}
if c == '"' || c == '\'' {
if i != 0 {
return nil, errUnbalancedQuotes
}
quotech = c
quote = true
line = line[i+1:]
continue outer
}
} else {
if escape {
escape = false
switch c {
case 'n':
c = '\n'
case 'r':
c = '\r'
case 't':
c = '\t'
}
} else if c == quotech {
quote = false
quotech = 0
cmd.Args = append(cmd.Args, nline)
line = line[i+1:]
if len(line) > 0 && line[0] != ' ' {
return nil, errUnbalancedQuotes
}
continue outer
} else if c == '\\' {
escape = true
continue
}
}
nline = append(nline, c)
}
if quote {
return nil, errUnbalancedQuotes
}
if len(line) > 0 {
cmd.Args = append(cmd.Args, line)
}
break
}
if len(cmd.Args) > 0 {
// convert this to resp command syntax
var wr Writer
wr.WriteArray(len(cmd.Args))
for i := range cmd.Args {
wr.WriteBulk(cmd.Args[i])
cmd.Args[i] = append([]byte(nil), cmd.Args[i]...)
}
cmd.Raw = wr.b
cmds = append(cmds, cmd)
}
b = b[i+1:]
if len(b) > 0 {
goto next
} else {
goto done
}
}
}
case '*':
// resp formatted command
marks := make([]int, 0, 16)
outer2:
for i := 1; i < len(b); i++ {
if b[i] == '\n' {
if b[i-1] != '\r' {
return nil, errInvalidMultiBulkLength
}
count, err := parseInt(b[1: i-1])
if err != nil || count <= 0 {
return nil, errInvalidMultiBulkLength
}
marks = marks[:0]
for j := 0; j < count; j++ {
// read bulk length
i++
if i < len(b) {
if b[i] != '$' {
return nil, &errProtocol{"expected '$', got '" +
string(b[i]) + "'"}
}
si := i
for ; i < len(b); i++ {
if b[i] == '\n' {
if b[i-1] != '\r' {
return nil, errInvalidBulkLength
}
size, err := parseInt(b[si+1: i-1])
if err != nil || size < 0 {
return nil, errInvalidBulkLength
}
if i+size+2 >= len(b) {
// not ready
break outer2
}
if b[i+size+2] != '\n' ||
b[i+size+1] != '\r' {
return nil, errInvalidBulkLength
}
i++
marks = append(marks, i, i+size)
i += size + 1
break
}
}
}
}
if len(marks) == count*2 {
var cmd Command
if rd.rd != nil {
// make a raw copy of the entire command when
// there's a underlying reader.
cmd.Raw = append([]byte(nil), b[:i+1]...)
} else {
// just assign the slice
cmd.Raw = b[:i+1]
}
cmd.Args = make([][]byte, len(marks)/2)
// slice up the raw command into the args based on
// the recorded marks.
for h := 0; h < len(marks); h += 2 {
cmd.Args[h/2] = cmd.Raw[marks[h]:marks[h+1]]
}
cmds = append(cmds, cmd)
b = b[i+1:]
if len(b) > 0 {
goto next
} else {
goto done
}
}
}
}
}
done:
rd.start = rd.end - len(b)
}
if leftover != nil {
*leftover = rd.end - rd.start
}
if len(cmds) > 0 {
return cmds, nil
}
if rd.rd == nil {
return nil, errIncompleteCommand
}
if rd.end == len(rd.buf) {
// at the end of the buffer.
if rd.start == rd.end {
// rewind the to the beginning
rd.start, rd.end = 0, 0
} else {
// must grow the buffer
newbuf := make([]byte, len(rd.buf)*2)
copy(newbuf, rd.buf)
rd.buf = newbuf
}
}
n, err := rd.rd.Read(rd.buf[rd.end:])
if err != nil {
return nil, err
}
rd.end += n
return rd.readCommands(leftover)
}
// ReadCommand reads the next command.
func (rd *Reader) ReadCommand() (Command, error) {
if len(rd.cmds) > 0 {
cmd := rd.cmds[0]
rd.cmds = rd.cmds[1:]
return cmd, nil
}
cmds, err := rd.readCommands(nil)
if err != nil {
return Command{}, err
}
rd.cmds = cmds
return rd.ReadCommand()
}
// Parse parses a raw RESP message and returns a command.
func Parse(raw []byte) (Command, error) {
rd := Reader{buf: raw, end: len(raw)}
var leftover int
cmds, err := rd.readCommands(&leftover)
if err != nil {
return Command{}, err
}
if leftover > 0 {
return Command{}, errTooMuchData
}
return cmds[0], nil
}