/
memcache.go
280 lines (248 loc) · 6.75 KB
/
memcache.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
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package memcache
import (
"bufio"
"fmt"
"io"
"net"
"strconv"
"strings"
)
type Connection struct {
conn net.Conn
buffered bufio.ReadWriter
}
type Result struct {
Key string
Value []byte
Flags uint16
Cas uint64
}
func Connect(address string) (conn *Connection, err error) {
var network string
if strings.Contains(address, "/") {
network = "unix"
} else {
network = "tcp"
}
var nc net.Conn
nc, err = net.Dial(network, address)
if err != nil {
return nil, err
}
return newConnection(nc), nil
}
func newConnection(nc net.Conn) *Connection {
return &Connection{
conn: nc,
buffered: *bufio.NewReadWriter(
bufio.NewReader(nc),
bufio.NewWriter(nc),
),
}
}
func (mc *Connection) Close() {
mc.conn.Close()
mc.conn = nil
}
func (mc *Connection) IsClosed() bool {
return mc.conn == nil
}
func (mc *Connection) Get(keys ...string) (results []Result, err error) {
defer handleError(&err)
results = mc.get("get", keys)
return
}
func (mc *Connection) Gets(keys ...string) (results []Result, err error) {
defer handleError(&err)
results = mc.get("gets", keys)
return
}
func (mc *Connection) Set(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) {
defer handleError(&err)
return mc.store("set", key, flags, timeout, value, 0), nil
}
func (mc *Connection) Add(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) {
defer handleError(&err)
return mc.store("add", key, flags, timeout, value, 0), nil
}
func (mc *Connection) Replace(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) {
defer handleError(&err)
return mc.store("replace", key, flags, timeout, value, 0), nil
}
func (mc *Connection) Append(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) {
defer handleError(&err)
return mc.store("append", key, flags, timeout, value, 0), nil
}
func (mc *Connection) Prepend(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) {
defer handleError(&err)
return mc.store("prepend", key, flags, timeout, value, 0), nil
}
func (mc *Connection) Cas(key string, flags uint16, timeout uint64, value []byte, cas uint64) (stored bool, err error) {
defer handleError(&err)
return mc.store("cas", key, flags, timeout, value, cas), nil
}
func (mc *Connection) Delete(key string) (deleted bool, err error) {
defer handleError(&err)
// delete <key> [<time>] [noreply]\r\n
mc.writestrings("delete ", key, "\r\n")
reply := mc.readline()
if strings.Contains(reply, "ERROR") {
panic(NewMemcacheError("Server error"))
}
return strings.HasPrefix(reply, "DELETED"), nil
}
//This purges the entire cache.
func (mc *Connection) FlushAll() (err error) {
defer handleError(&err)
// flush_all [delay] [noreply]\r\n
mc.writestrings("flush_all\r\n")
response := mc.readline()
if !strings.Contains(response, "OK") {
panic(NewMemcacheError(fmt.Sprintf("Error in FlushAll %v", response)))
}
return nil
}
func (mc *Connection) Stats(argument string) (result []byte, err error) {
defer handleError(&err)
if argument == "" {
mc.writestrings("stats\r\n")
} else {
mc.writestrings("stats ", argument, "\r\n")
}
mc.flush()
for {
l := mc.readline()
if strings.HasPrefix(l, "END") {
break
}
if strings.Contains(l, "ERROR") {
return nil, NewMemcacheError(l)
}
result = append(result, l...)
result = append(result, '\n')
}
return result, err
}
func (mc *Connection) get(command string, keys []string) (results []Result) {
results = make([]Result, 0, len(keys))
if len(keys) == 0 {
return
}
// get(s) <key>*\r\n
mc.writestrings(command)
for _, key := range keys {
mc.writestrings(" ", key)
}
mc.writestrings("\r\n")
header := mc.readline()
var result Result
for strings.HasPrefix(header, "VALUE") {
// VALUE <key> <flags> <bytes> [<cas unique>]\r\n
chunks := strings.Split(header, " ")
if len(chunks) < 4 {
panic(NewMemcacheError("Malformed response: %s", string(header)))
}
result.Key = chunks[1]
flags64, err := strconv.ParseUint(chunks[2], 10, 16)
if err != nil {
panic(NewMemcacheError("%v", err))
}
result.Flags = uint16(flags64)
size, err := strconv.ParseUint(chunks[3], 10, 64)
if err != nil {
panic(NewMemcacheError("%v", err))
}
if len(chunks) == 5 {
result.Cas, err = strconv.ParseUint(chunks[4], 10, 64)
if err != nil {
panic(NewMemcacheError("%v", err))
}
}
// <data block>\r\n
result.Value = mc.read(int(size) + 2)[:size]
results = append(results, result)
header = mc.readline()
}
if !strings.HasPrefix(header, "END") {
panic(NewMemcacheError("Malformed response: %s", string(header)))
}
return
}
func (mc *Connection) store(command, key string, flags uint16, timeout uint64, value []byte, cas uint64) (stored bool) {
if len(value) > 1000000 {
return false
}
// <command name> <key> <flags> <exptime> <bytes> [noreply]\r\n
mc.writestrings(command, " ", key, " ")
mc.write(strconv.AppendUint(nil, uint64(flags), 10))
mc.writestring(" ")
mc.write(strconv.AppendUint(nil, timeout, 10))
mc.writestring(" ")
mc.write(strconv.AppendInt(nil, int64(len(value)), 10))
if cas != 0 {
mc.writestring(" ")
mc.write(strconv.AppendUint(nil, cas, 10))
}
mc.writestring("\r\n")
// <data block>\r\n
mc.write(value)
mc.writestring("\r\n")
reply := mc.readline()
if strings.Contains(reply, "ERROR") {
panic(NewMemcacheError("Server error"))
}
return strings.HasPrefix(reply, "STORED")
}
func (mc *Connection) writestrings(strs ...string) {
for _, s := range strs {
mc.writestring(s)
}
}
func (mc *Connection) writestring(s string) {
if _, err := mc.buffered.WriteString(s); err != nil {
panic(NewMemcacheError("%s", err))
}
}
func (mc *Connection) write(b []byte) {
if _, err := mc.buffered.Write(b); err != nil {
panic(NewMemcacheError("%s", err))
}
}
func (mc *Connection) flush() {
if err := mc.buffered.Flush(); err != nil {
panic(NewMemcacheError("%s", err))
}
}
func (mc *Connection) readline() string {
mc.flush()
l, isPrefix, err := mc.buffered.ReadLine()
if isPrefix || err != nil {
panic(NewMemcacheError("Prefix: %v, %s", isPrefix, err))
}
return string(l)
}
func (mc *Connection) read(count int) []byte {
mc.flush()
b := make([]byte, count)
if _, err := io.ReadFull(mc.buffered, b); err != nil {
panic(NewMemcacheError("%s", err))
}
return b
}
type MemcacheError struct {
Message string
}
func NewMemcacheError(format string, args ...interface{}) MemcacheError {
return MemcacheError{fmt.Sprintf(format, args...)}
}
func (merr MemcacheError) Error() string {
return merr.Message
}
func handleError(err *error) {
if x := recover(); x != nil {
*err = x.(MemcacheError)
}
}