forked from simonklee/godis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
godis.go
343 lines (276 loc) · 7.14 KB
/
godis.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
// package godis implements a client for Redis with support
// for all commands and features such as transactions and
// pubsub.
package godis
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"strings"
)
type ReaderWriter interface {
write(b []byte) (*conn, error)
read(c *conn) *Reply
sync() *Sync
}
type Client struct {
Rw ReaderWriter
}
type PipeClient struct {
*Client
}
type Sync struct {
Addr string
Db int
Password string
net string
pool *pool
}
type Pipe struct {
*Sync
conn *conn
b *bytes.Buffer
appendMode bool
transaction bool
replyCount int
}
type Sub struct {
c *Sync
conn *conn
subscribed bool
Messages chan *Message
}
func New(netaddr string, db int, password string) *Client {
return &Client{newSync(netaddr, db, password)}
}
// New returns a new Sync given a net address, redis db and password.
// nettaddr should be formatted using "net:addr", where ":" is acting as a
// separator. E.g. "unix:/path/to/redis.sock", "tcp:127.0.0.1:12345" or use an
// empty string for redis default.
func newSync(netaddr string, db int, password string) *Sync {
if netaddr == "" {
netaddr = "tcp:127.0.0.1:6379"
}
na := strings.SplitN(netaddr, ":", 2)
return &Sync{Addr: na[1], Db: db, Password: password, net: na[0], pool: newPool()}
}
// PipeClient include support for MULTI/EXEC operations.
// It implements Exec() which executes all buffered
// commands. Set transaction to true to wrap buffered commands inside
// MULTI .. EXEC block. PipeClient is not thread-safe.
func NewPipeClient(netaddr string, db int, password string) *PipeClient {
s := newSync(netaddr, db, password)
p := &Pipe{s, nil, new(bytes.Buffer), true, false, 0}
c := &Client{p}
return &PipeClient{c}
}
// Uses the connection settings from a existing client to create a new PipeClient
func NewPipeClientFromClient(c *Client) *PipeClient {
s := c.Rw.sync()
netaddr := s.net + ":" + s.Addr
return NewPipeClient(netaddr, s.Db, s.Password)
}
func (p *PipeClient) pipe() *Pipe {
v, _ := p.Rw.(*Pipe)
return v
}
func NewSub(addr string, db int, password string) *Sub {
return &Sub{c: newSync(addr, db, password)}
}
// rw interface
func (c *Sync) read(conn *conn) *Reply {
r := conn.readReply()
if r.Err == io.EOF {
conn = nil
}
c.pool.push(conn)
return r
}
func (c *Sync) write(cmd []byte) (conn *conn, err error) {
if conn, err = c.getConn(); err != nil {
return nil, err
}
if _, err = conn.w.Write(cmd); err != nil {
c.pool.push(conn)
return nil, err
}
conn.w.Flush()
return conn, err
}
func (c *Sync) sync() *Sync {
return c
}
// extra methods on sync
func (c *Sync) getConn() (*conn, error) {
cc := c.pool.pop()
if cc != nil {
return cc, nil
}
return newConn(c.net, c.Addr, c.Db, c.Password)
}
// pipe interface implementation
func (p *Pipe) read(conn *conn) *Reply {
if p.appendMode {
return &Reply{}
}
if p.b.Len() > 0 {
if logCmd {
log.Printf("%d bytes were written to socket\n", p.b.Len())
}
p.conn.w.Write(p.b.Bytes())
p.conn.w.Flush()
p.b.Reset()
}
reply := conn.readReply()
if p.count() == 0 {
p.free()
}
return reply
}
func (p *Pipe) write(cmd []byte) (*conn, error) {
if p.conn == nil {
if c, err := p.getConn(); err != nil {
return nil, err
} else {
p.conn = c
}
}
if n, _ := p.b.Write(cmd); n != len(cmd) {
p.free()
return nil, errors.New("Writing to command buffer failed")
}
p.replyCount++
p.appendMode = true
return p.conn, nil
}
// read a reply from the socket if we are expecting it.
func (p *Pipe) getReply() *Reply {
if p.count() == 0 {
p.appendMode = true
p.transaction = false
return &Reply{Err: errors.New("No replies expected from conn")}
}
p.replyCount--
p.appendMode = false
return p.read(p.conn)
}
// retrieve the number of replies available
func (p *Pipe) count() int {
return p.replyCount
}
func (p *Pipe) free() {
p.pool.push(p.conn)
p.conn = nil
p.appendMode = true
}
func (s *Sub) read(conn *conn) *Reply {
return s.conn.readReply()
}
func (s *Sub) write(cmd []byte) (*conn, error) {
var err error
if s.conn == nil {
if c, err := s.c.getConn(); err != nil {
return nil, err
} else {
s.conn = c
}
}
if _, err = s.conn.w.Write(cmd); err != nil {
s.Close()
return nil, err
}
s.conn.w.Flush()
return s.conn, nil
}
func (s *Sub) sync() *Sync {
return s.c
}
func (s *Sub) listen() {
if s.conn == nil {
return
}
for {
r := s.read(s.conn)
if r.Err != nil {
go s.free()
return
}
if m := r.Message(); m != nil {
s.Messages <- m
}
}
}
func (s *Sub) subscribe() {
s.subscribed = true
s.Messages = make(chan *Message, 64)
go s.listen()
}
// Free the connection and close the chan
func (s *Sub) Close() {
s.conn.rwc.Close()
}
func (s *Sub) free() {
s.conn = nil
s.c.pool.push(nil)
s.subscribed = false
close(s.Messages)
}
// Methods which take ReaderWriter interface
func sendGen(rw ReaderWriter, readResp bool, retry int, args [][]byte) (r *Reply) {
c, err := rw.write(buildCmd(args))
r = &Reply{conn: c, Err: err}
defer func() {
// if connection was closed by the remote host we try to re-run the cmd
if retry > 0 && r.Err == io.EOF {
retry--
r = sendGen(rw, readResp, retry, args)
}
}()
if r.Err != nil {
return
}
if readResp {
return rw.read(c)
}
return
}
// writes a command a and returns single the Reply object
func Send(rw ReaderWriter, args ...[]byte) *Reply {
return sendGen(rw, true, MaxClientConn, args)
}
// uses reflection to create a bytestring of the name and args parameters,
// then calls Send()
func SendIface(rw ReaderWriter, name string, args ...interface{}) *Reply {
buf := make([][]byte, len(args)+1)
buf[0] = []byte(name)
for i, arg := range args {
switch v := arg.(type) {
case []byte:
buf[i+1] = v
case string:
buf[i+1] = []byte(v)
default:
buf[i+1] = []byte(fmt.Sprint(arg))
}
}
return sendGen(rw, true, MaxClientConn, buf)
}
func strToBytes(name string, args []string) [][]byte {
buf := make([][]byte, len(args)+1)
buf[0] = []byte(name)
for i, arg := range args {
buf[i+1] = []byte(arg)
}
return buf
}
func appendSendStr(rw ReaderWriter, name string, args ...string) *Reply {
buf := strToBytes(name, args)
return sendGen(rw, false, MaxClientConn, buf)
}
// creates a bytestring of the name and args parameters, then calls Send()
func SendStr(rw ReaderWriter, name string, args ...string) *Reply {
buf := strToBytes(name, args)
return sendGen(rw, true, MaxClientConn, buf)
}