-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
327 lines (291 loc) · 8.72 KB
/
redis.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
// Package redis demonstrates the usage of the gomme package to parse Redis'
// [RESP protocol] messages.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
package redis
import (
"errors"
"fmt"
"github.com/flowdev/comb/cmb"
. "github.com/flowdev/comb/cute"
"strconv"
"strings"
"github.com/flowdev/comb"
)
// ParseRESPMessage parses a Redis' [RESP protocol] message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
func ParseRESPMessage(input string) (RESPMessage, error) {
if len(input) < 3 {
return RESPMessage{}, fmt.Errorf("malformed message %s; reason: %w", input, ErrMessageTooShort)
}
if !isValidMessageKind(MessageKind(input[0])) {
return RESPMessage{}, fmt.Errorf("malformed message %s; reason: %w %c", input, ErrInvalidPrefix, input[0])
}
if input[len(input)-2] != '\r' || input[len(input)-1] != '\n' {
return RESPMessage{}, fmt.Errorf("malformed message %s; reason: %w", input, ErrInvalidSuffix)
}
parser := FirstSuccessful(
SimpleString(),
Error(),
Integer(),
BulkString(),
Array(),
)
return comb.RunOnString(input, parser)
}
// ErrMessageTooShort is returned when a message is too short to be valid.
// A [RESP protocol] message is at least 3 characters long: the message kind
// prefix, the message content (which can be empty), and the gomme.CRLF suffix.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
var ErrMessageTooShort = errors.New("message too short")
// ErrInvalidPrefix is returned when a message kind prefix is not recognized.
// Valid [RESP Protocol] message kind prefixes are "+", "-", ":", and "$".
//
// [RESP Protocol]: https://redis.io/docs/reference/protocol-spec/
var ErrInvalidPrefix = errors.New("invalid message prefix")
// ErrInvalidSuffix is returned when a message suffix is not recognized.
// Every [RESP protocol] message ends with a gomme.CRLF.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
var ErrInvalidSuffix = errors.New("invalid message suffix")
// RESPMessage is a parsed Redis' [RESP protocol] message.
//
// It can hold either a simple string, an error, an integer, a bulk string,
// or an array. The kind of the message is available in the Kind field.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type RESPMessage struct {
Kind MessageKind
SimpleString *SimpleStringMessage
Error *ErrorStringMessage
Integer *IntegerMessage
BulkString *BulkStringMessage
Array *ArrayMessage
}
// MessageKind is the kind of a Redis' [RESP protocol] message.
type MessageKind string
// The many different kinds of Redis' [RESP protocol] messages map
// to their respective protocol message's prefixes.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
const (
SimpleStringKind MessageKind = "+"
ErrorKind MessageKind = "-"
IntegerKind MessageKind = ":"
BulkStringKind MessageKind = "$"
ArrayKind MessageKind = "*"
InvalidKind MessageKind = "?"
)
// SimpleStringMessage is a simple string message parsed from a Redis'
// [RESP protocol] message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type SimpleStringMessage struct {
Content string
}
// SimpleString is a parser for Redis' RESP protocol simple strings.
//
// Simple strings are strings that are not expected to contain newlines.
// Simple strings start with a "+" character, and end with a gomme.CRLF.
//
// Once parsed, the content of the simple string is available in the
// simpleString field of the result's RESPMessage.
func SimpleString() comb.Parser[RESPMessage] {
mapFn := func(message string) (RESPMessage, error) {
if strings.ContainsAny(message, "\r\n") {
return RESPMessage{}, fmt.Errorf("malformed simple string: %s", message)
}
return RESPMessage{
Kind: SimpleStringKind,
SimpleString: &SimpleStringMessage{
Content: message,
},
}, nil
}
return cmb.Prefixed(
cmb.String(string(SimpleStringKind)),
cmb.Map(cmb.UntilString("\r\n"), mapFn),
)
}
// ErrorStringMessage is a parsed error string message from a Redis'
// [RESP protocol] message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type ErrorStringMessage struct {
Kind string
Message string
}
// Error is a parser for Redis' RESP protocol errors.
//
// Errors are strings that start with a "-" character, and end with a gomme.CRLF.
//
// The error message is available in the Error field of the result's
// RESPMessage.
func Error() comb.Parser[RESPMessage] {
mapFn := func(message string) (RESPMessage, error) {
if strings.ContainsAny(message, "\r\n") {
return RESPMessage{}, fmt.Errorf("malformed error string: %s", message)
}
return RESPMessage{
Kind: ErrorKind,
Error: &ErrorStringMessage{
Kind: "ERR",
Message: message,
},
}, nil
}
return cmb.Prefixed(
cmb.String(string(ErrorKind)),
cmb.Map(cmb.UntilString("\r\n"), mapFn),
)
}
// IntegerMessage is a parsed integer message from a Redis' [RESP protocol]
// message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type IntegerMessage struct {
Value int
}
// Integer is a parser for Redis' RESP protocol integers.
//
// Integers are signed numerical values represented as string messages
// that start with a ":" character, and end with a gomme.CRLF.
//
// The integer value is available in the IntegerMessage field of the result's
// RESPMessage.
func Integer() comb.Parser[RESPMessage] {
mapFn := func(message string) (RESPMessage, error) {
value, err := strconv.Atoi(message)
if err != nil {
return RESPMessage{}, err
}
return RESPMessage{
Kind: IntegerKind,
Integer: &IntegerMessage{
Value: value,
},
}, nil
}
return cmb.Prefixed(
cmb.String(string(IntegerKind)),
cmb.Map(cmb.UntilString("\r\n"), mapFn),
)
}
// BulkStringMessage is a parsed bulk string message from a Redis' [RESP protocol]
// message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type BulkStringMessage struct {
Data []byte
}
// BulkString is a parser for Redis' RESP protocol bulk strings.
//
// Bulk strings are binary-safe strings up to 512MB in size.
// Bulk strings start with a "$" character, and end with a gomme.CRLF.
//
// The bulk string's data is available in the BulkString field of the result's
// RESPMessage.
func BulkString() comb.Parser[RESPMessage] {
mapFn := func(length int64, message string) (RESPMessage, error) {
if length < 0 {
if length < -1 {
return RESPMessage{}, fmt.Errorf(
"unable to parse bulk string; "+
"reason: negative length %d",
length,
)
}
if length == -1 && len(message) != 0 {
return RESPMessage{}, fmt.Errorf(
"malformed bulkstring: declared message size -1, and actual size differ %d",
len(message),
)
}
} else if int64(len(message)) != length {
return RESPMessage{}, fmt.Errorf(
"malformed bulkstring: declared message size %d, and actual size differ %d; message: %q",
length, len(message), message,
)
}
return RESPMessage{
Kind: BulkStringKind,
BulkString: &BulkStringMessage{
Data: []byte(message),
},
}, nil
}
return cmb.Map2(
sizePrefix(cmb.String(string(BulkStringKind))),
cmb.Optional(
cmb.UntilString("\r\n"),
),
mapFn,
)
}
// ArrayMessage is a parsed array message from a Redis' [RESP protocol] message.
//
// [RESP protocol]: https://redis.io/docs/reference/protocol-spec/
type ArrayMessage struct {
Elements []RESPMessage
}
// Array is a parser for Redis' RESP protocol arrays.
//
// Arrays are sequences of RESP messages.
// Arrays start with a "*" character, and end with a gomme.CRLF.
//
// The array's messages are available in the Array field of the result's
// RESPMessage.
func Array() comb.Parser[RESPMessage] {
mapFn := func(size int64, message []RESPMessage) (RESPMessage, error) {
if int(size) == -1 {
if len(message) != 0 {
return RESPMessage{}, fmt.Errorf(
"malformed array: declared message size -1, and actual size differ %d",
len(message),
)
}
} else {
if len(message) != int(size) {
return RESPMessage{}, fmt.Errorf(
"malformed array: declared message size %d, and actual size differ %d",
size,
len(message),
)
}
}
return RESPMessage{
Kind: ArrayKind,
Array: &ArrayMessage{
Elements: message,
},
}, nil
}
return cmb.Map2(
sizePrefix(cmb.String(string(ArrayKind))),
cmb.Many0(
FirstSuccessful(
SimpleString(),
Error(),
Integer(),
BulkString(),
),
),
mapFn,
)
}
func sizePrefix(prefix comb.Parser[string]) comb.Parser[int64] {
return cmb.Delimited(
prefix,
cmb.Int64(true, 10),
cmb.CRLF(),
)
}
func isValidMessageKind(kind MessageKind) bool {
return kind == SimpleStringKind ||
kind == ErrorKind ||
kind == IntegerKind ||
kind == BulkStringKind ||
kind == ArrayKind
}