-
Notifications
You must be signed in to change notification settings - Fork 18
/
resp.go
323 lines (297 loc) · 8.13 KB
/
resp.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
// Tideland Go Library - Redis Client - resp
//
// Copyright (C) 2009-2017 Frank Mueller / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package redis
//--------------------
// IMPORTS
//--------------------
import (
"bufio"
"fmt"
"io"
"net"
"strconv"
"github.com/tideland/golib/errors"
)
//--------------------
// respONSE
//--------------------
// responseKind classifies a response of Redis.
type responseKind int
const (
receivingError responseKind = iota
timeoutError
statusResponse
errorResponse
integerResponse
bulkResponse
nullBulkResponse
arrayResponse
)
var responseKindDescr = map[responseKind]string{
receivingError: "receiving error",
timeoutError: "timeout error",
statusResponse: "status",
errorResponse: "error",
integerResponse: "integer",
bulkResponse: "bulk",
nullBulkResponse: "null-bulk",
arrayResponse: "array",
}
// response contains one Redis response.
type response struct {
kind responseKind
length int
data []byte
err error
}
// value returns the data as value.
func (r *response) value() Value {
return Value(r.data)
}
// errorValue returns the error as value.
func (r *response) errorValue() Value {
errdata := []byte(r.err.Error())
return Value(errdata)
}
// String creates a string representation of the response.
func (r *response) String() string {
descr := responseKindDescr[r.kind]
return fmt.Sprintf("RESPONSE (Kind: %s / Length: %d / Value: %v / Error: %v)", descr, r.length, r.value(), r.err)
}
//--------------------
// REDIS SERIALIZATION PROTOCOL
//--------------------
// resp implements the Redis Serialization Protocol.
type resp struct {
database *Database
conn net.Conn
reader *bufio.Reader
cmd string
}
// newResp establishes a connection to a Redis database
// based on the configuration of the passed database
// configuration.
func newResp(db *Database) (*resp, error) {
// Dial the database and create the protocol instance.
conn, err := net.DialTimeout(db.network, db.address, db.timeout)
if err != nil {
return nil, errors.Annotate(err, ErrConnectionEstablishing, errorMessages)
}
r := &resp{
database: db,
conn: conn,
reader: bufio.NewReader(conn),
}
return r, nil
}
// sendCommand sends a command and possible arguments to the server.
func (r *resp) sendCommand(cmd string, args ...interface{}) error {
r.cmd = cmd
lengthPart := r.buildLengthPart(args)
cmdPart := r.buildValuePart(cmd)
argsPart := r.buildArgumentsPart(args)
packet := join(lengthPart, cmdPart, argsPart)
_, err := r.conn.Write(packet)
if err != nil {
return errors.Annotate(err, ErrConnectionBroken, errorMessages, "send "+r.cmd)
}
return nil
}
// receiveResponse retrieves a response from the server.
func (r *resp) receiveResponse() *response {
// Receive first line.
line, err := r.reader.ReadBytes('\n')
if err != nil {
rerr := errors.Annotate(err, ErrConnectionBroken, errorMessages, "receive after "+r.cmd)
return &response{receivingError, 0, nil, rerr}
}
content := line[1 : len(line)-2]
// First byte defines kind.
switch line[0] {
case '+':
// Status response.
return &response{statusResponse, 0, line[:len(line)-2], nil}
case '-':
// Error response.
return &response{errorResponse, 0, line[:len(line)-2], nil}
case ':':
// Integer response.
return &response{integerResponse, 0, content, nil}
case '$':
// Bulk response or null bulk response.
count, err := strconv.Atoi(string(content))
if err != nil {
return &response{receivingError, 0, nil, errors.Annotate(err, ErrServerResponse, errorMessages)}
}
if count == -1 {
// Null bulk response.
return &response{nullBulkResponse, 0, nil, nil}
}
// Receive the bulk data.
toRead := count + 2
buffer := make([]byte, toRead)
n, err := io.ReadFull(r.reader, buffer)
if err != nil {
return &response{receivingError, 0, nil, err}
}
if n < toRead {
return &response{receivingError, 0, nil, errors.New(ErrServerResponse, errorMessages)}
}
return &response{bulkResponse, 0, buffer[0:count], nil}
case '*':
// Array reply. Check for timeout.
length, err := strconv.Atoi(string(content))
if err != nil {
return &response{receivingError, 0, nil, errors.Annotate(err, ErrServerResponse, errorMessages)}
}
if length == -1 {
// Timeout.
return &response{timeoutError, 0, nil, nil}
}
return &response{arrayResponse, length, nil, nil}
}
return &response{receivingError, 0, nil, errors.New(ErrInvalidResponse, errorMessages, string(line))}
}
// receiveResultSet receives all responses and converts them into a result set.
func (r *resp) receiveResultSet() (*ResultSet, error) {
defer func() { r.cmd = "-none-" }()
result := newResultSet()
current := result
for {
response := r.receiveResponse()
switch response.kind {
case receivingError:
return nil, response.err
case timeoutError:
return nil, errors.New(ErrTimeout, errorMessages)
case statusResponse, errorResponse, integerResponse, bulkResponse, nullBulkResponse:
current.append(response.value())
case arrayResponse:
switch {
case current == result && current.Len() == 0:
current.length = response.length
case !current.allReceived():
next := newResultSet()
next.parent = current
current.append(next)
current = next
current.length = response.length
}
}
// Check if all values are received.
current = current.nextResultSet()
if current == nil {
return result, nil
}
}
}
// buildLengthPart creates the length part of a command.
func (r *resp) buildLengthPart(args []interface{}) []byte {
length := 1
for _, arg := range args {
switch typedArg := arg.(type) {
case valuer:
length += typedArg.Len()
case Hash:
length += typedArg.Len() * 2
case Hashable:
length += typedArg.Len() * 2
default:
length++
}
}
return join("*", length, "\r\n")
}
// buildValuePart creates one value part of a command.
func (r *resp) buildValuePart(value interface{}) []byte {
var raw []byte
if v, ok := value.(Value); ok {
raw = []byte(v)
} else {
raw = valueToBytes(value)
}
return join("$", len(raw), "\r\n", raw, "\r\n")
}
// buildArgumentsPart creates the the arguments parts of a command.
func (r *resp) buildArgumentsPart(args []interface{}) []byte {
buildValuesPart := func(vs valuer) []byte {
tmp := []byte{}
for _, value := range vs.Values() {
tmp = append(tmp, r.buildValuePart(value)...)
}
return tmp
}
buildHashPart := func(h Hash) []byte {
tmp := []byte{}
for key, value := range h {
tmp = append(tmp, r.buildValuePart(key)...)
tmp = append(tmp, r.buildValuePart(value)...)
}
return tmp
}
tmp := []byte{}
part := []byte{}
for _, arg := range args {
switch typedArg := arg.(type) {
case valuer:
part = buildValuesPart(typedArg)
case Hash:
part = buildHashPart(typedArg)
case Hashable:
part = buildHashPart(typedArg.GetHash())
default:
part = r.buildValuePart(arg)
}
tmp = append(tmp, part...)
}
return tmp
}
// authenticate authenticates against the server if configured.
func (r *resp) authenticate() error {
if r.database.password != "" {
err := r.sendCommand("auth", r.database.password)
if err != nil {
return errors.Annotate(err, ErrAuthenticate, errorMessages)
}
result, err := r.receiveResultSet()
if err != nil {
return errors.Annotate(err, ErrAuthenticate, errorMessages)
}
value, err := result.ValueAt(0)
if err != nil {
return errors.Annotate(err, ErrAuthenticate, errorMessages)
}
if !value.IsOK() {
return errors.New(ErrAuthenticate, errorMessages)
}
}
return nil
}
// selectDatabase selects the database.
func (r *resp) selectDatabase() error {
err := r.sendCommand("select", r.database.index)
if err != nil {
return errors.Annotate(err, ErrSelectDatabase, errorMessages)
}
result, err := r.receiveResultSet()
if err != nil {
return errors.Annotate(err, ErrSelectDatabase, errorMessages)
}
value, err := result.ValueAt(0)
if err != nil {
return errors.Annotate(err, ErrSelectDatabase, errorMessages)
}
if !value.IsOK() {
return errors.New(ErrSelectDatabase, errorMessages)
}
return nil
}
// close ends the connection to Redis.
func (r *resp) close() error {
return r.conn.Close()
}
// EOF