@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
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/cache-provider-memcached",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.11.1-develop.9003.1.ce86c31a07",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Open Mercato cache provider for a self-hosted Memcached server (fixed CAS buckets with tag invalidation)",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./src/index.ts",
|
|
9
|
+
"sideEffects": false,
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "node build.mjs",
|
|
12
|
+
"watch": "node watch.mjs",
|
|
13
|
+
"test": "jest --config jest.config.cjs",
|
|
14
|
+
"test:containers": "cross-env OM_CACHE_PROVIDER_CONTAINER_TESTS=1 jest --config jest.config.cjs --runInBand 'src/.+\\.container\\.test\\.ts$'",
|
|
15
|
+
"qualify": "node scripts/qualify.mjs",
|
|
16
|
+
"typecheck": "tsc --noEmit"
|
|
17
|
+
},
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./src/index.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./protocol": {
|
|
24
|
+
"types": "./src/protocol/index.ts",
|
|
25
|
+
"default": "./dist/protocol/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"src",
|
|
32
|
+
"!src/**/__tests__",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"keywords": [
|
|
36
|
+
"open-mercato",
|
|
37
|
+
"cache",
|
|
38
|
+
"cache-provider",
|
|
39
|
+
"memcached"
|
|
40
|
+
],
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=20"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"@open-mercato/cache": ">=0.11.1-develop.9003.1.ce86c31a07"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"zod": "^4.6.6"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@open-mercato/cache": "0.11.1-develop.9003.1.ce86c31a07",
|
|
52
|
+
"@types/jest": "^30.0.0",
|
|
53
|
+
"@types/node": "^26.4.0",
|
|
54
|
+
"cross-env": "^10.1.0",
|
|
55
|
+
"esbuild": "^0.28.2",
|
|
56
|
+
"jest": "^30.4.2",
|
|
57
|
+
"testcontainers": "^12.0.3",
|
|
58
|
+
"ts-jest": "^29.4.12",
|
|
59
|
+
"typescript": "7.0.2"
|
|
60
|
+
},
|
|
61
|
+
"publishConfig": {
|
|
62
|
+
"access": "public"
|
|
63
|
+
},
|
|
64
|
+
"repository": {
|
|
65
|
+
"type": "git",
|
|
66
|
+
"url": "https://github.com/open-mercato/open-mercato",
|
|
67
|
+
"directory": "packages/cache-provider-memcached"
|
|
68
|
+
},
|
|
69
|
+
"stableVersion": "0.11.0"
|
|
6
70
|
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { CacheProviderError, isCacheProviderError } from '@open-mercato/cache/provider'
|
|
2
|
+
import { isMemcachedProtocolError } from './protocol/errors'
|
|
3
|
+
import { MEMCACHED_PROVIDER_ID } from './settings'
|
|
4
|
+
|
|
5
|
+
export type MemcachedCacheErrorCode = 'item_too_large' | 'cas_conflict' | 'incompatible_server' | 'protocol_error'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Provider-specific failures outside the shared `CacheProviderError` codes.
|
|
9
|
+
* Messages never include endpoints, keys or values.
|
|
10
|
+
*/
|
|
11
|
+
export class MemcachedCacheError extends Error {
|
|
12
|
+
public readonly code: MemcachedCacheErrorCode
|
|
13
|
+
public readonly providerId = MEMCACHED_PROVIDER_ID
|
|
14
|
+
declare public readonly originalError?: unknown
|
|
15
|
+
|
|
16
|
+
constructor(code: MemcachedCacheErrorCode, message: string, options: { cause?: unknown } = {}) {
|
|
17
|
+
super(message)
|
|
18
|
+
this.name = 'MemcachedCacheError'
|
|
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: MemcachedCacheErrorCode; message: string; providerId: string } {
|
|
29
|
+
return { name: this.name, code: this.code, message: this.message, providerId: this.providerId }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function isMemcachedCacheError(error: unknown): error is MemcachedCacheError {
|
|
34
|
+
return error instanceof MemcachedCacheError
|
|
35
|
+
|| (error instanceof Error && error.name === 'MemcachedCacheError' && typeof (error as { code?: unknown }).code === 'string')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Maps transport and protocol failures onto the shared sanitized contract:
|
|
40
|
+
* `CacheProviderError` (`timeout` / `unavailable`) for transport problems and
|
|
41
|
+
* `MemcachedCacheError` for item limits and protocol violations.
|
|
42
|
+
*/
|
|
43
|
+
export function toProviderFailure(error: unknown): Error {
|
|
44
|
+
if (isCacheProviderError(error) || isMemcachedCacheError(error)) return error
|
|
45
|
+
if (isMemcachedProtocolError(error)) {
|
|
46
|
+
switch (error.code) {
|
|
47
|
+
case 'timeout':
|
|
48
|
+
return new CacheProviderError('timeout', 'Memcached command timed out', { providerId: MEMCACHED_PROVIDER_ID, cause: error })
|
|
49
|
+
case 'unavailable':
|
|
50
|
+
case 'closed':
|
|
51
|
+
return new CacheProviderError('unavailable', 'Memcached server is unavailable', { providerId: MEMCACHED_PROVIDER_ID, cause: error })
|
|
52
|
+
case 'item_too_large':
|
|
53
|
+
return new MemcachedCacheError('item_too_large', 'Memcached rejected a cache bucket larger than its item size limit', { cause: error })
|
|
54
|
+
default:
|
|
55
|
+
return new MemcachedCacheError('protocol_error', 'Memcached returned an unexpected reply', { cause: error })
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return new CacheProviderError('unavailable', 'Memcached cache operation failed', { providerId: MEMCACHED_PROVIDER_ID, cause: error })
|
|
59
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { provider, createMemcachedCacheStrategy, type CreateMemcachedCacheStrategyOptions } from './provider'
|
|
2
|
+
export { provider as default } from './provider'
|
|
3
|
+
export {
|
|
4
|
+
MEMCACHED_PROVIDER_ID,
|
|
5
|
+
MEMCACHED_SETTINGS_DEFAULTS,
|
|
6
|
+
memcachedSettingsSchema,
|
|
7
|
+
redactMemcachedSettings,
|
|
8
|
+
type MemcachedProviderConfig,
|
|
9
|
+
type MemcachedProviderSettingsInput,
|
|
10
|
+
} from './settings'
|
|
11
|
+
export { MemcachedCacheError, isMemcachedCacheError, type MemcachedCacheErrorCode } from './errors'
|
|
12
|
+
export {
|
|
13
|
+
LAYOUT_VERSION,
|
|
14
|
+
bucketItemKey,
|
|
15
|
+
bucketItemKeyFor,
|
|
16
|
+
bucketIndexFor,
|
|
17
|
+
routingKey,
|
|
18
|
+
} from './layout'
|
|
19
|
+
export type { MemcachedCacheStrategy, MemcachedStrategyDiagnostics } from './strategy'
|
package/src/layout.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
export const LAYOUT_VERSION = 'v1'
|
|
4
|
+
export const BUCKET_FORMAT_VERSION = 1
|
|
5
|
+
/** Per-item bytes memcached spends on its header, key and CAS beyond the value. */
|
|
6
|
+
export const ITEM_OVERHEAD_BYTES = 192
|
|
7
|
+
|
|
8
|
+
const WRAPPER_RECORD_PATTERN = /^(.*):key:(?:k|meta):([0-9a-f]{64})$/
|
|
9
|
+
|
|
10
|
+
export type StoredEntry = {
|
|
11
|
+
/** Encoded payload produced by the host codec. */
|
|
12
|
+
p: string
|
|
13
|
+
/** 1 when `p` is base64 of a binary (compressed) frame. */
|
|
14
|
+
b?: 1
|
|
15
|
+
/** Scoped tags. */
|
|
16
|
+
t: string[]
|
|
17
|
+
/** Logical expiry in epoch milliseconds, or null. */
|
|
18
|
+
x: number | null
|
|
19
|
+
/** Creation time in epoch milliseconds. */
|
|
20
|
+
c: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type BucketEntries = Map<string, StoredEntry>
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Physical bucket item key: `{namespace}:v1:b{bucketCount}:{index}`. The
|
|
27
|
+
* bucket count is part of the key so a changed count starts a fresh layout
|
|
28
|
+
* instead of reading entries routed by a different modulus.
|
|
29
|
+
*/
|
|
30
|
+
export function bucketItemKey(namespace: string, bucketCount: number, index: number): string {
|
|
31
|
+
return `${namespace}:${LAYOUT_VERSION}:b${bucketCount}:${index}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function allBucketItemKeys(namespace: string, bucketCount: number): string[] {
|
|
35
|
+
return Array.from({ length: bucketCount }, (_, index) => bucketItemKey(namespace, bucketCount, index))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Routing identity of a physical key. The tenant wrapper stores a value record
|
|
40
|
+
* (`…:key:k:<hash>`) and a metadata record (`…:key:meta:<hash>`) per logical
|
|
41
|
+
* entry; both route to the same bucket so eviction removes them together.
|
|
42
|
+
*/
|
|
43
|
+
export function routingKey(physicalKey: string): string {
|
|
44
|
+
const match = WRAPPER_RECORD_PATTERN.exec(physicalKey)
|
|
45
|
+
return match ? `${match[1]}:key:${match[2]}` : physicalKey
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function bucketIndexFor(physicalKey: string, bucketCount: number): number {
|
|
49
|
+
const digest = createHash('sha256').update(routingKey(physicalKey), 'utf8').digest()
|
|
50
|
+
return digest.readUInt32BE(0) % bucketCount
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function bucketItemKeyFor(namespace: string, bucketCount: number, physicalKey: string): string {
|
|
54
|
+
return bucketItemKey(namespace, bucketCount, bucketIndexFor(physicalKey, bucketCount))
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function isStoredEntry(value: unknown): value is StoredEntry {
|
|
58
|
+
if (typeof value !== 'object' || value === null) return false
|
|
59
|
+
const record = value as Record<string, unknown>
|
|
60
|
+
return typeof record.p === 'string'
|
|
61
|
+
&& (record.b === undefined || record.b === 1)
|
|
62
|
+
&& Array.isArray(record.t)
|
|
63
|
+
&& record.t.every((tag) => typeof tag === 'string')
|
|
64
|
+
&& (record.x === null || typeof record.x === 'number')
|
|
65
|
+
&& typeof record.c === 'number'
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Returns null for an item that is not a readable bucket of this layout. */
|
|
69
|
+
export function decodeBucket(raw: Buffer): BucketEntries | null {
|
|
70
|
+
let parsed: unknown
|
|
71
|
+
try {
|
|
72
|
+
parsed = JSON.parse(raw.toString('utf8'))
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
if (typeof parsed !== 'object' || parsed === null) return null
|
|
77
|
+
const record = parsed as Record<string, unknown>
|
|
78
|
+
if (record.v !== BUCKET_FORMAT_VERSION || typeof record.e !== 'object' || record.e === null || Array.isArray(record.e)) return null
|
|
79
|
+
const entries: BucketEntries = new Map()
|
|
80
|
+
for (const [key, entry] of Object.entries(record.e as Record<string, unknown>)) {
|
|
81
|
+
if (isStoredEntry(entry)) entries.set(key, entry)
|
|
82
|
+
}
|
|
83
|
+
return entries
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function encodeBucket(entries: BucketEntries): Buffer {
|
|
87
|
+
const body: Record<string, StoredEntry> = {}
|
|
88
|
+
for (const [key, entry] of entries) body[key] = entry
|
|
89
|
+
return Buffer.from(JSON.stringify({ v: BUCKET_FORMAT_VERSION, e: body }), 'utf8')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function estimateEntryBytes(key: string, entry: StoredEntry): number {
|
|
93
|
+
return Buffer.byteLength(JSON.stringify(key), 'utf8') + Buffer.byteLength(JSON.stringify(entry), 'utf8') + 2
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const BUCKET_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ v: BUCKET_FORMAT_VERSION, e: {} }), 'utf8')
|
|
97
|
+
|
|
98
|
+
export function isEntryExpired(entry: StoredEntry, now: number): boolean {
|
|
99
|
+
return entry.x !== null && entry.x <= now
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Drops the oldest routing groups (value + metadata pairs) not listed in
|
|
104
|
+
* `protectedRoutes` until the encoded bucket fits `limitBytes`. Returns the
|
|
105
|
+
* encoded bucket and the number of physical records evicted, or null when the
|
|
106
|
+
* protected entries alone exceed the limit.
|
|
107
|
+
*/
|
|
108
|
+
export function fitBucket(
|
|
109
|
+
entries: BucketEntries,
|
|
110
|
+
limitBytes: number,
|
|
111
|
+
protectedRoutes: ReadonlySet<string>,
|
|
112
|
+
): { buffer: Buffer; evicted: number } | null {
|
|
113
|
+
let buffer = encodeBucket(entries)
|
|
114
|
+
if (buffer.length <= limitBytes) return { buffer, evicted: 0 }
|
|
115
|
+
const groups = new Map<string, { keys: string[]; newest: number; bytes: number }>()
|
|
116
|
+
for (const [key, entry] of entries) {
|
|
117
|
+
const route = routingKey(key)
|
|
118
|
+
if (protectedRoutes.has(route)) continue
|
|
119
|
+
const group = groups.get(route) ?? { keys: [], newest: 0, bytes: 0 }
|
|
120
|
+
group.keys.push(key)
|
|
121
|
+
group.newest = Math.max(group.newest, entry.c)
|
|
122
|
+
group.bytes += estimateEntryBytes(key, entry)
|
|
123
|
+
groups.set(route, group)
|
|
124
|
+
}
|
|
125
|
+
const ordered = Array.from(groups.values()).sort((left, right) => left.newest - right.newest)
|
|
126
|
+
let excess = buffer.length - limitBytes
|
|
127
|
+
let evicted = 0
|
|
128
|
+
for (const group of ordered) {
|
|
129
|
+
for (const key of group.keys) entries.delete(key)
|
|
130
|
+
evicted += group.keys.length
|
|
131
|
+
excess -= group.bytes
|
|
132
|
+
if (excess <= 0) {
|
|
133
|
+
buffer = encodeBucket(entries)
|
|
134
|
+
if (buffer.length <= limitBytes) return { buffer, evicted }
|
|
135
|
+
excess = buffer.length - limitBytes
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
buffer = encodeBucket(entries)
|
|
139
|
+
return buffer.length <= limitBytes ? { buffer, evicted } : null
|
|
140
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { MemcachedConnection } from './connection'
|
|
2
|
+
import { MemcachedProtocolError } from './errors'
|
|
3
|
+
import type { MemcachedTransport } from './transport'
|
|
4
|
+
import {
|
|
5
|
+
addCommand,
|
|
6
|
+
casCommand,
|
|
7
|
+
getsCommand,
|
|
8
|
+
metaDeleteCommand,
|
|
9
|
+
metaGetCommand,
|
|
10
|
+
metaGetManyCommand,
|
|
11
|
+
metaSetCommand,
|
|
12
|
+
noopCommand,
|
|
13
|
+
statsCommand,
|
|
14
|
+
versionCommand,
|
|
15
|
+
type ClassicStoreOptions,
|
|
16
|
+
type ClassicStoreOutcome,
|
|
17
|
+
type EncodedCommand,
|
|
18
|
+
type MemcachedItem,
|
|
19
|
+
type MetaDeleteOutcome,
|
|
20
|
+
type MetaSetOptions,
|
|
21
|
+
type MetaSetOutcome,
|
|
22
|
+
} from './commands'
|
|
23
|
+
|
|
24
|
+
export const MAX_COMMAND_BYTES = 16 * 1024
|
|
25
|
+
export const DEFAULT_POOL_SIZE = 2
|
|
26
|
+
export const DEFAULT_CONNECT_TIMEOUT_MS = 2_000
|
|
27
|
+
export const DEFAULT_COMMAND_TIMEOUT_MS = 2_000
|
|
28
|
+
|
|
29
|
+
export type MemcachedClientOptions = {
|
|
30
|
+
transport: MemcachedTransport
|
|
31
|
+
poolSize?: number
|
|
32
|
+
connectTimeoutMs?: number
|
|
33
|
+
commandTimeoutMs?: number
|
|
34
|
+
/** Upper bound for the command bytes of one batched request (default and maximum 16 KiB). */
|
|
35
|
+
maxCommandBytes?: number
|
|
36
|
+
/** Upper bound for the number of keys fetched by one batched request. */
|
|
37
|
+
maxKeysPerBatch?: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type MemcachedCommandName = 'mg' | 'ms' | 'md' | 'mn' | 'gets' | 'add' | 'cas' | 'version' | 'stats'
|
|
41
|
+
|
|
42
|
+
export type MemcachedClient = {
|
|
43
|
+
metaGet(key: string): Promise<MemcachedItem | null>
|
|
44
|
+
metaGetMany(keys: string[]): Promise<Map<string, MemcachedItem>>
|
|
45
|
+
metaSet(key: string, value: Buffer, options?: MetaSetOptions): Promise<MetaSetOutcome>
|
|
46
|
+
metaDelete(key: string, options?: { cas?: string }): Promise<MetaDeleteOutcome>
|
|
47
|
+
gets(keys: string[]): Promise<Map<string, MemcachedItem>>
|
|
48
|
+
add(key: string, value: Buffer, options?: ClassicStoreOptions): Promise<ClassicStoreOutcome>
|
|
49
|
+
cas(key: string, value: Buffer, cas: string, options?: ClassicStoreOptions): Promise<ClassicStoreOutcome>
|
|
50
|
+
noop(): Promise<void>
|
|
51
|
+
version(): Promise<string>
|
|
52
|
+
stats(group?: string): Promise<Map<string, string>>
|
|
53
|
+
commandCounts(): Record<MemcachedCommandName, number>
|
|
54
|
+
describe(): string
|
|
55
|
+
close(): Promise<void>
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function boundedInteger(value: number | undefined, fallback: number, min: number, max: number): number {
|
|
59
|
+
if (value === undefined) return fallback
|
|
60
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
61
|
+
throw new MemcachedProtocolError('protocol_error', `Memcached client option must be an integer between ${min} and ${max}`)
|
|
62
|
+
}
|
|
63
|
+
return value
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Splits keys into batches whose pipelined command text stays within
|
|
68
|
+
* `maxCommandBytes` and whose key count stays within `maxKeys`.
|
|
69
|
+
*/
|
|
70
|
+
export function planKeyBatches(keys: string[], lineBytes: (key: string) => number, maxCommandBytes: number, maxKeys: number): string[][] {
|
|
71
|
+
const batches: string[][] = []
|
|
72
|
+
let current: string[] = []
|
|
73
|
+
let currentBytes = 0
|
|
74
|
+
for (const key of keys) {
|
|
75
|
+
const bytes = lineBytes(key)
|
|
76
|
+
if (bytes > maxCommandBytes) {
|
|
77
|
+
throw new MemcachedProtocolError('command_too_large', 'A single memcached key exceeds the command size limit')
|
|
78
|
+
}
|
|
79
|
+
if (current.length > 0 && (currentBytes + bytes > maxCommandBytes || current.length >= maxKeys)) {
|
|
80
|
+
batches.push(current)
|
|
81
|
+
current = []
|
|
82
|
+
currentBytes = 0
|
|
83
|
+
}
|
|
84
|
+
current.push(key)
|
|
85
|
+
currentBytes += bytes
|
|
86
|
+
}
|
|
87
|
+
if (current.length > 0) batches.push(current)
|
|
88
|
+
return batches
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const META_GET_MANY_OVERHEAD = 'mg v c f k q\r\n'.length
|
|
92
|
+
const META_GET_MANY_TERMINATOR = 'mn\r\n'.length
|
|
93
|
+
const GETS_OVERHEAD = 'gets\r\n'.length
|
|
94
|
+
|
|
95
|
+
export function createMemcachedClient(options: MemcachedClientOptions): MemcachedClient {
|
|
96
|
+
const transport = options.transport
|
|
97
|
+
const poolSize = boundedInteger(options.poolSize, DEFAULT_POOL_SIZE, 1, 64)
|
|
98
|
+
const connectTimeoutMs = boundedInteger(options.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS, 1, 120_000)
|
|
99
|
+
const commandTimeoutMs = boundedInteger(options.commandTimeoutMs, DEFAULT_COMMAND_TIMEOUT_MS, 1, 120_000)
|
|
100
|
+
const maxCommandBytes = boundedInteger(options.maxCommandBytes, MAX_COMMAND_BYTES, 256, MAX_COMMAND_BYTES)
|
|
101
|
+
const maxKeysPerBatch = boundedInteger(options.maxKeysPerBatch, 512, 1, 4096)
|
|
102
|
+
const slots: Array<Promise<MemcachedConnection> | null> = Array.from({ length: poolSize }, () => null)
|
|
103
|
+
const counts: Record<MemcachedCommandName, number> = {
|
|
104
|
+
mg: 0, ms: 0, md: 0, mn: 0, gets: 0, add: 0, cas: 0, version: 0, stats: 0,
|
|
105
|
+
}
|
|
106
|
+
let cursor = 0
|
|
107
|
+
let closed = false
|
|
108
|
+
|
|
109
|
+
const openSlot = (index: number): Promise<MemcachedConnection> => {
|
|
110
|
+
const opening = MemcachedConnection.open(transport, { connectTimeoutMs, commandTimeoutMs }).then(
|
|
111
|
+
(connection) => {
|
|
112
|
+
if (closed) {
|
|
113
|
+
connection.close()
|
|
114
|
+
throw new MemcachedProtocolError('closed', 'Memcached client is closed')
|
|
115
|
+
}
|
|
116
|
+
return connection
|
|
117
|
+
},
|
|
118
|
+
(error: unknown) => {
|
|
119
|
+
if (slots[index] === opening) slots[index] = null
|
|
120
|
+
throw error
|
|
121
|
+
},
|
|
122
|
+
)
|
|
123
|
+
slots[index] = opening
|
|
124
|
+
return opening
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const acquire = async (): Promise<MemcachedConnection> => {
|
|
128
|
+
if (closed) throw new MemcachedProtocolError('closed', 'Memcached client is closed')
|
|
129
|
+
const index = cursor
|
|
130
|
+
cursor = (cursor + 1) % poolSize
|
|
131
|
+
const slot = slots[index]
|
|
132
|
+
if (slot) {
|
|
133
|
+
const connection = await slot.catch(() => null)
|
|
134
|
+
if (connection && connection.alive) return connection
|
|
135
|
+
if (slots[index] !== slot) return acquire()
|
|
136
|
+
}
|
|
137
|
+
return openSlot(index)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const run = async <T>(name: MemcachedCommandName, build: () => EncodedCommand<T>): Promise<T> => {
|
|
141
|
+
const command = build()
|
|
142
|
+
const connection = await acquire()
|
|
143
|
+
counts[name] += 1
|
|
144
|
+
return connection.send(command.payload, command.parse)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const runBatches = async <T>(
|
|
148
|
+
batches: string[][],
|
|
149
|
+
execute: (batch: string[]) => Promise<Map<string, T>>,
|
|
150
|
+
): Promise<Map<string, T>> => {
|
|
151
|
+
const merged = new Map<string, T>()
|
|
152
|
+
for (let start = 0; start < batches.length; start += poolSize) {
|
|
153
|
+
const wave = batches.slice(start, start + poolSize)
|
|
154
|
+
const results = await Promise.all(wave.map(execute))
|
|
155
|
+
for (const result of results) for (const [key, item] of result) merged.set(key, item)
|
|
156
|
+
}
|
|
157
|
+
return merged
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
metaGet: (key) => run('mg', () => metaGetCommand(key)),
|
|
162
|
+
async metaGetMany(keys) {
|
|
163
|
+
const unique = Array.from(new Set(keys))
|
|
164
|
+
if (unique.length === 0) return new Map()
|
|
165
|
+
const batches = planKeyBatches(
|
|
166
|
+
unique,
|
|
167
|
+
(key) => key.length + META_GET_MANY_OVERHEAD,
|
|
168
|
+
maxCommandBytes - META_GET_MANY_TERMINATOR,
|
|
169
|
+
maxKeysPerBatch,
|
|
170
|
+
)
|
|
171
|
+
return runBatches(batches, (batch) => run('mg', () => metaGetManyCommand(batch)))
|
|
172
|
+
},
|
|
173
|
+
metaSet: (key, value, setOptions) => run('ms', () => metaSetCommand(key, value, setOptions)),
|
|
174
|
+
metaDelete: (key, deleteOptions) => run('md', () => metaDeleteCommand(key, deleteOptions)),
|
|
175
|
+
async gets(keys) {
|
|
176
|
+
const unique = Array.from(new Set(keys))
|
|
177
|
+
if (unique.length === 0) return new Map()
|
|
178
|
+
const batches = planKeyBatches(unique, (key) => key.length + 1, maxCommandBytes - GETS_OVERHEAD, maxKeysPerBatch)
|
|
179
|
+
return runBatches(batches, (batch) => run('gets', () => getsCommand(batch)))
|
|
180
|
+
},
|
|
181
|
+
add: (key, value, storeOptions) => run('add', () => addCommand(key, value, storeOptions)),
|
|
182
|
+
cas: (key, value, cas, storeOptions) => run('cas', () => casCommand(key, value, cas, storeOptions)),
|
|
183
|
+
async noop() {
|
|
184
|
+
await run('mn', () => noopCommand())
|
|
185
|
+
},
|
|
186
|
+
version: () => run('version', () => versionCommand()),
|
|
187
|
+
stats: (group) => run('stats', () => statsCommand(group)),
|
|
188
|
+
commandCounts: () => ({ ...counts }),
|
|
189
|
+
describe: () => transport.describe(),
|
|
190
|
+
async close() {
|
|
191
|
+
if (closed) return
|
|
192
|
+
closed = true
|
|
193
|
+
const pending = slots.splice(0, slots.length)
|
|
194
|
+
await Promise.all(pending.map(async (slot) => {
|
|
195
|
+
if (!slot) return
|
|
196
|
+
const connection = await slot.catch(() => null)
|
|
197
|
+
connection?.close()
|
|
198
|
+
}))
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
}
|