-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
354 lines (286 loc) · 6.6 KB
/
client.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
// Copyright 2014 Eryx <evorui аt gmаil dοt cοm>, All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package redisgo // import "github.com/lynkdb/redisgo"
import (
"bufio"
"bytes"
"errors"
"net"
"strconv"
"time"
)
var (
bufio_size = 4096
delim = []byte{'\r', '\n'}
err_parse = errors.New("parse error")
err_auth = errors.New("auth failed")
)
type client struct {
sock net.Conn
reader *bufio.Reader
copts *connOptions
}
func newClient(copts *connOptions) (*client, error) {
sock, err := net.Dial(copts.net, copts.addr)
if err != nil {
return nil, err
}
cli := &client{
sock: sock,
reader: bufio.NewReaderSize(sock, bufio_size),
copts: copts,
}
if copts.auth != "" {
cli.sock.SetDeadline(time.Now().Add(cli.copts.timeout))
if rs := cli.Cmd("auth", copts.auth); !rs.OK() {
return nil, err_auth
}
}
return cli, nil
}
func (c *client) Cmd(cmd string, args ...interface{}) *Result {
buf, err := send_buf_cmd(cmd, args)
if err != nil {
return newResult(ResultBadArgument, err)
}
if c.sock == nil {
sock, err := net.Dial(c.copts.net, c.copts.addr)
if err != nil {
return newResult(ResultNetworkException, err)
}
c.sock = sock
c.reader = bufio.NewReaderSize(sock, bufio_size)
if c.copts.auth != "" {
if rs := c.Cmd("auth", c.copts.auth); !rs.OK() {
return newResult(ResultNoAuth, err_auth)
}
}
}
c.sock.SetDeadline(time.Now().Add(c.copts.timeout))
if _, err = c.sock.Write(buf); err != nil {
return newResult(ResultNetworkException, err)
}
rs, err := c.cmd_parse()
if err != nil {
if ev, ok := err.(*net.OpError); ok && ev.Timeout() {
return newResult(ResultTimeout, err)
}
return newResult(ResultNetworkException, err)
}
return rs
}
func cmd_parse_read(reader *bufio.Reader, size int) ([]byte, error) {
bs := make([]byte, size)
ni := 0
for {
n, err := reader.Read(bs[ni:])
if err != nil {
return nil, err
}
if (ni + n) >= size {
break
}
ni += n
}
return bs, nil
}
func (c *client) cmd_parse() (*Result, error) {
bs, err := c.reader.ReadBytes('\n')
if err != nil {
return nil, err
}
if len(bs) < 4 {
return nil, err_parse
}
rs := newResult(0, nil)
switch bs[0] {
// Errors
case '-':
rs.data = bytes_clone(bs[1 : len(bs)-2])
rs.cap = 0
rs.Status = ResultError
// Simple Strings, Integers
case '+', ':':
rs.data = bytes_clone(bs[1 : len(bs)-2])
rs.cap = 1
// Bulk Strings
case '$':
size, err := strconv.Atoi(string(bs[1 : len(bs)-2]))
if err != nil || size < -1 {
return nil, err_parse
}
if size > 0 {
bs2, err := cmd_parse_read(c.reader, size+2)
if err != nil {
return nil, err
}
rs.data = bytes_clone(bs2[:len(bs2)-2])
rs.cap = 1
} else {
rs.cap = 0
}
// Array
case '*':
size, err := strconv.Atoi(string(bs[1 : len(bs)-2]))
if err != nil || size < -1 {
return nil, err_parse
}
rs.cap = size
if err = cmd_parse_array(rs, c.reader); err != nil {
return nil, err
}
// protocol error
default:
return nil, err_parse
}
if rs.Status == 0 {
if rs.cap == 0 || (len(rs.data) == 0 && len(rs.Items) == 0) {
rs.Status = ResultNotFound
} else if (rs.cap == 1 && len(rs.data) > 0) || len(rs.Items) >= rs.cap {
rs.Status = ResultOK
} else {
rs.Status = ResultUnknown
}
}
return rs, nil
}
func cmd_parse_array(rs *Result, reader *bufio.Reader) error {
for i := 0; i < rs.cap; i++ {
bs, err := reader.ReadBytes('\n')
if err != nil {
return err
}
if len(bs) < 4 {
return err_parse
}
switch bs[0] {
// Bulk Strings
case '$':
size, err := strconv.Atoi(string(bs[1 : len(bs)-2]))
if err != nil || size < -1 {
return err_parse
}
if size > 0 {
bs2, err := cmd_parse_read(reader, size+2)
if err != nil {
return err
}
rs.Items = append(rs.Items, &Result{
data: bytes_clone(bs2[:(len(bs2) - 2)]),
cap: 1,
})
} else {
rs.Items = append(rs.Items, &Result{
cap: 0,
})
}
// Array
case '*':
size, err := strconv.Atoi(string(bs[1 : len(bs)-2]))
if err != nil || size < -1 {
return err_parse
}
rs2 := &Result{cap: size}
if size > 0 {
if err := cmd_parse_array(rs2, reader); err != nil {
return err
}
}
rs.Items = append(rs.Items, rs2)
// protocol error
default:
return err_parse
}
}
return nil
}
func (c *client) Close() error {
if c.sock != nil {
c.sock.Close()
c.sock = nil
}
return nil
}
func send_buf_cmd(cmd string, args []interface{}) ([]byte, error) {
var buf bytes.Buffer
buf.WriteByte('*')
buf.Write([]byte(strconv.Itoa(len(args) + 1)))
buf.Write(delim)
send_buf_ss(&buf, &cmd)
for _, arg := range args {
var s string
switch argt := arg.(type) {
case []byte:
send_buf_bs(&buf, argt)
continue
case string:
s = argt
case int:
s = strconv.FormatInt(int64(argt), 10)
case int8:
s = strconv.FormatInt(int64(argt), 10)
case int16:
s = strconv.FormatInt(int64(argt), 10)
case int32:
s = strconv.FormatInt(int64(argt), 10)
case int64:
s = strconv.FormatInt(argt, 10)
case uint:
s = strconv.FormatUint(uint64(argt), 10)
case uint8:
s = strconv.FormatUint(uint64(argt), 10)
case uint16:
s = strconv.FormatUint(uint64(argt), 10)
case uint32:
s = strconv.FormatUint(uint64(argt), 10)
case uint64:
s = strconv.FormatUint(argt, 10)
case float32:
s = strconv.FormatFloat(float64(argt), 'f', -1, 32)
case float64:
s = strconv.FormatFloat(argt, 'f', -1, 64)
case bool:
if argt {
s = "1"
} else {
s = "0"
}
case nil:
s = ""
default:
return []byte{}, errors.New("bad arguments")
}
send_buf_ss(&buf, &s)
}
return buf.Bytes(), nil
}
func send_buf_bs(buf *bytes.Buffer, data []byte) {
buf.WriteByte('$')
buf.WriteString(strconv.FormatInt(int64(len(data)), 10))
buf.Write(delim)
buf.Write(data)
buf.Write(delim)
}
func send_buf_ss(buf *bytes.Buffer, data *string) {
buf.WriteByte('$')
buf.WriteString(strconv.FormatInt(int64(len(*data)), 10))
buf.Write(delim)
buf.WriteString(*data)
buf.Write(delim)
}
func bytes_clone(src []byte) []byte {
dst := make([]byte, len(src))
copy(dst, src)
return dst
}