@open-mercato/cache-provider-memcached 0.0.0-stage → 0.11.1-develop.9002.1.e180dacef1

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.
Files changed (41) hide show
  1. package/README.md +166 -2
  2. package/dist/errors.js +46 -0
  3. package/dist/errors.js.map +7 -0
  4. package/dist/index.js +33 -0
  5. package/dist/index.js.map +7 -0
  6. package/dist/layout.js +101 -0
  7. package/dist/layout.js.map +7 -0
  8. package/dist/protocol/client.js +164 -0
  9. package/dist/protocol/client.js.map +7 -0
  10. package/dist/protocol/commands.js +292 -0
  11. package/dist/protocol/commands.js.map +7 -0
  12. package/dist/protocol/connection.js +114 -0
  13. package/dist/protocol/connection.js.map +7 -0
  14. package/dist/protocol/errors.js +28 -0
  15. package/dist/protocol/errors.js.map +7 -0
  16. package/dist/protocol/index.js +37 -0
  17. package/dist/protocol/index.js.map +7 -0
  18. package/dist/protocol/reader.js +75 -0
  19. package/dist/protocol/reader.js.map +7 -0
  20. package/dist/protocol/transport.js +65 -0
  21. package/dist/protocol/transport.js.map +7 -0
  22. package/dist/provider.js +47 -0
  23. package/dist/provider.js.map +7 -0
  24. package/dist/settings.js +49 -0
  25. package/dist/settings.js.map +7 -0
  26. package/dist/strategy.js +342 -0
  27. package/dist/strategy.js.map +7 -0
  28. package/package.json +67 -3
  29. package/src/errors.ts +59 -0
  30. package/src/index.ts +19 -0
  31. package/src/layout.ts +140 -0
  32. package/src/protocol/client.ts +201 -0
  33. package/src/protocol/commands.ts +338 -0
  34. package/src/protocol/connection.ts +138 -0
  35. package/src/protocol/errors.ts +44 -0
  36. package/src/protocol/index.ts +37 -0
  37. package/src/protocol/reader.ts +90 -0
  38. package/src/protocol/transport.ts +107 -0
  39. package/src/provider.ts +54 -0
  40. package/src/settings.ts +55 -0
  41. package/src/strategy.ts +423 -0
