@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,65 @@
1
+ import net from "node:net";
2
+ import tls from "node:tls";
3
+ import { MemcachedProtocolError } from "./errors.js";
4
+ function connectWithTimeout(create, readyEvent, timeoutMs) {
5
+ return new Promise((resolve, reject) => {
6
+ const socket = create();
7
+ let settled = false;
8
+ const finish = (error) => {
9
+ if (settled) return;
10
+ settled = true;
11
+ clearTimeout(timer);
12
+ socket.removeListener(readyEvent, onReady);
13
+ socket.removeListener("error", onError);
14
+ if (error) {
15
+ socket.destroy();
16
+ reject(error);
17
+ return;
18
+ }
19
+ socket.setNoDelay(true);
20
+ socket.setKeepAlive(true, 3e4);
21
+ resolve(socket);
22
+ };
23
+ const onReady = () => finish(null);
24
+ const onError = (error) => finish(new MemcachedProtocolError("unavailable", "Memcached connection failed", { cause: error }));
25
+ const timer = setTimeout(
26
+ () => finish(new MemcachedProtocolError("timeout", `Memcached connection did not open within ${timeoutMs}ms`)),
27
+ timeoutMs
28
+ );
29
+ socket.once(readyEvent, onReady);
30
+ socket.once("error", onError);
31
+ });
32
+ }
33
+ function createTcpTransport(endpoint) {
34
+ return {
35
+ open: ({ timeoutMs }) => connectWithTimeout(
36
+ () => net.connect({ host: endpoint.host, port: endpoint.port }),
37
+ "connect",
38
+ timeoutMs
39
+ ),
40
+ describe: () => `tcp:${endpoint.host}:${endpoint.port}`
41
+ };
42
+ }
43
+ function createTlsTransport(endpoint, options = {}) {
44
+ return {
45
+ open: ({ timeoutMs }) => connectWithTimeout(
46
+ () => tls.connect({
47
+ host: endpoint.host,
48
+ port: endpoint.port,
49
+ servername: options.servername ?? (net.isIP(endpoint.host) ? void 0 : endpoint.host),
50
+ ...options.ca !== void 0 ? { ca: options.ca } : {},
51
+ ...options.cert !== void 0 ? { cert: options.cert } : {},
52
+ ...options.key !== void 0 ? { key: options.key } : {},
53
+ rejectUnauthorized: options.rejectUnauthorized ?? true
54
+ }),
55
+ "secureConnect",
56
+ timeoutMs
57
+ ),
58
+ describe: () => `tls:${endpoint.host}:${endpoint.port}`
59
+ };
60
+ }
61
+ export {
62
+ createTcpTransport,
63
+ createTlsTransport
64
+ };
65
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/protocol/transport.ts"],
4
+ "sourcesContent": ["import net from 'node:net'\nimport tls from 'node:tls'\nimport { MemcachedProtocolError } from './errors'\n\n/**\n * Minimal duplex surface the connection needs. `net.Socket` and\n * `tls.TLSSocket` satisfy it; tests may inject an in-memory implementation.\n */\nexport type MemcachedSocket = {\n write(data: Buffer): boolean\n destroy(error?: Error): void\n on(event: 'data', listener: (chunk: Buffer) => void): unknown\n on(event: 'close', listener: () => void): unknown\n on(event: 'error', listener: (error: Error) => void): unknown\n setNoDelay?(noDelay?: boolean): unknown\n setKeepAlive?(enable?: boolean, initialDelay?: number): unknown\n}\n\nexport type MemcachedTransportOpenOptions = {\n timeoutMs: number\n}\n\n/**\n * Opens one connected socket to a single memcached server. `describe()` is a\n * redaction-safe label (never includes credentials).\n */\nexport type MemcachedTransport = {\n open(options: MemcachedTransportOpenOptions): Promise<MemcachedSocket>\n describe(): string\n}\n\nexport type MemcachedTcpEndpoint = {\n host: string\n port: number\n}\n\nexport type MemcachedTlsOptions = {\n ca?: string | Buffer | Array<string | Buffer>\n cert?: string | Buffer\n key?: string | Buffer\n servername?: string\n rejectUnauthorized?: boolean\n}\n\nfunction connectWithTimeout<TSocket extends net.Socket>(\n create: () => TSocket,\n readyEvent: 'connect' | 'secureConnect',\n timeoutMs: number,\n): Promise<TSocket> {\n return new Promise<TSocket>((resolve, reject) => {\n const socket = create()\n let settled = false\n const finish = (error: Error | null) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n socket.removeListener(readyEvent, onReady)\n socket.removeListener('error', onError)\n if (error) {\n socket.destroy()\n reject(error)\n return\n }\n socket.setNoDelay(true)\n socket.setKeepAlive(true, 30_000)\n resolve(socket)\n }\n const onReady = () => finish(null)\n const onError = (error: Error) => finish(new MemcachedProtocolError('unavailable', 'Memcached connection failed', { cause: error }))\n const timer = setTimeout(\n () => finish(new MemcachedProtocolError('timeout', `Memcached connection did not open within ${timeoutMs}ms`)),\n timeoutMs,\n )\n socket.once(readyEvent, onReady)\n socket.once('error', onError)\n })\n}\n\nexport function createTcpTransport(endpoint: MemcachedTcpEndpoint): MemcachedTransport {\n return {\n open: ({ timeoutMs }) => connectWithTimeout(\n () => net.connect({ host: endpoint.host, port: endpoint.port }),\n 'connect',\n timeoutMs,\n ),\n describe: () => `tcp:${endpoint.host}:${endpoint.port}`,\n }\n}\n\nexport function createTlsTransport(endpoint: MemcachedTcpEndpoint, options: MemcachedTlsOptions = {}): MemcachedTransport {\n return {\n open: ({ timeoutMs }) => connectWithTimeout(\n () => tls.connect({\n host: endpoint.host,\n port: endpoint.port,\n servername: options.servername ?? (net.isIP(endpoint.host) ? undefined : endpoint.host),\n ...(options.ca !== undefined ? { ca: options.ca } : {}),\n ...(options.cert !== undefined ? { cert: options.cert } : {}),\n ...(options.key !== undefined ? { key: options.key } : {}),\n rejectUnauthorized: options.rejectUnauthorized ?? true,\n }),\n 'secureConnect',\n timeoutMs,\n ),\n describe: () => `tls:${endpoint.host}:${endpoint.port}`,\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,SAAS;AAChB,OAAO,SAAS;AAChB,SAAS,8BAA8B;AA0CvC,SAAS,mBACP,QACA,YACA,WACkB;AAClB,SAAO,IAAI,QAAiB,CAAC,SAAS,WAAW;AAC/C,UAAM,SAAS,OAAO;AACtB,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,UAAwB;AACtC,UAAI,QAAS;AACb,gBAAU;AACV,mBAAa,KAAK;AAClB,aAAO,eAAe,YAAY,OAAO;AACzC,aAAO,eAAe,SAAS,OAAO;AACtC,UAAI,OAAO;AACT,eAAO,QAAQ;AACf,eAAO,KAAK;AACZ;AAAA,MACF;AACA,aAAO,WAAW,IAAI;AACtB,aAAO,aAAa,MAAM,GAAM;AAChC,cAAQ,MAAM;AAAA,IAChB;AACA,UAAM,UAAU,MAAM,OAAO,IAAI;AACjC,UAAM,UAAU,CAAC,UAAi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ider } from "@open-mercato/cache/provider";
2
+ import { createMemcachedClient } from "./protocol/client.js";
3
+ import { createTcpTransport } from "./protocol/transport.js";
4
+ import { toProviderFailure } from "./errors.js";
5
+ import {
6
+ MEMCACHED_PROVIDER_ID,
7
+ memcachedSettingsSchema,
8
+ redactMemcachedSettings
9
+ } from "./settings.js";
10
+ import { createMemcachedStrategy, probeMemcachedServer } from "./strategy.js";
11
+ async function createMemcachedCacheStrategy(config, context, options = {}) {
12
+ const client = createMemcachedClient({
13
+ transport: options.transport ?? createTcpTransport({ host: config.host, port: config.port }),
14
+ poolSize: config.poolSize,
15
+ connectTimeoutMs: config.connectTimeoutMs,
16
+ commandTimeoutMs: config.commandTimeoutMs,
17
+ maxCommandBytes: config.maxCommandBytes
18
+ });
19
+ let server;
20
+ try {
21
+ server = await probeMemcachedServer(client);
22
+ } catch (error) {
23
+ await client.close().catch(() => void 0);
24
+ throw toProviderFailure(error);
25
+ }
26
+ if (server.itemSizeMax !== null && server.itemSizeMax < config.maxItemBytes) {
27
+ context.logger.warn("server item size limit is lower than maxItemBytes; using the server limit", {
28
+ serverItemSizeMax: server.itemSizeMax,
29
+ maxItemBytes: config.maxItemBytes
30
+ });
31
+ }
32
+ return createMemcachedStrategy(client, config, context, server);
33
+ }
34
+ const provider = defineCacheProvider({
35
+ id: MEMCACHED_PROVIDER_ID,
36
+ settings: memcachedSettingsSchema,
37
+ capability: () => ({ placement: "local" }),
38
+ create: (config, context) => createMemcachedCacheStrategy(config, context),
39
+ redact: redactMemcachedSettings
40
+ });
41
+ var provider_default = provider;
42
+ export {
43
+ createMemcachedCacheStrategy,
44
+ provider_default as default,
45
+ provider
46
+ };
47
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/provider.ts"],
4
+ "sourcesContent": ["import { defineCacheProvider, type CacheProviderHostContext } from '@open-mercato/cache/provider'\nimport { createMemcachedClient, type MemcachedClient } from './protocol/client'\nimport { createTcpTransport, type MemcachedTransport } from './protocol/transport'\nimport { toProviderFailure } from './errors'\nimport {\n MEMCACHED_PROVIDER_ID,\n memcachedSettingsSchema,\n redactMemcachedSettings,\n type MemcachedProviderConfig,\n} from './settings'\nimport { createMemcachedStrategy, probeMemcachedServer, type MemcachedCacheStrategy } from './strategy'\n\nexport type CreateMemcachedCacheStrategyOptions = {\n /** Override the transport (tests, custom socket setups). Defaults to plain TCP to `host:port`. */\n transport?: MemcachedTransport\n}\n\nexport async function createMemcachedCacheStrategy(\n config: MemcachedProviderConfig,\n context: CacheProviderHostContext,\n options: CreateMemcachedCacheStrategyOptions = {},\n): Promise<MemcachedCacheStrategy> {\n const client: MemcachedClient = createMemcachedClient({\n transport: options.transport ?? createTcpTransport({ host: config.host, port: config.port }),\n poolSize: config.poolSize,\n connectTimeoutMs: config.connectTimeoutMs,\n commandTimeoutMs: config.commandTimeoutMs,\n maxCommandBytes: config.maxCommandBytes,\n })\n let server: { itemSizeMax: number | null }\n try {\n server = await probeMemcachedServer(client)\n } catch (error) {\n await client.close().catch(() => undefined)\n throw toProviderFailure(error)\n }\n if (server.itemSizeMax !== null && server.itemSizeMax < config.maxItemBytes) {\n context.logger.warn('server item size limit is lower than maxItemBytes; using the server limit', {\n serverItemSizeMax: server.itemSizeMax,\n maxItemBytes: config.maxItemBytes,\n })\n }\n return createMemcachedStrategy(client, config, context, server)\n}\n\nexport const provider = defineCacheProvider<MemcachedProviderConfig>({\n id: MEMCACHED_PROVIDER_ID,\n settings: memcachedSettingsSchema,\n capability: () => ({ placement: 'local' }),\n create: (config, context) => createMemcachedCacheStrategy(config, context),\n redact: redactMemcachedSettings,\n})\n\nexport default provider\n"],
5
+ "mappings": "AAAA,SAAS,2BAA0D;AACnE,SAAS,6BAAmD;AAC5D,SAAS,0BAAmD;AAC5D,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB,4BAAyD;AAO3F,eAAsB,6BACpB,QACA,SACA,UAA+C,CAAC,GACf;AACjC,QAAM,SAA0B,sBAAsB;AAAA,IACpD,WAAW,QAAQ,aAAa,mBAAmB,EAAE,MAAM,OAAO,MAAM,MAAM,OAAO,KAAK,CAAC;AAAA,IAC3F,UAAU,OAAO;AAAA,IACjB,kBAAkB,OAAO;AAAA,IACzB,kBAAkB,OAAO;AAAA,IACzB,iBAAiB,OAAO;AAAA,EAC1B,CAAC;AACD,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,qBAAqB,MAAM;AAAA,EAC5C,SAAS,OAAO;AACd,UAAM,OAAO,MAAM,EAAE,MAAM,MAAM,MAAS;AAC1C,UAAM,kBAAkB,KAAK;AAAA,EAC/B;AACA,MAAI,OAAO,gBAAgB,QAAQ,OAAO,cAAc,OAAO,cAAc;AAC3E,YAAQ,OAAO,KAAK,6EAA6E;AAAA,MAC/F,mBAAmB,OAAO;AAAA,MAC1B,cAAc,OAAO;AAAA,IACvB,CAAC;AAAA,EACH;AACA,SAAO,wBAAwB,QAAQ,QAAQ,SAAS,MAAM;AAChE;AAEO,MAAM,WAAW,oBAA6C;AAAA,EACnE,IAAI;AAAA,EACJ,UAAU;AAAA,EACV,YAAY,OAAO,EAAE,WAAW,QAAQ;AAAA,EACxC,QAAQ,CAAC,QAAQ,YAAY,6BAA6B,QAAQ,OAAO;AAAA,EACzE,QAAQ;AACV,CAAC;AAED,IAAO,mBAAQ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,49 @@
1
+ import { z } from "zod";
2
+ import { MAX_COMMAND_BYTES } from "./protocol/client.js";
3
+ const MEMCACHED_PROVIDER_ID = "open-mercato/memcached";
4
+ const MEMCACHED_SETTINGS_DEFAULTS = {
5
+ port: 11211,
6
+ bucketCount: 64,
7
+ maxItemBytes: 1024 * 1024,
8
+ casRetries: 16,
9
+ casBackoffMs: 4,
10
+ poolSize: 2,
11
+ connectTimeoutMs: 2e3,
12
+ commandTimeoutMs: 2e3,
13
+ maxCommandBytes: MAX_COMMAND_BYTES,
14
+ enumerationBatchSize: 16
15
+ };
16
+ const loopbackHost = z.enum(["127.0.0.1", "::1"]);
17
+ const memcachedSettingsSchema = z.object({
18
+ host: z.string().trim().pipe(loopbackHost),
19
+ port: z.number().int().min(1).max(65535).default(MEMCACHED_SETTINGS_DEFAULTS.port),
20
+ bucketCount: z.number().int().min(1).max(4096).default(MEMCACHED_SETTINGS_DEFAULTS.bucketCount),
21
+ maxItemBytes: z.number().int().min(4 * 1024).max(128 * 1024 * 1024).default(MEMCACHED_SETTINGS_DEFAULTS.maxItemBytes),
22
+ casRetries: z.number().int().min(1).max(100).default(MEMCACHED_SETTINGS_DEFAULTS.casRetries),
23
+ casBackoffMs: z.number().int().min(0).max(1e3).default(MEMCACHED_SETTINGS_DEFAULTS.casBackoffMs),
24
+ poolSize: z.number().int().min(1).max(32).default(MEMCACHED_SETTINGS_DEFAULTS.poolSize),
25
+ connectTimeoutMs: z.number().int().min(50).max(6e4).default(MEMCACHED_SETTINGS_DEFAULTS.connectTimeoutMs),
26
+ commandTimeoutMs: z.number().int().min(50).max(6e4).default(MEMCACHED_SETTINGS_DEFAULTS.commandTimeoutMs),
27
+ maxCommandBytes: z.number().int().min(256).max(MAX_COMMAND_BYTES).default(MEMCACHED_SETTINGS_DEFAULTS.maxCommandBytes),
28
+ enumerationBatchSize: z.number().int().min(1).max(256).default(MEMCACHED_SETTINGS_DEFAULTS.enumerationBatchSize)
29
+ }).strict();
30
+ function redactMemcachedSettings(config) {
31
+ return {
32
+ host: config.host,
33
+ port: config.port,
34
+ transport: "tcp",
35
+ bucketCount: config.bucketCount,
36
+ maxItemBytes: config.maxItemBytes,
37
+ casRetries: config.casRetries,
38
+ poolSize: config.poolSize,
39
+ connectTimeoutMs: config.connectTimeoutMs,
40
+ commandTimeoutMs: config.commandTimeoutMs
41
+ };
42
+ }
43
+ export {
44
+ MEMCACHED_PROVIDER_ID,
45
+ MEMCACHED_SETTINGS_DEFAULTS,
46
+ memcachedSettingsSchema,
47
+ redactMemcachedSettings
48
+ };
49
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/settings.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { MAX_COMMAND_BYTES } from './protocol/client'\n\nexport const MEMCACHED_PROVIDER_ID = 'open-mercato/memcached'\n\nexport const MEMCACHED_SETTINGS_DEFAULTS = {\n port: 11211,\n bucketCount: 64,\n maxItemBytes: 1024 * 1024,\n casRetries: 16,\n casBackoffMs: 4,\n poolSize: 2,\n connectTimeoutMs: 2_000,\n commandTimeoutMs: 2_000,\n maxCommandBytes: MAX_COMMAND_BYTES,\n enumerationBatchSize: 16,\n} as const\n\nconst loopbackHost = z.enum(['127.0.0.1', '::1'])\n\n/**\n * Settings accepted by the first supported profile: one self-hosted memcached\n * server over loopback TCP. Unknown keys (including transport/auth options of\n * unqualified profiles) are rejected.\n */\nexport const memcachedSettingsSchema = z.object({\n host: z.string().trim().pipe(loopbackHost),\n port: z.number().int().min(1).max(65535).default(MEMCACHED_SETTINGS_DEFAULTS.port),\n bucketCount: z.number().int().min(1).max(4096).default(MEMCACHED_SETTINGS_DEFAULTS.bucketCount),\n maxItemBytes: z.number().int().min(4 * 1024).max(128 * 1024 * 1024).default(MEMCACHED_SETTINGS_DEFAULTS.maxItemBytes),\n casRetries: z.number().int().min(1).max(100).default(MEMCACHED_SETTINGS_DEFAULTS.casRetries),\n casBackoffMs: z.number().int().min(0).max(1_000).default(MEMCACHED_SETTINGS_DEFAULTS.casBackoffMs),\n poolSize: z.number().int().min(1).max(32).default(MEMCACHED_SETTINGS_DEFAULTS.poolSize),\n connectTimeoutMs: z.number().int().min(50).max(60_000).default(MEMCACHED_SETTINGS_DEFAULTS.connectTimeoutMs),\n commandTimeoutMs: z.number().int().min(50).max(60_000).default(MEMCACHED_SETTINGS_DEFAULTS.commandTimeoutMs),\n maxCommandBytes: z.number().int().min(256).max(MAX_COMMAND_BYTES).default(MEMCACHED_SETTINGS_DEFAULTS.maxCommandBytes),\n enumerationBatchSize: z.number().int().min(1).max(256).default(MEMCACHED_SETTINGS_DEFAULTS.enumerationBatchSize),\n}).strict()\n\nexport type MemcachedProviderSettingsInput = z.input<typeof memcachedSettingsSchema>\nexport type MemcachedProviderConfig = z.output<typeof memcachedSettingsSchema>\n\nexport function redactMemcachedSettings(config: MemcachedProviderConfig): Record<string, unknown> {\n return {\n host: config.host,\n port: config.port,\n transport: 'tcp',\n bucketCount: config.bucketCount,\n maxItemBytes: config.maxItemBytes,\n casRetries: config.casRetries,\n poolSize: config.poolSize,\n connectTimeoutMs: config.connectTimeoutMs,\n commandTimeoutMs: config.commandTimeoutMs,\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,yBAAyB;AAE3B,MAAM,wBAAwB;AAE9B,MAAM,8BAA8B;AAAA,EACzC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,cAAc,OAAO;AAAA,EACrB,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,sBAAsB;AACxB;AAEA,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,KAAK,CAAC;AAOzC,MAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY;AAAA,EACzC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,KAAK,EAAE,QAAQ,4BAA4B,IAAI;AAAA,EACjF,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,IAAI,EAAE,QAAQ,4BAA4B,WAAW;AAAA,EAC9F,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,IAAI,MAAM,OAAO,IAAI,EAAE,QAAQ,4BAA4B,YAAY;AAAA,EACpH,YAAY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
7
+ decodeBucket,
8
+ estimateEntryBytes,
9
+ fitBucket,
10
+ isEntryExpired,
11
+ routingKey
12
+ } from "./layout.js";
13
+ const MAX_COALESCED_MUTATIONS = 64;
14
+ const EVICTION_WARNING_INTERVAL_MS = 6e4;
15
+ function sleep(ms) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+ function parseItemSizeMax(stats) {
19
+ const raw = stats.get("item_size_max");
20
+ const value = raw !== void 0 ? Number(raw) : Number.NaN;
21
+ return Number.isInteger(value) && value > 0 ? value : null;
22
+ }
23
+ function createMemcachedStrategy(client, config, context, server) {
24
+ const { namespace, helpers, logger } = context;
25
+ const bucketCount = config.bucketCount;
26
+ const bucketKeys = allBucketItemKeys(namespace, bucketCount);
27
+ const queues = /* @__PURE__ */ new Map();
28
+ const diagnostics = {
29
+ casConflicts: 0,
30
+ casRetriesExhausted: 0,
31
+ capacityEvictions: 0,
32
+ expiredReclaimed: 0,
33
+ corruptBucketsReset: 0
34
+ };
35
+ let serverItemSizeMax = server.itemSizeMax;
36
+ let lastEvictionWarning = 0;
37
+ let closed = null;
38
+ const longestBucketKey = bucketKeys.reduce((longest, key) => Math.max(longest, key.length), 0);
39
+ const effectiveItemLimit = () => {
40
+ const ceiling = serverItemSizeMax !== null ? Math.min(serverItemSizeMax, config.maxItemBytes) : config.maxItemBytes;
41
+ return ceiling - longestBucketKey - ITEM_OVERHEAD_BYTES;
42
+ };
43
+ const guard = async (operation) => {
44
+ try {
45
+ return await operation();
46
+ } catch (error) {
47
+ throw toProviderFailure(error);
48
+ }
49
+ };
50
+ const readBucket = async (index) => {
51
+ const item = await client.metaGet(bucketKeys[index]);
52
+ if (!item) return /* @__PURE__ */ new Map();
53
+ return decodeBucket(item.value) ?? /* @__PURE__ */ new Map();
54
+ };
55
+ const forEachBucket = async (visit) => {
56
+ for (let start = 0; start < bucketCount; start += config.enumerationBatchSize) {
57
+ const keys = bucketKeys.slice(start, start + config.enumerationBatchSize);
58
+ const items = await client.metaGetMany(keys);
59
+ keys.forEach((key, offset) => {
60
+ const item = items.get(key);
61
+ if (!item) return;
62
+ const entries = decodeBucket(item.value);
63
+ visit(start + offset, entries ?? /* @__PURE__ */ new Map());
64
+ });
65
+ }
66
+ };
67
+ const warnEviction = (evicted) => {
68
+ diagnostics.capacityEvictions += evicted;
69
+ const now = Date.now();
70
+ if (now - lastEvictionWarning < EVICTION_WARNING_INTERVAL_MS) return;
71
+ lastEvictionWarning = now;
72
+ logger.warn("bucket reached the item size limit; oldest entries were evicted", {
73
+ evicted,
74
+ totalEvicted: diagnostics.capacityEvictions,
75
+ bucketCount
76
+ });
77
+ };
78
+ const backoff = (attempt) => {
79
+ if (config.casBackoffMs <= 0) return Promise.resolve();
80
+ const ceiling = config.casBackoffMs * 2 ** Math.min(attempt, 6);
81
+ return sleep(Math.floor(Math.random() * ceiling) + 1);
82
+ };
83
+ const commit = async (index, batch) => {
84
+ const key = bucketKeys[index];
85
+ for (let attempt = 0; attempt < config.casRetries; attempt++) {
86
+ const item = await client.metaGet(key);
87
+ const decoded = item ? decodeBucket(item.value) : null;
88
+ const entries = decoded ?? /* @__PURE__ */ new Map();
89
+ let dirty = item !== null && decoded === null;
90
+ const mutationContext = { now: Date.now(), markDirty: () => {
91
+ dirty = true;
92
+ } };
93
+ const results = batch.map((mutation) => mutation.apply(entries, mutationContext));
94
+ let reclaimed = 0;
95
+ for (const [entryKey, entry] of entries) {
96
+ if (isEntryExpired(entry, mutationContext.now)) {
97
+ entries.delete(entryKey);
98
+ reclaimed += 1;
99
+ }
100
+ }
101
+ if (reclaimed > 0) dirty = true;
102
+ if (!dirty) return results;
103
+ let outcome;
104
+ if (entries.size === 0) {
105
+ if (!item) return results;
106
+ outcome = await client.metaDelete(key, { cas: item.cas });
107
+ if (outcome === "deleted" || outcome === "not_found") {
108
+ diagnostics.expiredReclaimed += reclaimed;
109
+ if (item && decoded === null) diagnostics.corruptBucketsReset += 1;
110
+ return results;
111
+ }
112
+ } else {
113
+ const protectedRoutes = /* @__PURE__ */ new Set();
114
+ for (const mutation of batch) if (mutation.writesRoute) protectedRoutes.add(mutation.writesRoute);
115
+ const fitted = fitBucket(entries, effectiveItemLimit(), protectedRoutes);
116
+ if (!fitted) {
117
+ throw new MemcachedCacheError("item_too_large", "Cache entries exceed the memcached item size limit of their bucket");
118
+ }
119
+ outcome = item ? await client.metaSet(key, fitted.buffer, { cas: item.cas }) : await client.metaSet(key, fitted.buffer, { mode: "add" });
120
+ if (outcome === "stored") {
121
+ diagnostics.expiredReclaimed += reclaimed;
122
+ if (item && decoded === null) diagnostics.corruptBucketsReset += 1;
123
+ if (fitted.evicted > 0) warnEviction(fitted.evicted);
124
+ return results;
125
+ }
126
+ }
127
+ diagnostics.casConflicts += 1;
128
+ await backoff(attempt);
129
+ }
130
+ diagnostics.casRetriesExhausted += 1;
131
+ throw new MemcachedCacheError("cas_conflict", `Memcached bucket update did not succeed within ${config.casRetries} compare-and-swap attempts`);
132
+ };
133
+ const commitWithFallback = async (index, batch) => {
134
+ try {
135
+ const results = await commit(index, batch);
136
+ batch.forEach((mutation, position) => mutation.resolve(results[position]));
137
+ } catch (error) {
138
+ if (batch.length > 1 && isMemcachedCacheError(error) && error.code === "item_too_large") {
139
+ for (const mutation of batch) {
140
+ try {
141
+ const [result] = await commit(index, [mutation]);
142
+ mutation.resolve(result);
143
+ } catch (singleError) {
144
+ mutation.reject(singleError);
145
+ }
146
+ }
147
+ return;
148
+ }
149
+ for (const mutation of batch) mutation.reject(error);
150
+ }
151
+ };
152
+ const drain = async (index, queue) => {
153
+ queue.running = true;
154
+ try {
155
+ while (queue.items.length > 0) {
156
+ const batch = queue.items.splice(0, MAX_COALESCED_MUTATIONS);
157
+ await commitWithFallback(index, batch);
158
+ }
159
+ } finally {
160
+ queue.running = false;
161
+ if (queue.items.length === 0 && queues.get(index) === queue) queues.delete(index);
162
+ }
163
+ };
164
+ const mutate = (index, apply, writesRoute = null) => new Promise((resolve, reject) => {
165
+ const queue = queues.get(index) ?? { items: [], running: false };
166
+ queues.set(index, queue);
167
+ queue.items.push({
168
+ apply,
169
+ writesRoute,
170
+ resolve,
171
+ reject
172
+ });
173
+ if (!queue.running) void drain(index, queue);
174
+ });
175
+ const decodeValue = (entry) => {
176
+ try {
177
+ const raw = entry.b === 1 ? Buffer.from(entry.p, "base64") : entry.p;
178
+ return { ok: true, value: JSON.parse(helpers.decode(raw)) };
179
+ } catch {
180
+ return { ok: false };
181
+ }
182
+ };
183
+ const dropCorruptEntry = (index, key, payload) => {
184
+ logger.warn("dropping undecodable cache entry");
185
+ mutate(index, (entries, mutationContext) => {
186
+ const current = entries.get(key);
187
+ if (current && current.p === payload) {
188
+ entries.delete(key);
189
+ mutationContext.markDirty();
190
+ }
191
+ return null;
192
+ }).catch(() => void 0);
193
+ };
194
+ const readEntry = async (key, returnExpired) => {
195
+ const index = bucketIndexFor(key, bucketCount);
196
+ const entries = await readBucket(index);
197
+ const entry = entries.get(key);
198
+ if (!entry) return { found: false };
199
+ if (!returnExpired && isEntryExpired(entry, Date.now())) return { found: false };
200
+ const decoded = decodeValue(entry);
201
+ if (!decoded.ok) {
202
+ dropCorruptEntry(index, key, entry.p);
203
+ return { found: false };
204
+ }
205
+ return { found: true, value: decoded.value };
206
+ };
207
+ const removeMatching = async (predicate) => {
208
+ const candidates = [];
209
+ const now = Date.now();
210
+ await forEachBucket((index, entries) => {
211
+ if (entries.size === 0) {
212
+ candidates.push(index);
213
+ return;
214
+ }
215
+ for (const entry of entries.values()) {
216
+ if (predicate(entry, now)) {
217
+ candidates.push(index);
218
+ return;
219
+ }
220
+ }
221
+ });
222
+ let removed = 0;
223
+ for (let start = 0; start < candidates.length; start += config.enumerationBatchSize) {
224
+ const wave = candidates.slice(start, start + config.enumerationBatchSize);
225
+ const counts = await Promise.all(wave.map((index) => mutate(index, (entries, mutationContext) => {
226
+ let count = 0;
227
+ for (const [key, entry] of entries) {
228
+ if (predicate(entry, mutationContext.now)) {
229
+ entries.delete(key);
230
+ count += 1;
231
+ }
232
+ }
233
+ if (count > 0) mutationContext.markDirty();
234
+ return count;
235
+ })));
236
+ for (const count of counts) removed += count;
237
+ }
238
+ return removed;
239
+ };
240
+ const removeKey = (key) => mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {
241
+ if (!entries.delete(key)) return false;
242
+ mutationContext.markDirty();
243
+ return true;
244
+ });
245
+ const refuseOversize = async (key, error) => {
246
+ await removeKey(key);
247
+ throw error;
248
+ };
249
+ const refreshServerLimits = async () => {
250
+ serverItemSizeMax = parseItemSizeMax(await client.stats("settings")) ?? serverItemSizeMax;
251
+ };
252
+ return {
253
+ get: (key, options) => guard(async () => {
254
+ const result = await readEntry(key, options?.returnExpired === true);
255
+ return result.found ? result.value : null;
256
+ }),
257
+ set: (key, value, options) => guard(async () => {
258
+ const ttl = options?.ttl ?? context.defaultTtl;
259
+ const json = JSON.stringify(value === void 0 ? null : value);
260
+ const encoded = helpers.encode(json);
261
+ const now = Date.now();
262
+ const entry = {
263
+ p: typeof encoded === "string" ? encoded : Buffer.from(encoded).toString("base64"),
264
+ ...typeof encoded === "string" ? {} : { b: 1 },
265
+ t: Array.from(new Set(Array.isArray(options?.tags) ? options.tags.filter((tag) => typeof tag === "string") : [])),
266
+ x: typeof ttl === "number" && ttl > 0 ? now + ttl : null,
267
+ c: now
268
+ };
269
+ if (estimateEntryBytes(key, entry) + BUCKET_ENVELOPE_BYTES > effectiveItemLimit()) {
270
+ await refuseOversize(key, new MemcachedCacheError("item_too_large", "Cache value exceeds the memcached item size limit"));
271
+ }
272
+ try {
273
+ await mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {
274
+ entries.set(key, { ...entry, c: Math.max(entry.c, mutationContext.now) });
275
+ mutationContext.markDirty();
276
+ return null;
277
+ }, routingKey(key));
278
+ } catch (error) {
279
+ if (isMemcachedCacheError(error) && error.code === "item_too_large") await refuseOversize(key, error);
280
+ throw error;
281
+ }
282
+ }),
283
+ has: (key) => guard(async () => (await readEntry(key, false)).found),
284
+ delete: (key) => guard(() => removeKey(key)),
285
+ deleteByTags: (tags) => guard(async () => {
286
+ const wanted = new Set((Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === "string" && tag.length > 0));
287
+ if (wanted.size === 0) return 0;
288
+ return removeMatching((entry) => entry.t.some((tag) => wanted.has(tag)));
289
+ }),
290
+ clear: () => guard(() => removeMatching(() => true)),
291
+ keys: (pattern) => guard(async () => {
292
+ const found = [];
293
+ await forEachBucket((_index, entries) => {
294
+ for (const key of entries.keys()) {
295
+ if (pattern && !helpers.matchPattern(key, pattern)) continue;
296
+ found.push(key);
297
+ }
298
+ });
299
+ return found;
300
+ }),
301
+ stats: () => guard(async () => {
302
+ let size = 0;
303
+ let expired = 0;
304
+ const now = Date.now();
305
+ await forEachBucket((_index, entries) => {
306
+ for (const entry of entries.values()) {
307
+ size += 1;
308
+ if (isEntryExpired(entry, now)) expired += 1;
309
+ }
310
+ });
311
+ return { size, expired };
312
+ }),
313
+ cleanup: () => guard(() => removeMatching((entry, now) => isEntryExpired(entry, now))),
314
+ healthcheck: () => guard(async () => {
315
+ await client.version();
316
+ await refreshServerLimits();
317
+ if (effectiveItemLimit() <= BUCKET_ENVELOPE_BYTES) {
318
+ throw new MemcachedCacheError("incompatible_server", "Memcached item size limit is too small for the bucket layout");
319
+ }
320
+ }),
321
+ close: () => {
322
+ if (!closed) closed = client.close();
323
+ return closed;
324
+ },
325
+ diagnostics: () => ({
326
+ ...diagnostics,
327
+ serverItemSizeMax,
328
+ effectiveItemLimitBytes: effectiveItemLimit(),
329
+ commandCounts: client.commandCounts()
330
+ })
331
+ };
332
+ }
333
+ async function probeMemcachedServer(client) {
334
+ const version = await client.version();
335
+ const itemSizeMax = parseItemSizeMax(await client.stats("settings"));
336
+ return { version, itemSizeMax };
337
+ }
338
+ export {
339
+ createMemcachedStrategy,
340
+ probeMemcachedServer
341
+ };
342
+ //# sourceMappingURL=strategy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/strategy.ts"],
4
+ "sourcesContent": ["import type { CacheProviderHostContext } from '@open-mercato/cache/provider'\nimport type { CacheGetOptions, CacheSetOptions, CacheStrategy, CacheValue } from '@open-mercato/cache/types'\nimport type { MemcachedClient, MemcachedCommandName } from './protocol/client'\nimport { MemcachedCacheError, isMemcachedCacheError, toProviderFailure } from './errors'\nimport {\n BUCKET_ENVELOPE_BYTES,\n ITEM_OVERHEAD_BYTES,\n allBucketItemKeys,\n bucketIndexFor,\n bucketItemKey,\n decodeBucket,\n estimateEntryBytes,\n fitBucket,\n isEntryExpired,\n routingKey,\n type BucketEntries,\n type StoredEntry,\n} from './layout'\nimport type { MemcachedProviderConfig } from './settings'\n\nconst MAX_COALESCED_MUTATIONS = 64\nconst EVICTION_WARNING_INTERVAL_MS = 60_000\n\ntype MutationContext = {\n now: number\n markDirty(): void\n}\n\ntype QueuedMutation = {\n apply(entries: BucketEntries, context: MutationContext): unknown\n writesRoute: string | null\n resolve(value: unknown): void\n reject(error: unknown): void\n}\n\ntype BucketQueue = {\n items: QueuedMutation[]\n running: boolean\n}\n\nexport type MemcachedStrategyDiagnostics = {\n casConflicts: number\n casRetriesExhausted: number\n capacityEvictions: number\n expiredReclaimed: number\n corruptBucketsReset: number\n serverItemSizeMax: number | null\n effectiveItemLimitBytes: number\n commandCounts: Record<MemcachedCommandName, number>\n}\n\nexport type MemcachedCacheStrategy = CacheStrategy & {\n healthcheck(): Promise<void>\n cleanup(): Promise<number>\n close(): Promise<void>\n diagnostics(): MemcachedStrategyDiagnostics\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction parseItemSizeMax(stats: Map<string, string>): number | null {\n const raw = stats.get('item_size_max')\n const value = raw !== undefined ? Number(raw) : Number.NaN\n return Number.isInteger(value) && value > 0 ? value : null\n}\n\nexport function createMemcachedStrategy(\n client: MemcachedClient,\n config: MemcachedProviderConfig,\n context: CacheProviderHostContext,\n server: { itemSizeMax: number | null },\n): MemcachedCacheStrategy {\n const { namespace, helpers, logger } = context\n const bucketCount = config.bucketCount\n const bucketKeys = allBucketItemKeys(namespace, bucketCount)\n const queues = new Map<number, BucketQueue>()\n const diagnostics = {\n casConflicts: 0,\n casRetriesExhausted: 0,\n capacityEvictions: 0,\n expiredReclaimed: 0,\n corruptBucketsReset: 0,\n }\n let serverItemSizeMax = server.itemSizeMax\n let lastEvictionWarning = 0\n let closed: Promise<void> | null = null\n\n const longestBucketKey = bucketKeys.reduce((longest, key) => Math.max(longest, key.length), 0)\n const effectiveItemLimit = () => {\n const ceiling = serverItemSizeMax !== null ? Math.min(serverItemSizeMax, config.maxItemBytes) : config.maxItemBytes\n return ceiling - longestBucketKey - ITEM_OVERHEAD_BYTES\n }\n\n const guard = async <T>(operation: () => Promise<T>): Promise<T> => {\n try {\n return await operation()\n } catch (error) {\n throw toProviderFailure(error)\n }\n }\n\n const readBucket = async (index: number): Promise<BucketEntries> => {\n const item = await client.metaGet(bucketKeys[index])\n if (!item) return new Map()\n return decodeBucket(item.value) ?? new Map()\n }\n\n const forEachBucket = async (visit: (index: number, entries: BucketEntries) => void): Promise<void> => {\n for (let start = 0; start < bucketCount; start += config.enumerationBatchSize) {\n const keys = bucketKeys.slice(start, start + config.enumerationBatchSize)\n const items = await client.metaGetMany(keys)\n keys.forEach((key, offset) => {\n const item = items.get(key)\n if (!item) return\n const entries = decodeBucket(item.value)\n visit(start + offset, entries ?? new Map())\n })\n }\n }\n\n const warnEviction = (evicted: number) => {\n diagnostics.capacityEvictions += evicted\n const now = Date.now()\n if (now - lastEvictionWarning < EVICTION_WARNING_INTERVAL_MS) return\n lastEvictionWarning = now\n logger.warn('bucket reached the item size limit; oldest entries were evicted', {\n evicted,\n totalEvicted: diagnostics.capacityEvictions,\n bucketCount,\n })\n }\n\n const backoff = (attempt: number) => {\n if (config.casBackoffMs <= 0) return Promise.resolve()\n const ceiling = config.casBackoffMs * 2 ** Math.min(attempt, 6)\n return sleep(Math.floor(Math.random() * ceiling) + 1)\n }\n\n const commit = async (index: number, batch: QueuedMutation[]): Promise<unknown[]> => {\n const key = bucketKeys[index]\n for (let attempt = 0; attempt < config.casRetries; attempt++) {\n const item = await client.metaGet(key)\n const decoded = item ? decodeBucket(item.value) : null\n const entries: BucketEntries = decoded ?? new Map()\n let dirty = item !== null && decoded === null\n const mutationContext: MutationContext = { now: Date.now(), markDirty: () => { dirty = true } }\n const results = batch.map((mutation) => mutation.apply(entries, mutationContext))\n let reclaimed = 0\n for (const [entryKey, entry] of entries) {\n if (isEntryExpired(entry, mutationContext.now)) {\n entries.delete(entryKey)\n reclaimed += 1\n }\n }\n if (reclaimed > 0) dirty = true\n if (!dirty) return results\n\n let outcome: string\n if (entries.size === 0) {\n if (!item) return results\n outcome = await client.metaDelete(key, { cas: item.cas })\n if (outcome === 'deleted' || outcome === 'not_found') {\n diagnostics.expiredReclaimed += reclaimed\n if (item && decoded === null) diagnostics.corruptBucketsReset += 1\n return results\n }\n } else {\n const protectedRoutes = new Set<string>()\n for (const mutation of batch) if (mutation.writesRoute) protectedRoutes.add(mutation.writesRoute)\n const fitted = fitBucket(entries, effectiveItemLimit(), protectedRoutes)\n if (!fitted) {\n throw new MemcachedCacheError('item_too_large', 'Cache entries exceed the memcached item size limit of their bucket')\n }\n outcome = item\n ? await client.metaSet(key, fitted.buffer, { cas: item.cas })\n : await client.metaSet(key, fitted.buffer, { mode: 'add' })\n if (outcome === 'stored') {\n diagnostics.expiredReclaimed += reclaimed\n if (item && decoded === null) diagnostics.corruptBucketsReset += 1\n if (fitted.evicted > 0) warnEviction(fitted.evicted)\n return results\n }\n }\n diagnostics.casConflicts += 1\n await backoff(attempt)\n }\n diagnostics.casRetriesExhausted += 1\n throw new MemcachedCacheError('cas_conflict', `Memcached bucket update did not succeed within ${config.casRetries} compare-and-swap attempts`)\n }\n\n const commitWithFallback = async (index: number, batch: QueuedMutation[]): Promise<void> => {\n try {\n const results = await commit(index, batch)\n batch.forEach((mutation, position) => mutation.resolve(results[position]))\n } catch (error) {\n if (batch.length > 1 && isMemcachedCacheError(error) && error.code === 'item_too_large') {\n for (const mutation of batch) {\n try {\n const [result] = await commit(index, [mutation])\n mutation.resolve(result)\n } catch (singleError) {\n mutation.reject(singleError)\n }\n }\n return\n }\n for (const mutation of batch) mutation.reject(error)\n }\n }\n\n const drain = async (index: number, queue: BucketQueue): Promise<void> => {\n queue.running = true\n try {\n while (queue.items.length > 0) {\n const batch = queue.items.splice(0, MAX_COALESCED_MUTATIONS)\n await commitWithFallback(index, batch)\n }\n } finally {\n queue.running = false\n if (queue.items.length === 0 && queues.get(index) === queue) queues.delete(index)\n }\n }\n\n const mutate = <R>(\n index: number,\n apply: (entries: BucketEntries, context: MutationContext) => R,\n writesRoute: string | null = null,\n ): Promise<R> => new Promise<R>((resolve, reject) => {\n const queue = queues.get(index) ?? { items: [], running: false }\n queues.set(index, queue)\n queue.items.push({\n apply,\n writesRoute,\n resolve: resolve as (value: unknown) => void,\n reject,\n })\n if (!queue.running) void drain(index, queue)\n })\n\n const decodeValue = (entry: StoredEntry): { ok: true; value: CacheValue } | { ok: false } => {\n try {\n const raw = entry.b === 1 ? Buffer.from(entry.p, 'base64') : entry.p\n return { ok: true, value: JSON.parse(helpers.decode(raw)) as CacheValue }\n } catch {\n return { ok: false }\n }\n }\n\n const dropCorruptEntry = (index: number, key: string, payload: string) => {\n logger.warn('dropping undecodable cache entry')\n mutate(index, (entries, mutationContext) => {\n const current = entries.get(key)\n if (current && current.p === payload) {\n entries.delete(key)\n mutationContext.markDirty()\n }\n return null\n }).catch(() => undefined)\n }\n\n const readEntry = async (key: string, returnExpired: boolean): Promise<{ found: false } | { found: true; value: CacheValue }> => {\n const index = bucketIndexFor(key, bucketCount)\n const entries = await readBucket(index)\n const entry = entries.get(key)\n if (!entry) return { found: false }\n if (!returnExpired && isEntryExpired(entry, Date.now())) return { found: false }\n const decoded = decodeValue(entry)\n if (!decoded.ok) {\n dropCorruptEntry(index, key, entry.p)\n return { found: false }\n }\n return { found: true, value: decoded.value }\n }\n\n const removeMatching = async (predicate: (entry: StoredEntry, now: number) => boolean): Promise<number> => {\n const candidates: number[] = []\n const now = Date.now()\n await forEachBucket((index, entries) => {\n if (entries.size === 0) {\n candidates.push(index)\n return\n }\n for (const entry of entries.values()) {\n if (predicate(entry, now)) {\n candidates.push(index)\n return\n }\n }\n })\n let removed = 0\n for (let start = 0; start < candidates.length; start += config.enumerationBatchSize) {\n const wave = candidates.slice(start, start + config.enumerationBatchSize)\n const counts = await Promise.all(wave.map((index) => mutate(index, (entries, mutationContext) => {\n let count = 0\n for (const [key, entry] of entries) {\n if (predicate(entry, mutationContext.now)) {\n entries.delete(key)\n count += 1\n }\n }\n if (count > 0) mutationContext.markDirty()\n return count\n })))\n for (const count of counts) removed += count\n }\n return removed\n }\n\n const removeKey = (key: string) => mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {\n if (!entries.delete(key)) return false\n mutationContext.markDirty()\n return true\n })\n\n const refuseOversize = async (key: string, error: MemcachedCacheError): Promise<never> => {\n await removeKey(key)\n throw error\n }\n\n const refreshServerLimits = async () => {\n serverItemSizeMax = parseItemSizeMax(await client.stats('settings')) ?? serverItemSizeMax\n }\n\n return {\n get: (key: string, options?: CacheGetOptions) => guard(async () => {\n const result = await readEntry(key, options?.returnExpired === true)\n return result.found ? result.value : null\n }),\n\n set: (key: string, value: CacheValue, options?: CacheSetOptions) => guard(async () => {\n const ttl = options?.ttl ?? context.defaultTtl\n const json = JSON.stringify(value === undefined ? null : value)\n const encoded = helpers.encode(json)\n const now = Date.now()\n const entry: StoredEntry = {\n p: typeof encoded === 'string' ? encoded : Buffer.from(encoded).toString('base64'),\n ...(typeof encoded === 'string' ? {} : { b: 1 as const }),\n t: Array.from(new Set(Array.isArray(options?.tags) ? options.tags.filter((tag) => typeof tag === 'string') : [])),\n x: typeof ttl === 'number' && ttl > 0 ? now + ttl : null,\n c: now,\n }\n if (estimateEntryBytes(key, entry) + BUCKET_ENVELOPE_BYTES > effectiveItemLimit()) {\n await refuseOversize(key, new MemcachedCacheError('item_too_large', 'Cache value exceeds the memcached item size limit'))\n }\n try {\n await mutate(bucketIndexFor(key, bucketCount), (entries, mutationContext) => {\n entries.set(key, { ...entry, c: Math.max(entry.c, mutationContext.now) })\n mutationContext.markDirty()\n return null\n }, routingKey(key))\n } catch (error) {\n if (isMemcachedCacheError(error) && error.code === 'item_too_large') await refuseOversize(key, error)\n throw error\n }\n }),\n\n has: (key: string) => guard(async () => (await readEntry(key, false)).found),\n\n delete: (key: string) => guard(() => removeKey(key)),\n\n deleteByTags: (tags: string[]) => guard(async () => {\n const wanted = new Set((Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === 'string' && tag.length > 0))\n if (wanted.size === 0) return 0\n return removeMatching((entry) => entry.t.some((tag) => wanted.has(tag)))\n }),\n\n clear: () => guard(() => removeMatching(() => true)),\n\n keys: (pattern?: string) => guard(async () => {\n const found: string[] = []\n await forEachBucket((_index, entries) => {\n for (const key of entries.keys()) {\n if (pattern && !helpers.matchPattern(key, pattern)) continue\n found.push(key)\n }\n })\n return found\n }),\n\n stats: () => guard(async () => {\n let size = 0\n let expired = 0\n const now = Date.now()\n await forEachBucket((_index, entries) => {\n for (const entry of entries.values()) {\n size += 1\n if (isEntryExpired(entry, now)) expired += 1\n }\n })\n return { size, expired }\n }),\n\n cleanup: () => guard(() => removeMatching((entry, now) => isEntryExpired(entry, now))),\n\n healthcheck: () => guard(async () => {\n await client.version()\n await refreshServerLimits()\n if (effectiveItemLimit() <= BUCKET_ENVELOPE_BYTES) {\n throw new MemcachedCacheError('incompatible_server', 'Memcached item size limit is too small for the bucket layout')\n }\n }),\n\n close: () => {\n if (!closed) closed = client.close()\n return closed\n },\n\n diagnostics: () => ({\n ...diagnostics,\n serverItemSizeMax,\n effectiveItemLimitBytes: effectiveItemLimit(),\n commandCounts: client.commandCounts(),\n }),\n }\n}\n\nexport async function probeMemcachedServer(client: MemcachedClient): Promise<{ version: string; itemSizeMax: number | null }> {\n const version = await client.version()\n const itemSizeMax = parseItemSizeMax(await client.stats('settings'))\n return { version, itemSizeMax }\n}\n"],
5
+ "mappings": "AAGA,SAAS,qBAAqB,uBAAuB,yBAAyB;AAC9E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAGP,MAAM,0BAA0B;AAChC,MAAM,+BAA+B;AAqCrC,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,iBAAiB,OAA2C;AACnE,QAAM,MAAM,MAAM,IAAI,eAAe;AACrC,QAAM,QAAQ,QAAQ,SAAY,OAAO,GAAG,IAAI,OAAO;AACvD,SAAO,OAAO,UAAU,KAAK,KAAK,QAAQ,IAAI,QAAQ;AACxD;AAEO,SAAS,wBACd,QACA,QACA,SACA,QACwB;AACxB,QAAM,EAAE,WAAW,SAAS,OAAO,IAAI;AACvC,QAAM,cAAc,OAAO;AAC3B,QAAM,aAAa,kBAAkB,WAAW,WAAW;AAC3D,QAAM,SAAS,oBAAI,IAAyB;AAC5C,QAAM,cAAc;AAAA,IAClB,cAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA,EACvB;AACA,MAAI,oBAAoB,OAAO;AAC/B,MAAI,sBAAsB;AAC1B,MAAI,SAA+B;AAEnC,QAAM,mBAAmB,WAAW,OAAO,CAAC,SAAS,QAAQ,KAAK,IAAI,SAAS,IAAI,MAAM,GAAG,CAAC;AAC7F,QAAM,qBAAqB,MAAM;AAC/B,UAAM,UAAU,sBAAsB,OAAO,KAAK,IAAI,mBAAmB,OAAO,YAAY,IAAI,OAAO;AACvG,WAAO,UAAU,mBAAmB;AAAA,EACtC;AAEA,QAAM,QAAQ,OAAU,cAA4C;AA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