-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathclient.go
More file actions
233 lines (208 loc) · 4.65 KB
/
client.go
File metadata and controls
233 lines (208 loc) · 4.65 KB
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
package redis
import (
"bufio"
"bytes"
"errors"
"net"
"strconv"
"time"
)
const (
bufSize int = 4096
)
//* Common errors
var AuthError error = errors.New("authentication failed")
var LoadingError error = errors.New("server is busy loading dataset in memory")
var ParseError error = errors.New("parse error")
var PipelineQueueEmptyError error = errors.New("pipeline queue empty")
//* Client
// Client describes a Redis client.
type Client struct {
conn net.Conn
timeout time.Duration
reader *bufio.Reader
pending []*request
completed []*Reply
}
// Dial connects to the given Redis server with the given timeout.
func DialTimeout(network, addr string, timeout time.Duration) (*Client, error) {
// establish a connection
conn, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
c := new(Client)
c.conn = conn
c.timeout = timeout
c.reader = bufio.NewReaderSize(conn, bufSize)
return c, nil
}
// Dial connects to the given Redis server.
func Dial(network, addr string) (*Client, error) {
return DialTimeout(network, addr, time.Duration(0))
}
//* Public methods
// Close closes the connection.
func (c *Client) Close() error {
return c.conn.Close()
}
// Cmd calls the given Redis command.
func (c *Client) Cmd(cmd string, args ...interface{}) *Reply {
err := c.writeRequest(&request{cmd, args})
if err != nil {
return &Reply{Type: ErrorReply, Err: err}
}
return c.readReply()
}
// Append adds the given call to the pipeline queue.
// Use GetReply() to read the reply.
func (c *Client) Append(cmd string, args ...interface{}) {
c.pending = append(c.pending, &request{cmd, args})
}
// GetReply returns the reply for the next request in the pipeline queue.
// Error reply with PipelineQueueEmptyError is returned,
// if the pipeline queue is empty.
func (c *Client) GetReply() *Reply {
if len(c.completed) > 0 {
r := c.completed[0]
c.completed = c.completed[1:]
return r
}
c.completed = nil
if len(c.pending) == 0 {
return &Reply{Type: ErrorReply, Err: PipelineQueueEmptyError}
}
nreqs := len(c.pending)
err := c.writeRequest(c.pending...)
c.pending = nil
if err != nil {
return &Reply{Type: ErrorReply, Err: err}
}
r := c.readReply()
c.completed = make([]*Reply, nreqs-1)
for i := 0; i < nreqs-1; i++ {
c.completed[i] = c.readReply()
}
return r
}
//* Private methods
func (c *Client) setReadTimeout() {
if c.timeout != 0 {
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
}
}
func (c *Client) setWriteTimeout() {
if c.timeout != 0 {
c.conn.SetWriteDeadline(time.Now().Add(c.timeout))
}
}
func (c *Client) readReply() *Reply {
c.setReadTimeout()
return c.parse()
}
func (c *Client) writeRequest(requests ...*request) error {
c.setWriteTimeout()
_, err := c.conn.Write(createRequest(requests...))
if err != nil {
c.Close()
return err
}
return nil
}
func (c *Client) parse() (r *Reply) {
r = new(Reply)
b, err := c.reader.ReadBytes('\n')
if err != nil {
if t, ok := err.(*net.OpError); !ok || !t.Timeout() {
// close connection except timeout
c.Close()
}
r.Type = ErrorReply
r.Err = err
return
}
fb := b[0]
b = b[1 : len(b)-2] // get rid of the first byte and the trailing \r\n
switch fb {
case '-':
// error reply
r.Type = ErrorReply
if bytes.HasPrefix(b, []byte("LOADING")) {
r.Err = LoadingError
} else {
r.Err = errors.New(string(b))
}
case '+':
// status reply
r.Type = StatusReply
r.buf = b
case ':':
// integer reply
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
r.Type = ErrorReply
r.Err = ParseError
} else {
r.Type = IntegerReply
r.int = i
}
case '$':
// bulk reply
i, err := strconv.Atoi(string(b))
if err != nil {
r.Type = ErrorReply
r.Err = ParseError
} else {
if i == -1 {
// null bulk reply (key not found)
r.Type = NilReply
} else {
// bulk reply
ir := i + 2
br := make([]byte, ir)
rc := 0
for rc < ir {
n, err := c.reader.Read(br[rc:])
if err != nil {
c.Close()
r.Type = ErrorReply
r.Err = err
}
rc += n
}
r.Type = BulkReply
r.buf = br[0:i]
}
}
case '*':
// multi bulk reply
i, err := strconv.Atoi(string(b))
if err != nil {
r.Type = ErrorReply
r.Err = ParseError
} else {
switch {
case i == -1:
// null multi bulk
r.Type = NilReply
case i >= 0:
// multi bulk
// parse the replies recursively
r.Type = MultiReply
r.Elems = make([]*Reply, i)
for i := range r.Elems {
r.Elems[i] = c.parse()
}
default:
// invalid multi bulk reply
r.Type = ErrorReply
r.Err = ParseError
}
}
default:
// invalid reply
r.Type = ErrorReply
r.Err = ParseError
}
return
}