@@ -0,0 +1,107 @@
1
+ import net from 'node:net'
2
+ import tls from 'node:tls'
3
+ import { MemcachedProtocolError } from './errors'
4
+
5
+ /**
6
+ * Minimal duplex surface the connection needs. `net.Socket` and
7
+ * `tls.TLSSocket` satisfy it; tests may inject an in-memory implementation.
8
+ */
9
+ export type MemcachedSocket = {
10
+ write(data: Buffer): boolean
11
+ destroy(error?: Error): void
12
+ on(event: 'data', listener: (chunk: Buffer) => void): unknown
13
+ on(event: 'close', listener: () => void): unknown
14
+ on(event: 'error', listener: (error: Error) => void): unknown
15
+ setNoDelay?(noDelay?: boolean): unknown
16
+ setKeepAlive?(enable?: boolean, initialDelay?: number): unknown
17
+ }
18
+
19
+ export type MemcachedTransportOpenOptions = {
20
+ timeoutMs: number
21
+ }
22
+
23
+ /**
24
+ * Opens one connected socket to a single memcached server. `describe()` is a
25
+ * redaction-safe label (never includes credentials).
26
+ */
27
+ export type MemcachedTransport = {
28
+ open(options: MemcachedTransportOpenOptions): Promise<MemcachedSocket>
29
+ describe(): string
30
+ }
31
+
32
+ export type MemcachedTcpEndpoint = {
33
+ host: string
34
+ port: number
35
+ }
36
+
37
+ export type MemcachedTlsOptions = {
38
+ ca?: string | Buffer | Array<string | Buffer>
39
+ cert?: string | Buffer
40
+ key?: string | Buffer
41
+ servername?: string
42
+ rejectUnauthorized?: boolean
43
+ }
44
+
45
+ function connectWithTimeout<TSocket extends net.Socket>(
46
+ create: () => TSocket,
47
+ readyEvent: 'connect' | 'secureConnect',
48
+ timeoutMs: number,
49
+ ): Promise<TSocket> {
50
+ return new Promise<TSocket>((resolve, reject) => {
51
+ const socket = create()
52
+ let settled = false
53
+ const finish = (error: Error | null) => {
54
+ if (settled) return
55
+ settled = true
56
+ clearTimeout(timer)
57
+ socket.removeListener(readyEvent, onReady)
58
+ socket.removeListener('error', onError)
59
+ if (error) {
60
+ socket.destroy()
61
+ reject(error)
62
+ return
63
+ }
64
+ socket.setNoDelay(true)
65
+ socket.setKeepAlive(true, 30_000)
66
+ resolve(socket)
67
+ }
68
+ const onReady = () => finish(null)
69
+ const onError = (error: Error) => finish(new MemcachedProtocolError('unavailable', 'Memcached connection failed', { cause: error }))
70
+ const timer = setTimeout(
71
+ () => finish(new MemcachedProtocolError('timeout', `Memcached connection did not open within ${timeoutMs}ms`)),
72
+ timeoutMs,
73
+ )
74
+ socket.once(readyEvent, onReady)
75
+ socket.once('error', onError)
76
+ })
77
+ }
78
+
79
+ export function createTcpTransport(endpoint: MemcachedTcpEndpoint): MemcachedTransport {
80
+ return {
81
+ open: ({ timeoutMs }) => connectWithTimeout(
82
+ () => net.connect({ host: endpoint.host, port: endpoint.port }),
83
+ 'connect',
84
+ timeoutMs,
85
+ ),
86
+ describe: () => `tcp:${endpoint.host}:${endpoint.port}`,
87
+ }
88
+ }
89
+
90
+ export function createTlsTransport(endpoint: MemcachedTcpEndpoint, options: MemcachedTlsOptions = {}): MemcachedTransport {
91
+ return {
92
+ open: ({ timeoutMs }) => connectWithTimeout(
93
+ () => tls.connect({
94
+ host: endpoint.host,
95
+ port: endpoint.port,
96
+ servername: options.servername ?? (net.isIP(endpoint.host) ? undefined : endpoint.host),
97
+ ...(options.ca !== undefined ? { ca: options.ca } : {}),
98
+ ...(options.cert !== undefined ? { cert: options.cert } : {}),
99
+ ...(options.key !== undefined ? { key: options.key } : {}),
100
+ rejectUnauthorized: options.rejectUnauthorized ?? true,
101
+ }),
102
+ 'secureConnect',
103
+ timeoutMs,
104
+ ),
105
+ describe: () => `tls:${endpoint.host}:${endpoint.port}`,
106
+ }
107
+ }
@@ -0,0 +1,54 @@
1
+ import { defineCacheProvider, type CacheProviderHostContext } from '@open-mercato/cache/provider'
2
+ import { createMemcachedClient, type MemcachedClient } from './protocol/client'
3
+ import { createTcpTransport, type MemcachedTransport } from './protocol/transport'
4
+ import { toProviderFailure } from './errors'
5
+ import {
6
+ MEMCACHED_PROVIDER_ID,
7
+ memcachedSettingsSchema,
8
+ redactMemcachedSettings,
9
+ type MemcachedProviderConfig,
10
+ } from './settings'
11
+ import { createMemcachedStrategy, probeMemcachedServer, type MemcachedCacheStrategy } from './strategy'
12
+
13
+ export type CreateMemcachedCacheStrategyOptions = {
14
+ /** Override the transport (tests, custom socket setups). Defaults to plain TCP to `host:port`. */
15
+ transport?: MemcachedTransport
16
+ }
17
+
18
+ export async function createMemcachedCacheStrategy(
19
+ config: MemcachedProviderConfig,
20
+ context: CacheProviderHostContext,
21
+ options: CreateMemcachedCacheStrategyOptions = {},
22
+ ): Promise<MemcachedCacheStrategy> {
23
+ const client: MemcachedClient = createMemcachedClient({
24
+ transport: options.transport ?? createTcpTransport({ host: config.host, port: config.port }),
25
+ poolSize: config.poolSize,
26
+ connectTimeoutMs: config.connectTimeoutMs,
27
+ commandTimeoutMs: config.commandTimeoutMs,
28
+ maxCommandBytes: config.maxCommandBytes,
29
+ })
30
+ let server: { itemSizeMax: number | null }
31
+ try {
32
+ server = await probeMemcachedServer(client)
33
+ } catch (error) {
34
+ await client.close().catch(() => undefined)
35
+ throw toProviderFailure(error)
36
+ }
37
+ if (server.itemSizeMax !== null && server.itemSizeMax < config.maxItemBytes) {
38
+ context.logger.warn('server item size limit is lower than maxItemBytes; using the server limit', {
39
+ serverItemSizeMax: server.itemSizeMax,
40
+ maxItemBytes: config.maxItemBytes,
41
+ })
42
+ }
43
+ return createMemcachedStrategy(client, config, context, server)
44
+ }
45
+
46
+ export const provider = defineCacheProvider<MemcachedProviderConfig>({
47
+ id: MEMCACHED_PROVIDER_ID,
48
+ settings: memcachedSettingsSchema,
49
+ capability: () => ({ placement: 'local' }),
50
+ create: (config, context) => createMemcachedCacheStrategy(config, context),
51
+ redact: redactMemcachedSettings,
52
+ })
53
+
54
+ export default provider
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod'
2
+ import { MAX_COMMAND_BYTES } from './protocol/client'
3
+
4
+ export const MEMCACHED_PROVIDER_ID = 'open-mercato/memcached'
5
+
6
+ export const MEMCACHED_SETTINGS_DEFAULTS = {
7
+ port: 11211,
8
+ bucketCount: 64,
9
+ maxItemBytes: 1024 * 1024,
10
+ casRetries: 16,
11
+ casBackoffMs: 4,
12
+ poolSize: 2,
13
+ connectTimeoutMs: 2_000,
14
+ commandTimeoutMs: 2_000,
15
+ maxCommandBytes: MAX_COMMAND_BYTES,
16
+ enumerationBatchSize: 16,
17
+ } as const
18
+
19
+ const loopbackHost = z.enum(['127.0.0.1', '::1'])
20
+
21
+ /**
22
+ * Settings accepted by the first supported profile: one self-hosted memcached
23
+ * server over loopback TCP. Unknown keys (including transport/auth options of
24
+ * unqualified profiles) are rejected.
25
+ */
26
+ export const memcachedSettingsSchema = z.object({
27
+ host: z.string().trim().pipe(loopbackHost),
28
+ port: z.number().int().min(1).max(65535).default(MEMCACHED_SETTINGS_DEFAULTS.port),
29
+ bucketCount: z.number().int().min(1).max(4096).default(MEMCACHED_SETTINGS_DEFAULTS.bucketCount),
30
+ maxItemBytes: z.number().int().min(4 * 1024).max(128 * 1024 * 1024).default(MEMCACHED_SETTINGS_DEFAULTS.maxItemBytes),
31
+ casRetries: z.number().int().min(1).max(100).default(MEMCACHED_SETTINGS_DEFAULTS.casRetries),
32
+ casBackoffMs: z.number().int().min(0).max(1_000).default(MEMCACHED_SETTINGS_DEFAULTS.casBackoffMs),
33
+ poolSize: z.number().int().min(1).max(32).default(MEMCACHED_SETTINGS_DEFAULTS.poolSize),
34
+ connectTimeoutMs: z.number().int().min(50).max(60_000).default(MEMCACHED_SETTINGS_DEFAULTS.connectTimeoutMs),
35
+ commandTimeoutMs: z.number().int().min(50).max(60_000).default(MEMCACHED_SETTINGS_DEFAULTS.commandTimeoutMs),
36
+ maxCommandBytes: z.number().int().min(256).max(MAX_COMMAND_BYTES).default(MEMCACHED_SETTINGS_DEFAULTS.maxCommandBytes),
37
+ enumerationBatchSize: z.number().int().min(1).max(256).default(MEMCACHED_SETTINGS_DEFAULTS.enumerationBatchSize),
38
+ }).strict()
39
+
40
+ export type MemcachedProviderSettingsInput = z.input<typeof memcachedSettingsSchema>
41
+ export type MemcachedProviderConfig = z.output<typeof memcachedSettingsSchema>
42
+
43
+ export function redactMemcachedSettings(config: MemcachedProviderConfig): Record<string, unknown> {
44
+ return {
45
+ host: config.host,
46
+ port: config.port,
47
+ transport: 'tcp',
48
+ bucketCount: config.bucketCount,
49
+ maxItemBytes: config.maxItemBytes,
50
+ casRetries: config.casRetries,
51
+ poolSize: config.poolSize,
52
+ connectTimeoutMs: config.connectTimeoutMs,
53
+ commandTimeoutMs: config.commandTimeoutMs,
54
+ }
55
+ }
@@ -0,0 +1,423 @@
1
+ import type { CacheProviderHostContext } from '@open-mercato/cache/provider'
2
+ import type { CacheGetOptions, CacheSetOptions, CacheStrategy, CacheValue } from '@open-mercato/cache/types'
3
+ import type { MemcachedClient, MemcachedCommandName } from './protocol/client'
4
+ import { MemcachedCacheError, isMemcachedCacheError, toProviderFailure } from './errors'
5
+ import {
6
+ BUCKET_ENVELOPE_BYTES,
7
+ ITEM_OVERHEAD_BYTES,
8
+ allBucketItemKeys,
9
+ bucketIndexFor,
10
+ bucketItemKey,
11
+ decodeBucket,
12
+ estimateEntryBytes,
13
+ fitBucket,
14
+ isEntryExpired,
15
+ routingKey,
16
+ type BucketEntries,
17
+ type StoredEntry,
18
+ } from './layout'
19
+ import type { MemcachedProviderConfig } from './settings'
20
+
21
+ const MAX_COALESCED_MUTATIONS = 64
22
+ const EVICTION_WARNING_INTERVAL_MS = 60_000
23
+
24
+ type MutationContext = {
25
+ now: number
26
+ markDirty(): void
27
+ }
28
+
29
+ type QueuedMutation = {
30
+ apply(entries: BucketEntries, context: MutationContext): unknown
31
+ writesRoute: string | null
32
+ resolve(value: unknown): void
33
+ reject(error: unknown): void
34
+ }
35
+
36
+ type BucketQueue = {
37
+ items: QueuedMutation[]
38
+ running: boolean
39
+ }
40
+
41
+ export type MemcachedStrategyDiagnostics = {
42
+ casConflicts: number
43
+ casRetriesExhausted: number
44
+ capacityEvictions: number
45
+ expiredReclaimed: number
46
+ corruptBucketsReset: number
47
+ serverItemSizeMax: number | null
48
+ effectiveItemLimitBytes: number
49
+ commandCounts: Record<MemcachedCommandName, number>
50
+ }
51
+
52
+ export type MemcachedCacheStrategy = CacheStrategy & {
53
+ healthcheck(): Promise<void>
54
+ cleanup(): Promise<number>
55
+ close(): Promise<void>
56
+ diagnostics(): MemcachedStrategyDiagnostics
57
+ }
58
+
59
+ function sleep(ms: number): Promise<void> {
60
+ return new Promise((resolve) => setTimeout(resolve, ms))
61
+ }
62
+
63
+ function parseItemSizeMax(stats: Map<string, string>): number | null {
64
+ const raw = stats.get('item_size_max')
65
+ const value = raw !== undefined ? Number(raw) : Number.NaN
66
+ return Number.isInteger(value) && value > 0 ? value : null
67
+ }
68
+
69
+ export function createMemcachedStrategy(
70
+ client: MemcachedClient,
71
+ config: MemcachedProviderConfig,
72
+ context: CacheProviderHostContext,
73
+ server: { itemSizeMax: number | null },
74
+ ): MemcachedCacheStrategy {
75
+ const { namespace, helpers, logger } = context
76
+ const bucketCount = config.bucketCount
77
+ const bucketKeys = allBucketItemKeys(namespace, bucketCount)
78
+ const queues = new Map<number, BucketQueue>()
79
+ const diagnostics = {
80
+ casConflicts: 0,
81
+ casRetriesExhausted: 0,
82
+ capacityEvictions: 0,
83
+ expiredReclaimed: 0,
84
+ corruptBucketsReset: 0,
85
+ }
86
+ let serverItemSizeMax = server.itemSizeMax
87
+ let lastEvictionWarning = 0
88
+ let closed: Promise<void> | null = null
89
+
90
+ const longestBucketKey = bucketKeys.reduce((longest, key) => Math.max(longest, key.length), 0)
91
+ const effectiveItemLimit = () => {
92
+ const ceiling = serverItemSizeMax !== null ? Math.min(serverItemSizeMax, config.maxItemBytes) : config.maxItemBytes
93
+ return ceiling - longestBucketKey - ITEM_OVERHEAD_BYTES
94
+ }
95
+
96
+ const guard = async <T>(operation: () => Promise<T>): Promise<T> => {
97
+ try {
98
+ return await operation()
99
+ } catch (error) {
100
+ throw toProviderFailure(error)
101
+ }
102
+ }
103
+
104
+ const readBucket = async (index: number): Promise<BucketEntries> => {
105
+ const item = await client.metaGet(bucketKeys[index])
106
+ if (!item) return new Map()
107
+ return decodeBucket(item.value) ?? new Map()
108
+ }
109
+
110
+ const forEachBucket = async (visit: (index: number, entries: BucketEntries) => void): Promise<void> => {
111
+ for (let start = 0; start < bucketCount; start += config.enumerationBatchSize) {
112
+ const keys = bucketKeys.slice(start, start + config.enumerationBatchSize)
113
+ const items = await client.metaGetMany(keys)
114
+ keys.forEach((key, offset) => {
115
+ const item = items.get(key)
116
+ if (!item) return
117
+ const entries = decodeBucket(item.value)
118
+ visit(start + offset, entries ?? new Map())
119
+ })
120
+ }
121
+ }
122
+
123
+ const warnEviction = (evicted: number) => {
124
+ diagnostics.capacityEvictions += evicted
125
+ const now = Date.now()
126
+ if (now - lastEvictionWarning < EVICTION_WARNING_INTERVAL_MS) return
127
+ lastEvictionWarning = now
128
+ logger.warn('bucket reached the item size limit; oldest entries were evicted', {
129
+ evicted,
130
+ totalEvicted: diagnostics.capacityEvictions,
131
+ bucketCount,
132
+ })
133
+ }
134
+
135
+ const backoff = (attempt: number) => {
136
+ if (config.casBackoffMs <= 0) return Promise.resolve()
137
+ const ceiling = config.casBackoffMs * 2 ** Math.min(attempt, 6)
138
+ return sleep(Math.floor(Math.random() * ceiling) + 1)
139
+ }
140
+
141
+ const commit = async (index: number, batch: QueuedMutation[]): Promise<unknown[]> => {
142
+ const key = bucketKeys[index]
143
+ for (let attempt = 0; attempt < config.casRetries; attempt++) {
144
+ const item = await client.metaGet(key)
145
+ const decoded = item ? decodeBucket(item.value) : null
146
+ const entries: BucketEntries = decoded ?? new Map()
147
+ let dirty = item !== null && decoded === null
148
+ const mutationContext: MutationContext = { now: Date.now(), markDirty: () => { dirty = true } }
149
+ const results = batch.map((mutation) => mutation.apply(entries, mutationContext))
150
+ let reclaimed = 0
151
+ for (const [entryKey, entry] of entries) {
152
+ if (isEntryExpired(entry, mutationContext.now)) {
153
+ entries.delete(entryKey)
154
+ reclaimed += 1
155
+ }
156
+ }
157
+ if (reclaimed > 0) dirty = true
158
+ if (!dirty) return results
159
+
160
+ let outcome: string
161
+ if (entries.size === 0) {
162
+ if (!item) return results
163
+ outcome = await client.metaDelete(key, { cas: item.cas })
164
+ if (outcome === 'deleted' || outcome === 'not_found') {
165
+ diagnostics.expiredReclaimed += reclaimed
166
+ if (item && decoded === null) diagnostics.corruptBucketsReset += 1
167
+ return results
168
+ }
169
+ } else {
170
+ const protectedRoutes = new Set<string>()
171
+ for (const mutation of batch) if (mutation.writesRoute) protectedRoutes.add(mutation.writesRoute)
172
+ const fitted = fitBucket(entries, effectiveItemLimit(), protectedRoutes)
173
+ if (!fitted) {
174
+ throw new MemcachedCacheError('item_too_large', 'Cache entries exceed the memcached item size limit of their bucket')
175
+ }
176
+ outcome = item
177
+ ? await client.metaSet(key, fitted.buffer, { cas: item.cas })
178
+ : await client.metaSet(key, fitted.buffer, { mode: 'add' })
179
+ if (outcome === 'stored') {
180
+ diagnostics.expiredReclaimed += reclaimed
181
+ if (item && decoded === null) diagnostics.corruptBucketsReset += 1
182
+ if (fitted.evicted > 0) warnEviction(fitted.evicted)
183
+ return results
184
+ }
185
+ }
186
+ diagnostics.casConflicts += 1
187
+ await backoff(attempt)
188
+ }
189
+ diagnostics.casRetriesExhausted += 1
190
+ throw new MemcachedCacheError('cas_conflict', `Memcached bucket update did not succeed within ${config.casRetries} compare-and-swap attempts`)
191
+ }
192
+
193
+ const commitWithFallback = async (index: number, batch: QueuedMutation[]): Promise<void> => {
194
+ try {
195
+ const results = await commit(index, batch)
196
+ batch.forEach((mutation, position) => mutation.resolve(results[position]))
197
+ } catch (error) {
198
+ if (batch.length > 1 && isMemcachedCacheError(error) && error.code === 'item_too_large') {
199
+ for (const mutation of batch) {
200
+ try {
201
+ const [result] = await commit(index, [mutation])
202
+ mutation.resolve(result)
203
+ } catch (singleError) {
204
+ mutation.reject(singleError)
205
+ }
206
+ }
207
+ return
208
+ }
209
+ for (const mutation of batch) mutation.reject(error)
210
+ }
211
+ }
212
+
213
+ const drain = async (index: number, queue: BucketQueue): Promise<void> => {
214
+ queue.running = true
215
+ try {
216
+ while (queue.items.length > 0) {
217
+ const batch = queue.items.splice(0, MAX_COALESCED_MUTATIONS)
218
+ await commitWithFallback(index, batch)
219
+ }
220
+ } finally {
221
+ queue.running = false
222
+ if (queue.items.length === 0 && queues.get(index) === queue) queues.delete(index)
223
+ }
224
+ }
225
+
226
+ const mutate = <R>(
227
+ index: number,
228
+ apply: (entries: BucketEntries, context: MutationContext) => R,
229
+ writesRoute: string | null = null,
230
+ ): Promise<R> => new Promise<R>((resolve, reject) => {
231
+ const queue = queues.get(index) ?? { items: [], running: false }
232
+ queues.set(index, queue)
233
+ queue.items.push({
234
+ apply,
235
+ writesRoute,
236
+ resolve: resolve as (value: unknown) => void,
237
+ reject,
238
+ })
239
+ if (!queue.running) void drain(index, queue)
240
+ })
241
+
242
+ const decodeValue = (entry: StoredEntry): { ok: true; value: CacheValue } | { ok: false } => {
243
+ try {
244
+ const raw = entry.b === 1 ? Buffer.from(entry.p, 'base64') : entry.p
245
+ return { ok: true, value: JSON.parse(helpers.decode(raw)) as CacheValue }
246
+ } catch {
247
+ return { ok: false }
248
+ }
249
+ }
250
+
251
+ const dropCorruptEntry = (index: number, key: string, payload: string) => {
252
+ logger.warn('dropping undecodable cache entry')
253
+ mutate(index, (entries, mutationContext) => {
254
+ const current = entries.get(key)
255
+ if (current && current.p === payload) {
256
+ entries.delete(key)
257
+ mutationContext.markDirty()
258
+ }
259
+ return null
260
+ }).catch(() => undefined)
261
+ }
262
+
263
+ const readEntry = async (key: string, returnExpired: boolean): Promise<{ found: false } | { found: true; value: CacheValue }> => {
264
+ const index = bucketIndexFor(key, bucketCount)
265
+ const entries = await readBucket(index)
266
+ const entry = entries.get(key)
267
+ if (!entry) return { found: false }
268
+ if (!returnExpired && isEntryExpired(entry, Date.now())) return { found: false }
269
+ const decoded = decodeValue(entry)
270
+ if (!decoded.ok) {
271
+ dropCorruptEntry(index, key, entry.p)
272
+ return { found: false }
273
+ }
274
+ return { found: true, value: decoded.value }
275
+ }
276
+
277
+ const removeMatching = async (predicate: (entry: StoredEntry, now: number) => boolean): Promise<number> => {
278
+ const candidates: number[] = []
279
+ const now = Date.now()
280
+ await forEachBucket((index, entries) => {
281
+ if (entries.size === 0) {
282
+ candidates.push(index)
283
+ return
284
+ }
285
+ for (const entry of entries.values()) {
286
+ if (predicate(entry, now)) {
287
+ candidates.push(index)
288
+ return
289
+ }
290
+ }
291
+ })
292
+ let removed = 0
293
+ for (let start = 0; start < candidates.length; start += config.enumerationBatchSize) {
294
+ const wave = candidates.slice(start, start + config.enumerationBatchSize)
295
+ const counts = await Promise.all(wave.map((index) => mutate(index, (entries, mutationContext) => {
296
+ let count = 0
297
+ for (const [key, entry] of entries) {
298
+ if (predicate(entry, mutationContext.now)) {
299
+ entries.delete(key)
300
+ count += 1
301
+ }
302
+ }
303
+ if (count > 0) mutationContext.markDirty()
304
+ return count
305
+ })))
306
+ for (const count of counts) removed += count
307
+ }
308
+ return removed
309
+ }
310
+
311
+ const removeKey = (key: string) => mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {
312
+ if (!entries.delete(key)) return false
313
+ mutationContext.markDirty()
314
+ return true
315
+ })
316
+
317
+ const refuseOversize = async (key: string, error: MemcachedCacheError): Promise<never> => {
318
+ await removeKey(key)
319
+ throw error
320
+ }
321
+
322
+ const refreshServerLimits = async () => {
323
+ serverItemSizeMax = parseItemSizeMax(await client.stats('settings')) ?? serverItemSizeMax
324
+ }
325
+
326
+ return {
327
+ get: (key: string, options?: CacheGetOptions) => guard(async () => {
328
+ const result = await readEntry(key, options?.returnExpired === true)
329
+ return result.found ? result.value : null
330
+ }),
331
+
332
+ set: (key: string, value: CacheValue, options?: CacheSetOptions) => guard(async () => {
333
+ const ttl = options?.ttl ?? context.defaultTtl
334
+ const json = JSON.stringify(value === undefined ? null : value)
335
+ const encoded = helpers.encode(json)
336
+ const now = Date.now()
337
+ const entry: StoredEntry = {
338
+ p: typeof encoded === 'string' ? encoded : Buffer.from(encoded).toString('base64'),
339
+ ...(typeof encoded === 'string' ? {} : { b: 1 as const }),
340
+ t: Array.from(new Set(Array.isArray(options?.tags) ? options.tags.filter((tag) => typeof tag === 'string') : [])),
341
+ x: typeof ttl === 'number' && ttl > 0 ? now + ttl : null,
342
+ c: now,
343
+ }
344
+ if (estimateEntryBytes(key, entry) + BUCKET_ENVELOPE_BYTES > effectiveItemLimit()) {
345
+ await refuseOversize(key, new MemcachedCacheError('item_too_large', 'Cache value exceeds the memcached item size limit'))
346
+ }
347
+ try {
348
+ await mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {
349
+ entries.set(key, { ...entry, c: Math.max(entry.c, mutationContext.now) })
350
+ mutationContext.markDirty()
351
+ return null
352
+ }, routingKey(key))
353
+ } catch (error) {
354
+ if (isMemcachedCacheError(error) && error.code === 'item_too_large') await refuseOversize(key, error)
355
+ throw error
356
+ }
357
+ }),
358
+
359
+ has: (key: string) => guard(async () => (await readEntry(key, false)).found),
360
+
361
+ delete: (key: string) => guard(() => removeKey(key)),
362
+
363
+ deleteByTags: (tags: string[]) => guard(async () => {
364
+ const wanted = new Set((Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === 'string' && tag.length > 0))
365
+ if (wanted.size === 0) return 0
366
+ return removeMatching((entry) => entry.t.some((tag) => wanted.has(tag)))
367
+ }),
368
+
369
+ clear: () => guard(() => removeMatching(() => true)),
370
+
371
+ keys: (pattern?: string) => guard(async () => {
372
+ const found: string[] = []
373
+ await forEachBucket((_index, entries) => {
374
+ for (const key of entries.keys()) {
375
+ if (pattern && !helpers.matchPattern(key, pattern)) continue
376
+ found.push(key)
377
+ }
378
+ })
379
+ return found
380
+ }),
381
+
382
+ stats: () => guard(async () => {
383
+ let size = 0
384
+ let expired = 0
385
+ const now = Date.now()
386
+ await forEachBucket((_index, entries) => {
387
+ for (const entry of entries.values()) {
388
+ size += 1
389
+ if (isEntryExpired(entry, now)) expired += 1
390
+ }
391
+ })
392
+ return { size, expired }
393
+ }),
394
+
395
+ cleanup: () => guard(() => removeMatching((entry, now) => isEntryExpired(entry, now))),
396
+
397
+ healthcheck: () => guard(async () => {
398
+ await client.version()
399
+ await refreshServerLimits()
400
+ if (effectiveItemLimit() <= BUCKET_ENVELOPE_BYTES) {
401
+ throw new MemcachedCacheError('incompatible_server', 'Memcached item size limit is too small for the bucket layout')
402
+ }
403
+ }),
404
+
405
+ close: () => {
406
+ if (!closed) closed = client.close()
407
+ return closed
408
+ },
409
+
410
+ diagnostics: () => ({
411
+ ...diagnostics,
412
+ serverItemSizeMax,
413
+ effectiveItemLimitBytes: effectiveItemLimit(),
414
+ commandCounts: client.commandCounts(),
415
+ }),
416
+ }
417
+ }
418
+
419
+ export async function probeMemcachedServer(client: MemcachedClient): Promise<{ version: string; itemSizeMax: number | null }> {
420
+ const version = await client.version()
421
+ const itemSizeMax = parseItemSizeMax(await client.stats('settings'))
422
+ return { version, itemSizeMax }
423
+ }