@open-mercato/cache-provider-memcached 0.0.0-stage → 0.11.1-develop.9003.1.ce86c31a07
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +166 -2
- package/dist/errors.js +46 -0
- package/dist/errors.js.map +7 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +7 -0
- package/dist/layout.js +101 -0
- package/dist/layout.js.map +7 -0
- package/dist/protocol/client.js +164 -0
- package/dist/protocol/client.js.map +7 -0
- package/dist/protocol/commands.js +292 -0
- package/dist/protocol/commands.js.map +7 -0
- package/dist/protocol/connection.js +114 -0
- package/dist/protocol/connection.js.map +7 -0
- package/dist/protocol/errors.js +28 -0
- package/dist/protocol/errors.js.map +7 -0
- package/dist/protocol/index.js +37 -0
- package/dist/protocol/index.js.map +7 -0
- package/dist/protocol/reader.js +75 -0
- package/dist/protocol/reader.js.map +7 -0
- package/dist/protocol/transport.js +65 -0
- package/dist/protocol/transport.js.map +7 -0
- package/dist/provider.js +47 -0
- package/dist/provider.js.map +7 -0
- package/dist/settings.js +49 -0
- package/dist/settings.js.map +7 -0
- package/dist/strategy.js +342 -0
- package/dist/strategy.js.map +7 -0
- package/package.json +67 -3
- package/src/errors.ts +59 -0
- package/src/index.ts +19 -0
- package/src/layout.ts +140 -0
- package/src/protocol/client.ts +201 -0
- package/src/protocol/commands.ts +338 -0
- package/src/protocol/connection.ts +138 -0
- package/src/protocol/errors.ts +44 -0
- package/src/protocol/index.ts +37 -0
- package/src/protocol/reader.ts +90 -0
- package/src/protocol/transport.ts +107 -0
- package/src/provider.ts +54 -0
- package/src/settings.ts +55 -0
- package/src/strategy.ts +423 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { MemcachedProtocolError } from './errors'
|
|
2
|
+
import {
|
|
3
|
+
FatalResponseError,
|
|
4
|
+
NEED_MORE,
|
|
5
|
+
PROGRESS,
|
|
6
|
+
failureOrUnexpected,
|
|
7
|
+
parseServerFailure,
|
|
8
|
+
type ParsedResult,
|
|
9
|
+
type ResponseParser,
|
|
10
|
+
} from './reader'
|
|
11
|
+
|
|
12
|
+
export const MAX_KEY_BYTES = 250
|
|
13
|
+
const KEY_PATTERN = /^[\x21-\x7e]+$/
|
|
14
|
+
|
|
15
|
+
export type MemcachedItem = {
|
|
16
|
+
value: Buffer
|
|
17
|
+
cas: string
|
|
18
|
+
flags: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type MetaSetMode = 'set' | 'add' | 'replace' | 'append' | 'prepend'
|
|
22
|
+
|
|
23
|
+
export type MetaSetOutcome = 'stored' | 'not_stored' | 'exists' | 'not_found'
|
|
24
|
+
export type MetaDeleteOutcome = 'deleted' | 'not_found' | 'exists'
|
|
25
|
+
export type ClassicStoreOutcome = 'stored' | 'not_stored' | 'exists' | 'not_found'
|
|
26
|
+
|
|
27
|
+
const META_SET_MODE_TOKEN: Record<MetaSetMode, string> = {
|
|
28
|
+
set: 'S',
|
|
29
|
+
add: 'E',
|
|
30
|
+
replace: 'R',
|
|
31
|
+
append: 'A',
|
|
32
|
+
prepend: 'P',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const CAS_PATTERN = /^\d{1,20}$/
|
|
36
|
+
|
|
37
|
+
export function assertValidKey(key: string): void {
|
|
38
|
+
if (typeof key !== 'string' || key.length === 0 || Buffer.byteLength(key, 'latin1') > MAX_KEY_BYTES || !KEY_PATTERN.test(key)) {
|
|
39
|
+
throw new MemcachedProtocolError('invalid_key', `Memcached keys must be 1-${MAX_KEY_BYTES} printable ASCII characters without spaces`)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function assertCas(cas: string): void {
|
|
44
|
+
if (!CAS_PATTERN.test(cas)) throw new MemcachedProtocolError('protocol_error', 'Invalid memcached CAS token')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function assertTtlSeconds(ttlSeconds: number): void {
|
|
48
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 0) {
|
|
49
|
+
throw new MemcachedProtocolError('protocol_error', 'Memcached TTL must be a non-negative integer number of seconds')
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function assertFlags(flags: number): void {
|
|
54
|
+
if (!Number.isInteger(flags) || flags < 0 || flags > 0xffffffff) {
|
|
55
|
+
throw new MemcachedProtocolError('protocol_error', 'Memcached client flags must be a 32-bit unsigned integer')
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function line(text: string): Buffer {
|
|
60
|
+
return Buffer.from(`${text}\r\n`, 'latin1')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function withData(header: string, value: Buffer): Buffer[] {
|
|
64
|
+
return [line(header), value, Buffer.from('\r\n', 'latin1')]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function parseMetaFlags(tokens: string[]): { cas: string | null; flags: number; key: string | null } {
|
|
68
|
+
let cas: string | null = null
|
|
69
|
+
let flags = 0
|
|
70
|
+
let key: string | null = null
|
|
71
|
+
for (const token of tokens) {
|
|
72
|
+
if (token.length === 0) continue
|
|
73
|
+
const kind = token[0]
|
|
74
|
+
const rest = token.slice(1)
|
|
75
|
+
if (kind === 'c') cas = rest
|
|
76
|
+
else if (kind === 'f') flags = Number.parseInt(rest, 10) || 0
|
|
77
|
+
else if (kind === 'k') key = rest
|
|
78
|
+
}
|
|
79
|
+
return { cas, flags, key }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function parseLength(raw: string | undefined): number {
|
|
83
|
+
const length = raw !== undefined ? Number(raw) : Number.NaN
|
|
84
|
+
if (!Number.isInteger(length) || length < 0) {
|
|
85
|
+
throw new FatalResponseError(new MemcachedProtocolError('protocol_error', 'Memcached reply carried an invalid value length'))
|
|
86
|
+
}
|
|
87
|
+
return length
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type EncodedCommand<T> = {
|
|
91
|
+
payload: Buffer | Buffer[]
|
|
92
|
+
parse: ResponseParser<ParsedResult<T>>
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function metaGetCommand(key: string): EncodedCommand<MemcachedItem | null> {
|
|
96
|
+
assertValidKey(key)
|
|
97
|
+
return {
|
|
98
|
+
payload: line(`mg ${key} v c f`),
|
|
99
|
+
parse(reader) {
|
|
100
|
+
const header = reader.readLine()
|
|
101
|
+
if (header === null) return NEED_MORE
|
|
102
|
+
if (header === 'EN') return { value: { ok: true, value: null } }
|
|
103
|
+
if (header.startsWith('VA ')) {
|
|
104
|
+
const tokens = header.split(' ')
|
|
105
|
+
const length = parseLength(tokens[1])
|
|
106
|
+
const data = reader.readData(length)
|
|
107
|
+
if (data === null) return NEED_MORE
|
|
108
|
+
const meta = parseMetaFlags(tokens.slice(2))
|
|
109
|
+
return { value: { ok: true, value: { value: data, cas: meta.cas ?? '0', flags: meta.flags } } }
|
|
110
|
+
}
|
|
111
|
+
return failureOrUnexpected(header, 'mg')
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Quiet meta-get pipeline terminated by `mn`: misses are suppressed and hits
|
|
118
|
+
* carry their key (`k` flag). The caller bounds the command size.
|
|
119
|
+
*/
|
|
120
|
+
export function metaGetManyCommand(keys: string[]): EncodedCommand<Map<string, MemcachedItem>> {
|
|
121
|
+
for (const key of keys) assertValidKey(key)
|
|
122
|
+
const found = new Map<string, MemcachedItem>()
|
|
123
|
+
let failure: MemcachedProtocolError | null = null
|
|
124
|
+
const text = `${keys.map((key) => `mg ${key} v c f k q`).join('\r\n')}\r\nmn\r\n`
|
|
125
|
+
return {
|
|
126
|
+
payload: Buffer.from(text, 'latin1'),
|
|
127
|
+
parse(reader) {
|
|
128
|
+
const header = reader.readLine()
|
|
129
|
+
if (header === null) return NEED_MORE
|
|
130
|
+
if (header === 'MN') {
|
|
131
|
+
return { value: failure ? { ok: false, error: failure } : { ok: true, value: found } }
|
|
132
|
+
}
|
|
133
|
+
if (header.startsWith('VA ')) {
|
|
134
|
+
const tokens = header.split(' ')
|
|
135
|
+
const length = parseLength(tokens[1])
|
|
136
|
+
const data = reader.readData(length)
|
|
137
|
+
if (data === null) return NEED_MORE
|
|
138
|
+
const meta = parseMetaFlags(tokens.slice(2))
|
|
139
|
+
if (meta.key === null) {
|
|
140
|
+
throw new FatalResponseError(new MemcachedProtocolError('protocol_error', 'Memcached multi-get hit is missing its key'))
|
|
141
|
+
}
|
|
142
|
+
found.set(meta.key, { value: data, cas: meta.cas ?? '0', flags: meta.flags })
|
|
143
|
+
return PROGRESS
|
|
144
|
+
}
|
|
145
|
+
if (header === 'EN') return PROGRESS
|
|
146
|
+
const serverFailure = parseServerFailure(header)
|
|
147
|
+
if (!serverFailure) {
|
|
148
|
+
throw new FatalResponseError(new MemcachedProtocolError('protocol_error', 'Unexpected memcached reply to mg'))
|
|
149
|
+
}
|
|
150
|
+
if (serverFailure.fatal) throw new FatalResponseError(serverFailure.error)
|
|
151
|
+
failure = failure ?? serverFailure.error
|
|
152
|
+
return PROGRESS
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export type MetaSetOptions = {
|
|
158
|
+
mode?: MetaSetMode
|
|
159
|
+
cas?: string
|
|
160
|
+
ttlSeconds?: number
|
|
161
|
+
flags?: number
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function metaSetCommand(key: string, value: Buffer, options: MetaSetOptions = {}): EncodedCommand<MetaSetOutcome> {
|
|
165
|
+
assertValidKey(key)
|
|
166
|
+
const tokens = [`ms ${key} ${value.length}`]
|
|
167
|
+
if (options.ttlSeconds !== undefined) {
|
|
168
|
+
assertTtlSeconds(options.ttlSeconds)
|
|
169
|
+
tokens.push(`T${options.ttlSeconds}`)
|
|
170
|
+
}
|
|
171
|
+
if (options.flags !== undefined) {
|
|
172
|
+
assertFlags(options.flags)
|
|
173
|
+
tokens.push(`F${options.flags}`)
|
|
174
|
+
}
|
|
175
|
+
if (options.cas !== undefined) {
|
|
176
|
+
assertCas(options.cas)
|
|
177
|
+
tokens.push(`C${options.cas}`)
|
|
178
|
+
}
|
|
179
|
+
if (options.mode && options.mode !== 'set') tokens.push(`M${META_SET_MODE_TOKEN[options.mode]}`)
|
|
180
|
+
return {
|
|
181
|
+
payload: withData(tokens.join(' '), value),
|
|
182
|
+
parse(reader) {
|
|
183
|
+
const reply = reader.readLine()
|
|
184
|
+
if (reply === null) return NEED_MORE
|
|
185
|
+
const code = reply.split(' ')[0]
|
|
186
|
+
if (code === 'HD') return { value: { ok: true, value: 'stored' } }
|
|
187
|
+
if (code === 'NS') return { value: { ok: true, value: 'not_stored' } }
|
|
188
|
+
if (code === 'EX') return { value: { ok: true, value: 'exists' } }
|
|
189
|
+
if (code === 'NF') return { value: { ok: true, value: 'not_found' } }
|
|
190
|
+
return failureOrUnexpected(reply, 'ms')
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function metaDeleteCommand(key: string, options: { cas?: string } = {}): EncodedCommand<MetaDeleteOutcome> {
|
|
196
|
+
assertValidKey(key)
|
|
197
|
+
const tokens = [`md ${key}`]
|
|
198
|
+
if (options.cas !== undefined) {
|
|
199
|
+
assertCas(options.cas)
|
|
200
|
+
tokens.push(`C${options.cas}`)
|
|
201
|
+
}
|
|
202
|
+
return {
|
|
203
|
+
payload: line(tokens.join(' ')),
|
|
204
|
+
parse(reader) {
|
|
205
|
+
const reply = reader.readLine()
|
|
206
|
+
if (reply === null) return NEED_MORE
|
|
207
|
+
const code = reply.split(' ')[0]
|
|
208
|
+
if (code === 'HD') return { value: { ok: true, value: 'deleted' } }
|
|
209
|
+
if (code === 'NF') return { value: { ok: true, value: 'not_found' } }
|
|
210
|
+
if (code === 'EX') return { value: { ok: true, value: 'exists' } }
|
|
211
|
+
return failureOrUnexpected(reply, 'md')
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function getsCommand(keys: string[]): EncodedCommand<Map<string, MemcachedItem>> {
|
|
217
|
+
if (keys.length === 0) throw new MemcachedProtocolError('protocol_error', 'gets requires at least one key')
|
|
218
|
+
for (const key of keys) assertValidKey(key)
|
|
219
|
+
const found = new Map<string, MemcachedItem>()
|
|
220
|
+
return {
|
|
221
|
+
payload: line(`gets ${keys.join(' ')}`),
|
|
222
|
+
parse(reader) {
|
|
223
|
+
const header = reader.readLine()
|
|
224
|
+
if (header === null) return NEED_MORE
|
|
225
|
+
if (header === 'END') return { value: { ok: true, value: found } }
|
|
226
|
+
if (header.startsWith('VALUE ')) {
|
|
227
|
+
const tokens = header.split(' ')
|
|
228
|
+
const key = tokens[1]
|
|
229
|
+
const flags = Number.parseInt(tokens[2] ?? '0', 10) || 0
|
|
230
|
+
const length = parseLength(tokens[3])
|
|
231
|
+
const cas = tokens[4]
|
|
232
|
+
const data = reader.readData(length)
|
|
233
|
+
if (data === null) return NEED_MORE
|
|
234
|
+
if (!key || !cas) {
|
|
235
|
+
throw new FatalResponseError(new MemcachedProtocolError('protocol_error', 'Malformed memcached VALUE header'))
|
|
236
|
+
}
|
|
237
|
+
found.set(key, { value: data, cas, flags })
|
|
238
|
+
return PROGRESS
|
|
239
|
+
}
|
|
240
|
+
return failureOrUnexpected(header, 'gets')
|
|
241
|
+
},
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function classicStoreOutcome(reply: string, command: string): { value: ParsedResult<ClassicStoreOutcome> } {
|
|
246
|
+
if (reply === 'STORED') return { value: { ok: true, value: 'stored' } }
|
|
247
|
+
if (reply === 'NOT_STORED') return { value: { ok: true, value: 'not_stored' } }
|
|
248
|
+
if (reply === 'EXISTS') return { value: { ok: true, value: 'exists' } }
|
|
249
|
+
if (reply === 'NOT_FOUND') return { value: { ok: true, value: 'not_found' } }
|
|
250
|
+
return failureOrUnexpected(reply, command)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export type ClassicStoreOptions = {
|
|
254
|
+
ttlSeconds?: number
|
|
255
|
+
flags?: number
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function classicStoreCommand(
|
|
259
|
+
verb: 'add' | 'set' | 'cas',
|
|
260
|
+
key: string,
|
|
261
|
+
value: Buffer,
|
|
262
|
+
options: ClassicStoreOptions & { cas?: string },
|
|
263
|
+
): EncodedCommand<ClassicStoreOutcome> {
|
|
264
|
+
assertValidKey(key)
|
|
265
|
+
const ttlSeconds = options.ttlSeconds ?? 0
|
|
266
|
+
const flags = options.flags ?? 0
|
|
267
|
+
assertTtlSeconds(ttlSeconds)
|
|
268
|
+
assertFlags(flags)
|
|
269
|
+
const header = [verb, key, String(flags), String(ttlSeconds), String(value.length)]
|
|
270
|
+
if (verb === 'cas') {
|
|
271
|
+
if (options.cas === undefined) throw new MemcachedProtocolError('protocol_error', 'cas requires a CAS token')
|
|
272
|
+
assertCas(options.cas)
|
|
273
|
+
header.push(options.cas)
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
payload: withData(header.join(' '), value),
|
|
277
|
+
parse(reader) {
|
|
278
|
+
const reply = reader.readLine()
|
|
279
|
+
if (reply === null) return NEED_MORE
|
|
280
|
+
return classicStoreOutcome(reply, verb)
|
|
281
|
+
},
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function addCommand(key: string, value: Buffer, options: ClassicStoreOptions = {}): EncodedCommand<ClassicStoreOutcome> {
|
|
286
|
+
return classicStoreCommand('add', key, value, options)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function casCommand(key: string, value: Buffer, cas: string, options: ClassicStoreOptions = {}): EncodedCommand<ClassicStoreOutcome> {
|
|
290
|
+
return classicStoreCommand('cas', key, value, { ...options, cas })
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function versionCommand(): EncodedCommand<string> {
|
|
294
|
+
return {
|
|
295
|
+
payload: line('version'),
|
|
296
|
+
parse(reader) {
|
|
297
|
+
const reply = reader.readLine()
|
|
298
|
+
if (reply === null) return NEED_MORE
|
|
299
|
+
if (reply.startsWith('VERSION ')) return { value: { ok: true, value: reply.slice(8).trim() } }
|
|
300
|
+
return failureOrUnexpected(reply, 'version')
|
|
301
|
+
},
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export function noopCommand(): EncodedCommand<null> {
|
|
306
|
+
return {
|
|
307
|
+
payload: line('mn'),
|
|
308
|
+
parse(reader) {
|
|
309
|
+
const reply = reader.readLine()
|
|
310
|
+
if (reply === null) return NEED_MORE
|
|
311
|
+
if (reply === 'MN') return { value: { ok: true, value: null } }
|
|
312
|
+
return failureOrUnexpected(reply, 'mn')
|
|
313
|
+
},
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const STATS_GROUP_PATTERN = /^[a-z_]{1,32}$/
|
|
318
|
+
|
|
319
|
+
export function statsCommand(group?: string): EncodedCommand<Map<string, string>> {
|
|
320
|
+
if (group !== undefined && !STATS_GROUP_PATTERN.test(group)) {
|
|
321
|
+
throw new MemcachedProtocolError('protocol_error', 'Invalid memcached stats group')
|
|
322
|
+
}
|
|
323
|
+
const stats = new Map<string, string>()
|
|
324
|
+
return {
|
|
325
|
+
payload: line(group ? `stats ${group}` : 'stats'),
|
|
326
|
+
parse(reader) {
|
|
327
|
+
const reply = reader.readLine()
|
|
328
|
+
if (reply === null) return NEED_MORE
|
|
329
|
+
if (reply === 'END') return { value: { ok: true, value: stats } }
|
|
330
|
+
if (reply.startsWith('STAT ')) {
|
|
331
|
+
const separator = reply.indexOf(' ', 5)
|
|
332
|
+
if (separator > 0) stats.set(reply.slice(5, separator), reply.slice(separator + 1))
|
|
333
|
+
return PROGRESS
|
|
334
|
+
}
|
|
335
|
+
return failureOrUnexpected(reply, 'stats')
|
|
336
|
+
},
|
|
337
|
+
}
|
|
338
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { MemcachedProtocolError } from './errors'
|
|
2
|
+
import type { MemcachedSocket, MemcachedTransport } from './transport'
|
|
3
|
+
import {
|
|
4
|
+
FatalResponseError,
|
|
5
|
+
NEED_MORE,
|
|
6
|
+
PROGRESS,
|
|
7
|
+
ResponseReader,
|
|
8
|
+
type ParsedResult,
|
|
9
|
+
type ResponseParser,
|
|
10
|
+
} from './reader'
|
|
11
|
+
|
|
12
|
+
type PendingRequest = {
|
|
13
|
+
parse: ResponseParser<ParsedResult<unknown>>
|
|
14
|
+
resolve(value: unknown): void
|
|
15
|
+
reject(error: Error): void
|
|
16
|
+
timer: ReturnType<typeof setTimeout> | null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One pipelined memcached connection. Requests are written in order and their
|
|
21
|
+
* replies parsed in the same order. A timeout, a protocol violation or a
|
|
22
|
+
* socket failure destroys the connection and fails every in-flight request,
|
|
23
|
+
* because the reply stream position is no longer known.
|
|
24
|
+
*/
|
|
25
|
+
export class MemcachedConnection {
|
|
26
|
+
private readonly queue: PendingRequest[] = []
|
|
27
|
+
private chunks: Buffer[] = []
|
|
28
|
+
private buffered = 0
|
|
29
|
+
private needed = 0
|
|
30
|
+
private failure: MemcachedProtocolError | null = null
|
|
31
|
+
|
|
32
|
+
private constructor(private readonly socket: MemcachedSocket, private readonly commandTimeoutMs: number) {
|
|
33
|
+
socket.on('data', (chunk) => this.onData(chunk))
|
|
34
|
+
socket.on('error', (error) => this.fail(new MemcachedProtocolError('unavailable', 'Memcached connection failed', { cause: error })))
|
|
35
|
+
socket.on('close', () => this.fail(new MemcachedProtocolError('unavailable', 'Memcached connection closed')))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static async open(transport: MemcachedTransport, options: { connectTimeoutMs: number; commandTimeoutMs: number }): Promise<MemcachedConnection> {
|
|
39
|
+
const socket = await transport.open({ timeoutMs: options.connectTimeoutMs })
|
|
40
|
+
return new MemcachedConnection(socket, options.commandTimeoutMs)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
get alive(): boolean {
|
|
44
|
+
return this.failure === null
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get pending(): number {
|
|
48
|
+
return this.queue.length
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
send<T>(payload: Buffer | Buffer[], parse: ResponseParser<ParsedResult<T>>): Promise<T> {
|
|
52
|
+
if (this.failure) return Promise.reject(this.failure)
|
|
53
|
+
return new Promise<T>((resolve, reject) => {
|
|
54
|
+
const request: PendingRequest = {
|
|
55
|
+
parse: parse as ResponseParser<ParsedResult<unknown>>,
|
|
56
|
+
resolve: resolve as (value: unknown) => void,
|
|
57
|
+
reject,
|
|
58
|
+
timer: null,
|
|
59
|
+
}
|
|
60
|
+
if (this.commandTimeoutMs > 0) {
|
|
61
|
+
request.timer = setTimeout(() => {
|
|
62
|
+
this.fail(new MemcachedProtocolError('timeout', `Memcached command did not complete within ${this.commandTimeoutMs}ms`))
|
|
63
|
+
}, this.commandTimeoutMs)
|
|
64
|
+
}
|
|
65
|
+
this.queue.push(request)
|
|
66
|
+
const parts = Array.isArray(payload) ? payload : [payload]
|
|
67
|
+
for (const part of parts) this.socket.write(part)
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
close(): void {
|
|
72
|
+
this.fail(new MemcachedProtocolError('closed', 'Memcached client is closed'))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private onData(chunk: Buffer): void {
|
|
76
|
+
if (this.failure) return
|
|
77
|
+
this.chunks.push(chunk)
|
|
78
|
+
this.buffered += chunk.length
|
|
79
|
+
if (this.buffered < this.needed) return
|
|
80
|
+
this.drain()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private drain(): void {
|
|
84
|
+
const buffer = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks, this.buffered)
|
|
85
|
+
let committed = 0
|
|
86
|
+
let needed = 0
|
|
87
|
+
while (committed < buffer.length || this.queue.length > 0) {
|
|
88
|
+
const head = this.queue[0]
|
|
89
|
+
if (!head) {
|
|
90
|
+
this.fail(new MemcachedProtocolError('protocol_error', 'Memcached sent an unsolicited reply'))
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
const reader = new ResponseReader(buffer, committed)
|
|
94
|
+
let step
|
|
95
|
+
try {
|
|
96
|
+
step = head.parse(reader)
|
|
97
|
+
} catch (error) {
|
|
98
|
+
const reason = error instanceof FatalResponseError
|
|
99
|
+
? error.reason
|
|
100
|
+
: error instanceof MemcachedProtocolError
|
|
101
|
+
? error
|
|
102
|
+
: new MemcachedProtocolError('protocol_error', 'Memcached reply could not be parsed', { cause: error })
|
|
103
|
+
this.queue.shift()
|
|
104
|
+
if (head.timer) clearTimeout(head.timer)
|
|
105
|
+
head.reject(reason)
|
|
106
|
+
this.fail(new MemcachedProtocolError('unavailable', 'Memcached connection reset after an unrecoverable reply', { cause: reason }))
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
if (step === NEED_MORE) {
|
|
110
|
+
needed = Math.max(reader.needed - committed, buffer.length - committed + 1)
|
|
111
|
+
break
|
|
112
|
+
}
|
|
113
|
+
committed = reader.offset
|
|
114
|
+
if (step === PROGRESS) continue
|
|
115
|
+
this.queue.shift()
|
|
116
|
+
if (head.timer) clearTimeout(head.timer)
|
|
117
|
+
if (step.value.ok) head.resolve(step.value.value)
|
|
118
|
+
else head.reject(step.value.error)
|
|
119
|
+
}
|
|
120
|
+
const rest = committed < buffer.length ? buffer.subarray(committed) : null
|
|
121
|
+
this.chunks = rest ? [rest] : []
|
|
122
|
+
this.buffered = rest ? rest.length : 0
|
|
123
|
+
this.needed = rest ? needed : 0
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private fail(error: MemcachedProtocolError): void {
|
|
127
|
+
if (this.failure) return
|
|
128
|
+
this.failure = error
|
|
129
|
+
const pending = this.queue.splice(0, this.queue.length)
|
|
130
|
+
for (const request of pending) {
|
|
131
|
+
if (request.timer) clearTimeout(request.timer)
|
|
132
|
+
request.reject(error)
|
|
133
|
+
}
|
|
134
|
+
this.chunks = []
|
|
135
|
+
this.buffered = 0
|
|
136
|
+
this.socket.destroy()
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export type MemcachedProtocolErrorCode =
|
|
2
|
+
| 'timeout'
|
|
3
|
+
| 'unavailable'
|
|
4
|
+
| 'closed'
|
|
5
|
+
| 'item_too_large'
|
|
6
|
+
| 'invalid_key'
|
|
7
|
+
| 'command_too_large'
|
|
8
|
+
| 'client_error'
|
|
9
|
+
| 'server_error'
|
|
10
|
+
| 'protocol_error'
|
|
11
|
+
|
|
12
|
+
export class MemcachedProtocolError extends Error {
|
|
13
|
+
public readonly code: MemcachedProtocolErrorCode
|
|
14
|
+
declare public readonly originalError?: unknown
|
|
15
|
+
|
|
16
|
+
constructor(code: MemcachedProtocolErrorCode, message: string, options: { cause?: unknown } = {}) {
|
|
17
|
+
super(message)
|
|
18
|
+
this.name = 'MemcachedProtocolError'
|
|
19
|
+
this.code = code
|
|
20
|
+
Object.defineProperty(this, 'originalError', {
|
|
21
|
+
value: options.cause,
|
|
22
|
+
enumerable: false,
|
|
23
|
+
writable: false,
|
|
24
|
+
configurable: false,
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
toJSON(): { name: string; code: MemcachedProtocolErrorCode; message: string } {
|
|
29
|
+
return { name: this.name, code: this.code, message: this.message }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function isMemcachedProtocolError(error: unknown): error is MemcachedProtocolError {
|
|
34
|
+
return error instanceof MemcachedProtocolError
|
|
35
|
+
|| (error instanceof Error && error.name === 'MemcachedProtocolError' && typeof (error as { code?: unknown }).code === 'string')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Connection-level failures leave the request outcome unknown: the command may
|
|
40
|
+
* or may not have reached the server. Callers must not assume it was applied.
|
|
41
|
+
*/
|
|
42
|
+
export function isMemcachedConnectionError(error: unknown): boolean {
|
|
43
|
+
return isMemcachedProtocolError(error) && (error.code === 'timeout' || error.code === 'unavailable' || error.code === 'closed')
|
|
44
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createMemcachedClient,
|
|
3
|
+
planKeyBatches,
|
|
4
|
+
MAX_COMMAND_BYTES,
|
|
5
|
+
DEFAULT_POOL_SIZE,
|
|
6
|
+
DEFAULT_CONNECT_TIMEOUT_MS,
|
|
7
|
+
DEFAULT_COMMAND_TIMEOUT_MS,
|
|
8
|
+
type MemcachedClient,
|
|
9
|
+
type MemcachedClientOptions,
|
|
10
|
+
type MemcachedCommandName,
|
|
11
|
+
} from './client'
|
|
12
|
+
export {
|
|
13
|
+
MAX_KEY_BYTES,
|
|
14
|
+
assertValidKey,
|
|
15
|
+
type MemcachedItem,
|
|
16
|
+
type MetaSetMode,
|
|
17
|
+
type MetaSetOptions,
|
|
18
|
+
type MetaSetOutcome,
|
|
19
|
+
type MetaDeleteOutcome,
|
|
20
|
+
type ClassicStoreOptions,
|
|
21
|
+
type ClassicStoreOutcome,
|
|
22
|
+
} from './commands'
|
|
23
|
+
export {
|
|
24
|
+
MemcachedProtocolError,
|
|
25
|
+
isMemcachedProtocolError,
|
|
26
|
+
isMemcachedConnectionError,
|
|
27
|
+
type MemcachedProtocolErrorCode,
|
|
28
|
+
} from './errors'
|
|
29
|
+
export {
|
|
30
|
+
createTcpTransport,
|
|
31
|
+
createTlsTransport,
|
|
32
|
+
type MemcachedSocket,
|
|
33
|
+
type MemcachedTransport,
|
|
34
|
+
type MemcachedTransportOpenOptions,
|
|
35
|
+
type MemcachedTcpEndpoint,
|
|
36
|
+
type MemcachedTlsOptions,
|
|
37
|
+
} from './transport'
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { MemcachedProtocolError } from './errors'
|
|
2
|
+
|
|
3
|
+
const CR = 0x0d
|
|
4
|
+
const LF = 0x0a
|
|
5
|
+
|
|
6
|
+
export const NEED_MORE: unique symbol = Symbol('memcached.needMore')
|
|
7
|
+
export const PROGRESS: unique symbol = Symbol('memcached.progress')
|
|
8
|
+
|
|
9
|
+
export type ParseStep<T> = typeof NEED_MORE | typeof PROGRESS | { value: T }
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Incremental parser for one pipelined request. It reads from `reader` and
|
|
13
|
+
* returns `NEED_MORE` (nothing consumed, wait for bytes), `PROGRESS` (bytes
|
|
14
|
+
* consumed, request not finished yet) or the final value.
|
|
15
|
+
*/
|
|
16
|
+
export type ResponseParser<T> = (reader: ResponseReader) => ParseStep<T>
|
|
17
|
+
|
|
18
|
+
export class ResponseReader {
|
|
19
|
+
public offset: number
|
|
20
|
+
public needed = 0
|
|
21
|
+
|
|
22
|
+
constructor(private readonly buffer: Buffer, offset: number) {
|
|
23
|
+
this.offset = offset
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
readLine(): string | null {
|
|
27
|
+
const end = this.buffer.indexOf('\r\n', this.offset, 'latin1')
|
|
28
|
+
if (end < 0) {
|
|
29
|
+
this.needed = this.buffer.length + 1
|
|
30
|
+
return null
|
|
31
|
+
}
|
|
32
|
+
const line = this.buffer.toString('latin1', this.offset, end)
|
|
33
|
+
this.offset = end + 2
|
|
34
|
+
return line
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
readData(length: number): Buffer | null {
|
|
38
|
+
const end = this.offset + length
|
|
39
|
+
if (end + 2 > this.buffer.length) {
|
|
40
|
+
this.needed = end + 2
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
if (this.buffer[end] !== CR || this.buffer[end + 1] !== LF) {
|
|
44
|
+
throw new MemcachedProtocolError('protocol_error', 'Memcached value block is not terminated by CRLF')
|
|
45
|
+
}
|
|
46
|
+
const data = Buffer.from(this.buffer.subarray(this.offset, end))
|
|
47
|
+
this.offset = end + 2
|
|
48
|
+
return data
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Maps the generic `ERROR` / `CLIENT_ERROR` / `SERVER_ERROR` replies. A client
|
|
54
|
+
* error may leave the server reading the rest of our payload as a command, so
|
|
55
|
+
* the connection is marked unusable; server errors keep the stream in sync.
|
|
56
|
+
*/
|
|
57
|
+
export function parseServerFailure(line: string): { error: MemcachedProtocolError; fatal: boolean } | null {
|
|
58
|
+
if (line === 'ERROR' || line.startsWith('ERROR ')) {
|
|
59
|
+
return { error: new MemcachedProtocolError('client_error', 'Memcached rejected an unknown command'), fatal: true }
|
|
60
|
+
}
|
|
61
|
+
if (line.startsWith('CLIENT_ERROR')) {
|
|
62
|
+
return { error: new MemcachedProtocolError('client_error', `Memcached client error: ${line.slice(12).trim().slice(0, 120)}`), fatal: true }
|
|
63
|
+
}
|
|
64
|
+
if (line.startsWith('SERVER_ERROR')) {
|
|
65
|
+
const detail = line.slice(12).trim().slice(0, 120)
|
|
66
|
+
if (/too large/i.test(detail)) {
|
|
67
|
+
return { error: new MemcachedProtocolError('item_too_large', 'Memcached rejected an item larger than its item size limit'), fatal: false }
|
|
68
|
+
}
|
|
69
|
+
return { error: new MemcachedProtocolError('server_error', `Memcached server error: ${detail}`), fatal: false }
|
|
70
|
+
}
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class FatalResponseError extends Error {
|
|
75
|
+
constructor(public readonly reason: MemcachedProtocolError) {
|
|
76
|
+
super(reason.message)
|
|
77
|
+
this.name = 'FatalResponseError'
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type ParsedResult<T> = { ok: true; value: T } | { ok: false; error: MemcachedProtocolError }
|
|
82
|
+
|
|
83
|
+
export function failureOrUnexpected<T>(line: string, expected: string): { value: ParsedResult<T> } {
|
|
84
|
+
const failure = parseServerFailure(line)
|
|
85
|
+
if (!failure) {
|
|
86
|
+
throw new FatalResponseError(new MemcachedProtocolError('protocol_error', `Unexpected memcached reply to ${expected}`))
|
|
87
|
+
}
|
|
88
|
+
if (failure.fatal) throw new FatalResponseError(failure.error)
|
|
89
|
+
return { value: { ok: false, error: failure.error } }
|
|
90
|
+
}
|