tricache 0.6.7 → 0.7.0

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 (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +480 -22
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1173 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3705
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +69 -21
  33. package/src/cache-service.ts +987 -190
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +244 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
@@ -0,0 +1,4583 @@
1
+ import {
2
+ CacheEncryption,
3
+ PREFIX_COMPRESSED,
4
+ PREFIX_ENC_COMPRESSED,
5
+ compressBuffer,
6
+ compressWithHeader,
7
+ consoleLogger,
8
+ decompressBuffer,
9
+ decompressWithHeader
10
+ } from "./chunk-PFB5FMEY.js";
11
+
12
+ // src/cache-service.ts
13
+ import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
14
+ import { pack as pack3, unpack as unpack3 } from "msgpackr";
15
+ import crypto2 from "crypto";
16
+ import os2 from "os";
17
+
18
+ // src/worker-pool.ts
19
+ import { Worker } from "worker_threads";
20
+ import { fileURLToPath } from "url";
21
+ import { dirname, join } from "path";
22
+ import os from "os";
23
+ import { existsSync } from "fs";
24
+ var _workerFile;
25
+ var _workerExecArgv = [];
26
+ try {
27
+ const dir = dirname(fileURLToPath(import.meta.url));
28
+ const jsPath = join(dir, "serialize-worker.js");
29
+ const tsPath = join(dir, "serialize-worker.ts");
30
+ if (existsSync(jsPath)) {
31
+ _workerFile = jsPath;
32
+ } else if (existsSync(tsPath)) {
33
+ _workerFile = tsPath;
34
+ _workerExecArgv = ["--import", "tsx"];
35
+ } else {
36
+ _workerFile = jsPath;
37
+ }
38
+ } catch {
39
+ _workerFile = join(__dirname, "serialize-worker.js");
40
+ }
41
+ function getTransferableArrayBuffer(buf) {
42
+ if (buf.buffer instanceof ArrayBuffer) {
43
+ if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
44
+ return buf.buffer;
45
+ }
46
+ }
47
+ if (buf.byteLength >= 131072) {
48
+ const copy = new ArrayBuffer(buf.byteLength);
49
+ new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
50
+ return copy;
51
+ }
52
+ return null;
53
+ }
54
+ var WorkerPool = class {
55
+ workers = [];
56
+ pending = [];
57
+ _nextId = 0;
58
+ _robin = 0;
59
+ _available = false;
60
+ constructor(opts) {
61
+ try {
62
+ const { workers, pending } = this._spawnWorkers(opts);
63
+ this.workers = workers;
64
+ this.pending = pending;
65
+ this._available = true;
66
+ } catch {
67
+ this._destroy();
68
+ }
69
+ }
70
+ _spawnWorkers(opts) {
71
+ const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
72
+ const workerData = {
73
+ keyBase64: opts.keyBase64,
74
+ mode: opts.mode,
75
+ prevKeyBase64: opts.prevKeyBase64 ?? "",
76
+ prevMode: opts.prevMode,
77
+ compression: opts.compression ?? "none",
78
+ compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024
79
+ };
80
+ const workers = [];
81
+ const pendingList = [];
82
+ const createWorker = (index) => {
83
+ const worker = new Worker(_workerFile, {
84
+ workerData,
85
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
86
+ });
87
+ const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
88
+ if (!pendingList[index]) pendingList[index] = pending;
89
+ worker.on("message", (msg) => {
90
+ const entry = pending.get(msg.id);
91
+ if (!entry) return;
92
+ pending.delete(msg.id);
93
+ if (pending.size === 0) worker.unref();
94
+ if (msg.error !== void 0) {
95
+ entry.reject(new Error(msg.error));
96
+ } else if (msg.result !== void 0) {
97
+ if (typeof msg.result === "string") {
98
+ entry.resolve(msg.result);
99
+ } else {
100
+ entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString("utf8"));
101
+ }
102
+ }
103
+ });
104
+ worker.on("error", (err) => {
105
+ for (const [, entry] of pending) entry.reject(err);
106
+ pending.clear();
107
+ worker.unref();
108
+ });
109
+ worker.on("exit", (exitCode) => {
110
+ for (const [, entry] of pending) {
111
+ entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
112
+ }
113
+ pending.clear();
114
+ worker.unref();
115
+ if (this._available && exitCode !== 0 && workers[index] === worker) {
116
+ try {
117
+ workers[index] = createWorker(index);
118
+ } catch {
119
+ }
120
+ }
121
+ });
122
+ worker.unref();
123
+ return worker;
124
+ };
125
+ for (let i = 0; i < size; i++) {
126
+ const worker = createWorker(i);
127
+ workers.push(worker);
128
+ }
129
+ return { workers, pending: pendingList };
130
+ }
131
+ /**
132
+ * Gracefully drain in-flight tasks and re-initialize workers with updated key material.
133
+ * Atomically swaps workers so new requests immediately route to new workers,
134
+ * while existing in-flight operations complete on old workers before termination.
135
+ */
136
+ async drainAndReinit(opts) {
137
+ const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
138
+ const oldWorkers = this.workers;
139
+ const oldPending = this.pending;
140
+ this.workers = newWorkers;
141
+ this.pending = newPending;
142
+ this._robin = 0;
143
+ this._available = true;
144
+ const start = Date.now();
145
+ while (oldPending.some((m) => m.size > 0)) {
146
+ if (Date.now() - start > 5e3) break;
147
+ await new Promise((r) => setTimeout(r, 10));
148
+ }
149
+ for (let i = 0; i < oldWorkers.length; i++) {
150
+ for (const [, entry] of oldPending[i] ?? []) {
151
+ entry.reject(new Error("WorkerPool replaced during key rotation"));
152
+ }
153
+ oldPending[i]?.clear();
154
+ oldWorkers[i]?.terminate().catch(() => {
155
+ });
156
+ }
157
+ }
158
+ get isAvailable() {
159
+ return this._available;
160
+ }
161
+ /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
162
+ encrypt(payload) {
163
+ return this._dispatch("encrypt", payload);
164
+ }
165
+ /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
166
+ decrypt(payload) {
167
+ return this._dispatch("decrypt", payload);
168
+ }
169
+ _dispatch(type, payload) {
170
+ if (!this._available || this.workers.length === 0) {
171
+ return Promise.reject(new Error("WorkerPool is not available"));
172
+ }
173
+ const id = this._nextId++;
174
+ const idx = this._robin;
175
+ const worker = this.workers[idx];
176
+ const pending = this.pending[idx];
177
+ this._robin = (this._robin + 1) % this.workers.length;
178
+ let transferable = null;
179
+ let dataToSend = typeof payload === "string" ? payload : payload;
180
+ if (typeof payload !== "string") {
181
+ transferable = getTransferableArrayBuffer(payload);
182
+ if (transferable) {
183
+ dataToSend = new Uint8Array(transferable);
184
+ }
185
+ } else if (payload.length >= 131072) {
186
+ const buf = Buffer.from(payload, "utf8");
187
+ transferable = getTransferableArrayBuffer(buf);
188
+ if (transferable) {
189
+ dataToSend = new Uint8Array(transferable);
190
+ }
191
+ }
192
+ const transferList = transferable ? [transferable] : [];
193
+ return new Promise((resolve, reject) => {
194
+ pending.set(id, { resolve, reject });
195
+ worker.ref();
196
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
197
+ });
198
+ }
199
+ /** Terminate all worker threads. In-flight promises are rejected. */
200
+ async destroy() {
201
+ this._available = false;
202
+ this._destroy();
203
+ }
204
+ _destroy() {
205
+ for (let i = 0; i < this.workers.length; i++) {
206
+ for (const [, entry] of this.pending[i] ?? []) {
207
+ entry.reject(new Error("WorkerPool destroyed"));
208
+ }
209
+ this.pending[i]?.clear();
210
+ this.workers[i]?.terminate().catch(() => {
211
+ });
212
+ }
213
+ }
214
+ };
215
+ function availableCpus() {
216
+ return os.availableParallelism?.() ?? os.cpus().length;
217
+ }
218
+
219
+ // src/cache-service.ts
220
+ import v8 from "v8";
221
+ import fs2 from "fs";
222
+ import path2 from "path";
223
+
224
+ // src/smart-memory-cache.ts
225
+ import { pack, unpack } from "msgpackr";
226
+
227
+ // src/wasm/bloom-filter-wasm.ts
228
+ var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
229
+ var KEY_STAGING_OFFSET = 2e4;
230
+ var MAX_KEY_BYTES = 512;
231
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
232
+ var WasmBloomFilter = class {
233
+ exports;
234
+ mem;
235
+ stagingTarget;
236
+ encoder = new TextEncoder();
237
+ numBits = 1e5;
238
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
239
+ _maxCapacity;
240
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
241
+ _insertionCount = 0;
242
+ constructor() {
243
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
244
+ this.exports = instance.exports;
245
+ this.mem = new Uint8Array(this.exports.memory.buffer);
246
+ this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
247
+ const k = 7, p = 0.01;
248
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
249
+ }
250
+ writeKey(key) {
251
+ if (key.length === 0) return 0;
252
+ return this.encoder.encodeInto(key, this.stagingTarget).written;
253
+ }
254
+ add(key) {
255
+ const len = this.writeKey(key);
256
+ if (len === 0) return;
257
+ this.exports.add(KEY_STAGING_OFFSET, len);
258
+ this._insertionCount++;
259
+ }
260
+ mightContain(key) {
261
+ const len = this.writeKey(key);
262
+ if (len === 0) return true;
263
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
264
+ }
265
+ reset() {
266
+ this.exports.reset();
267
+ this._insertionCount = 0;
268
+ }
269
+ rebuild(keys) {
270
+ this.reset();
271
+ for (const key of keys) this.add(key);
272
+ }
273
+ get stats() {
274
+ const bitsSet = this.exports.countBits();
275
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
276
+ }
277
+ /** Number of add() calls since last reset/rebuild. */
278
+ get insertions() {
279
+ return this._insertionCount;
280
+ }
281
+ /**
282
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
283
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
284
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
285
+ */
286
+ get maxCapacity() {
287
+ return this._maxCapacity;
288
+ }
289
+ };
290
+
291
+ // src/smart-memory-cache.ts
292
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
293
+ var LARGE_VALUE_BYTES = 16384;
294
+ var EVICTION_BATCH_PERCENT = 0.2;
295
+ var EVICTION_SAMPLE = 16;
296
+ var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
297
+ var JsBloomFilter = class {
298
+ bits;
299
+ numBits;
300
+ k;
301
+ /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
302
+ _maxCapacity;
303
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
304
+ _insertionCount = 0;
305
+ constructor(numBits = 1e5, k = 7) {
306
+ this.numBits = numBits;
307
+ this.k = k;
308
+ this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
309
+ const p = 0.01;
310
+ this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
311
+ }
312
+ fnv1a32(s) {
313
+ let h = 2166136261;
314
+ for (let i = 0; i < s.length; i++) {
315
+ h ^= s.charCodeAt(i);
316
+ h = Math.imul(h, 16777619) >>> 0;
317
+ }
318
+ return h >>> 0;
319
+ }
320
+ djb2(s) {
321
+ let h = 5381;
322
+ for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) >>> 0;
323
+ return h >>> 0;
324
+ }
325
+ setBit(i) {
326
+ this.bits[i >>> 3] |= 1 << (i & 7);
327
+ }
328
+ getBit(i) {
329
+ return (this.bits[i >>> 3] & 1 << (i & 7)) !== 0;
330
+ }
331
+ add(key) {
332
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
333
+ for (let i = 0; i < this.k; i++) this.setBit((h1 + i * h2 >>> 0) % this.numBits);
334
+ this._insertionCount++;
335
+ }
336
+ mightContain(key) {
337
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
338
+ for (let i = 0; i < this.k; i++) if (!this.getBit((h1 + i * h2 >>> 0) % this.numBits)) return false;
339
+ return true;
340
+ }
341
+ reset() {
342
+ this.bits.fill(0);
343
+ this._insertionCount = 0;
344
+ }
345
+ rebuild(keys) {
346
+ this.bits.fill(0);
347
+ this._insertionCount = 0;
348
+ for (const k of keys) this.add(k);
349
+ }
350
+ /** Number of add() calls since last reset/rebuild. */
351
+ get insertions() {
352
+ return this._insertionCount;
353
+ }
354
+ /**
355
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
356
+ * Exact formula for the configured k and target p=1 %:
357
+ * n_max = -m * ln(1 - p^(1/k)) / k
358
+ */
359
+ get maxCapacity() {
360
+ return this._maxCapacity;
361
+ }
362
+ get stats() {
363
+ let bitsSet = 0;
364
+ for (const byte of this.bits) {
365
+ let b = byte;
366
+ while (b) {
367
+ bitsSet++;
368
+ b &= b - 1;
369
+ }
370
+ }
371
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
372
+ }
373
+ };
374
+ function createBloomFilter(logger, maxEntries) {
375
+ const LN2_SQ = Math.LN2 * Math.LN2;
376
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
377
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
378
+ try {
379
+ const wasm = new WasmBloomFilter();
380
+ if (wasm.maxCapacity >= maxEntries) {
381
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
382
+ return wasm;
383
+ }
384
+ logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
385
+ wasmCapacity: wasm.maxCapacity,
386
+ maxEntries,
387
+ optimalBits
388
+ });
389
+ } catch (err) {
390
+ logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
391
+ }
392
+ return new JsBloomFilter(optimalBits, optimalK);
393
+ }
394
+ var SKETCH_ROWS = 4;
395
+ var SKETCH_WIDTH = 512;
396
+ var SKETCH_MASK = SKETCH_WIDTH - 1;
397
+ var SKETCH_DECAY_THRESHOLD = 1e5;
398
+ var CountMinSketch = class {
399
+ table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
400
+ inserts = 0;
401
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
402
+ fnv32(key) {
403
+ let h = 2166136261;
404
+ for (let i = 0; i < key.length; i++) {
405
+ h ^= key.charCodeAt(i);
406
+ h = Math.imul(h, 16777619) >>> 0;
407
+ }
408
+ return h;
409
+ }
410
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
411
+ increment(key) {
412
+ const h = this.fnv32(key);
413
+ const h1 = (h ^ h >>> 16) >>> 0;
414
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
415
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
416
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
417
+ const t = this.table;
418
+ const i0 = h1 & SKETCH_MASK;
419
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
420
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
421
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
422
+ if (t[i0] < 65535) t[i0]++;
423
+ if (t[i1] < 65535) t[i1]++;
424
+ if (t[i2] < 65535) t[i2]++;
425
+ if (t[i3] < 65535) t[i3]++;
426
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
427
+ }
428
+ /** Minimum-across-rows frequency estimate. */
429
+ estimate(key) {
430
+ const h = this.fnv32(key);
431
+ const h1 = (h ^ h >>> 16) >>> 0;
432
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
433
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
434
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
435
+ const t = this.table;
436
+ return Math.min(
437
+ t[h1 & SKETCH_MASK],
438
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
439
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
440
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
441
+ );
442
+ }
443
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
444
+ decay() {
445
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
446
+ this.inserts = 0;
447
+ }
448
+ };
449
+ function globMatchParts(parts, first, last, key) {
450
+ if (first.length > 0 && !key.startsWith(first)) return false;
451
+ if (last.length > 0 && !key.endsWith(last)) return false;
452
+ if (first.length + last.length > key.length) return false;
453
+ let pos = first.length;
454
+ const end = key.length - last.length;
455
+ for (let i = 1; i < parts.length - 1; i++) {
456
+ const seg = parts[i];
457
+ if (seg.length === 0) continue;
458
+ const idx = key.indexOf(seg, pos);
459
+ if (idx === -1 || idx + seg.length > end) return false;
460
+ pos = idx + seg.length;
461
+ }
462
+ return true;
463
+ }
464
+ var SmartMemoryCache = class {
465
+ cache = /* @__PURE__ */ new Map();
466
+ opts;
467
+ bloom;
468
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
469
+ categoryPrefixes;
470
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
471
+ sketch = new CountMinSketch();
472
+ totalSize = 0;
473
+ categoryCount = /* @__PURE__ */ new Map();
474
+ categorySize = /* @__PURE__ */ new Map();
475
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
476
+ categoryKeys = /* @__PURE__ */ new Map();
477
+ // ── Observability counters ──────────────────────────────────────────────────────
478
+ bloomChecks = 0;
479
+ bloomFalsePos = 0;
480
+ compressions = 0;
481
+ categoryHits = /* @__PURE__ */ new Map();
482
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
483
+ _bloomDirtyCount = 0;
484
+ /**
485
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
486
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
487
+ * that is overwritten in-place rather than replaced with a new object literal.
488
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
489
+ * any other code can observe the pool state.
490
+ */
491
+ _evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
492
+ _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
493
+ constructor(opts, existing) {
494
+ this.opts = opts;
495
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
496
+ this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
497
+ if (existing) {
498
+ for (const [k, v] of existing) this.cache.set(k, v);
499
+ this.recalculateStats();
500
+ for (const key of this.cache.keys()) this.bloom.add(key);
501
+ }
502
+ }
503
+ // ── Internal helpers ──────────────────────────────────────────────────────
504
+ recalculateStats() {
505
+ this.totalSize = 0;
506
+ this.categoryCount.clear();
507
+ this.categorySize.clear();
508
+ this.categoryKeys.clear();
509
+ for (const [key, entry] of this.cache) {
510
+ this.totalSize += entry.size;
511
+ const cat = this.getCategory(key);
512
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
513
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
514
+ let ks = this.categoryKeys.get(cat);
515
+ if (!ks) {
516
+ ks = /* @__PURE__ */ new Set();
517
+ this.categoryKeys.set(cat, ks);
518
+ }
519
+ ks.add(key);
520
+ }
521
+ }
522
+ getCategory(key) {
523
+ for (const prefix of this.categoryPrefixes) {
524
+ if (key.startsWith(prefix)) return prefix;
525
+ }
526
+ return "default";
527
+ }
528
+ getCategoryLimit(cat) {
529
+ return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
530
+ }
531
+ _delete(key, reason = "manual") {
532
+ const entry = this.cache.get(key);
533
+ if (!entry) return false;
534
+ const cat = this.getCategory(key);
535
+ this.totalSize -= entry.size;
536
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
537
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
538
+ this.categoryKeys.get(cat)?.delete(key);
539
+ this._bloomDirtyCount++;
540
+ const deleted = this.cache.delete(key);
541
+ if (deleted && this.opts.onEviction) {
542
+ try {
543
+ this.opts.onEviction(key, reason);
544
+ } catch {
545
+ }
546
+ }
547
+ return deleted;
548
+ }
549
+ ensureCapacity(category, neededSize) {
550
+ const lim = this.getCategoryLimit(category);
551
+ const catCnt = this.categoryCount.get(category) ?? 0;
552
+ const catSz = this.categorySize.get(category) ?? 0;
553
+ let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
554
+ let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
555
+ if (!catOvf && !glbOvf) {
556
+ const wm = this.opts.evictionWatermark ?? 0.9;
557
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
558
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
559
+ if (entryWatermark || byteWatermark) {
560
+ this.smartEvict(category, false);
561
+ }
562
+ return;
563
+ }
564
+ const MAX_EVICT_PASSES = 64;
565
+ let passes = 0;
566
+ do {
567
+ this.smartEvict(category, catOvf);
568
+ const lim2 = this.getCategoryLimit(category);
569
+ const catCnt2 = this.categoryCount.get(category) ?? 0;
570
+ const catSz2 = this.categorySize.get(category) ?? 0;
571
+ catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
572
+ glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
573
+ passes++;
574
+ } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
575
+ }
576
+ score(entry, catBonus, now, key) {
577
+ const age = now - entry.lastAccess;
578
+ const ttl = Math.max(0, entry.expiresAt - now);
579
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
580
+ return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
581
+ }
582
+ /**
583
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
584
+ * saturated the filter past its ~1 % FP capacity.
585
+ *
586
+ * Trigger: (insertions − live entries) > maxCapacity
587
+ *
588
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
589
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
590
+ * cache holds more entries than the filter's rated capacity — which would
591
+ * stall the write path entirely.
592
+ *
593
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
594
+ */
595
+ maybeRebuildBloom() {
596
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
597
+ if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
598
+ this.bloom.rebuild(this.cache.keys());
599
+ this._bloomDirtyCount = 0;
600
+ }
601
+ }
602
+ smartEvict(targetCat, catOvf) {
603
+ const now = Date.now();
604
+ const pool = this._evictPool;
605
+ const gPool = this._evictGPool;
606
+ let poolLen = 0;
607
+ if (catOvf) {
608
+ const catKeySet = this.categoryKeys.get(targetCat);
609
+ if (catKeySet) {
610
+ let catSeen = 0;
611
+ for (const key of catKeySet) {
612
+ const entry = this.cache.get(key);
613
+ if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
614
+ catSeen++;
615
+ const s = this.score(entry, 100, now, key);
616
+ if (poolLen < EVICT_COUNT) {
617
+ pool[poolLen].key = key;
618
+ pool[poolLen].score = s;
619
+ poolLen++;
620
+ } else {
621
+ const j = Math.floor(Math.random() * catSeen);
622
+ if (j < EVICT_COUNT) {
623
+ pool[j].key = key;
624
+ pool[j].score = s;
625
+ }
626
+ }
627
+ }
628
+ }
629
+ }
630
+ if (poolLen < EVICT_COUNT) {
631
+ const remaining = EVICTION_SAMPLE - poolLen;
632
+ let globalSeen = 0;
633
+ let gLen = 0;
634
+ for (const [key, entry] of this.cache) {
635
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
636
+ if (catOvf && this.getCategory(key) === targetCat) continue;
637
+ globalSeen++;
638
+ const s = this.score(entry, 0, now, key);
639
+ if (gLen < remaining) {
640
+ gPool[gLen].key = key;
641
+ gPool[gLen].score = s;
642
+ gLen++;
643
+ } else {
644
+ const j = Math.floor(Math.random() * globalSeen);
645
+ if (j < remaining) {
646
+ gPool[j].key = key;
647
+ gPool[j].score = s;
648
+ }
649
+ }
650
+ }
651
+ for (let i = 0; i < gLen; i++) {
652
+ pool[poolLen].key = gPool[i].key;
653
+ pool[poolLen].score = gPool[i].score;
654
+ poolLen++;
655
+ }
656
+ }
657
+ if (poolLen === 0) return;
658
+ for (let i = 1; i < poolLen; i++) {
659
+ const sk = pool[i].key, ss = pool[i].score;
660
+ let j = i - 1;
661
+ while (j >= 0 && pool[j].score > ss) {
662
+ pool[j + 1].key = pool[j].key;
663
+ pool[j + 1].score = pool[j].score;
664
+ j--;
665
+ }
666
+ pool[j + 1].key = sk;
667
+ pool[j + 1].score = ss;
668
+ }
669
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
670
+ for (let i = 0; i < toEvict; i++) {
671
+ const key = pool[i].key;
672
+ const entry = this.cache.get(key);
673
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
674
+ this._delete(key, "capacity");
675
+ }
676
+ }
677
+ // ── Public API ────────────────────────────────────────────────────────────
678
+ get(key) {
679
+ this.bloomChecks++;
680
+ if (!this.bloom.mightContain(key)) return null;
681
+ const entry = this.cache.get(key);
682
+ if (!entry) {
683
+ this.bloomFalsePos++;
684
+ return null;
685
+ }
686
+ const now = Date.now();
687
+ if (entry.expiresAt < now) {
688
+ this._delete(key, "ttl");
689
+ return null;
690
+ }
691
+ entry.hits++;
692
+ entry.lastAccess = now;
693
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
694
+ const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
695
+ _hit.value = value;
696
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
697
+ _hit.expiresAt = entry.expiresAt;
698
+ _hit.ttlMs = entry.ttlMs;
699
+ _hit.delta = entry.delta;
700
+ _hit.fetchedAt = now;
701
+ _hit.tagVersions = entry.tagVersions;
702
+ _hit.setAt = entry.setAt;
703
+ return _hit;
704
+ }
705
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
706
+ const packed = pack(data);
707
+ const size = packed.byteLength;
708
+ this.compressions++;
709
+ this.sketch.increment(key);
710
+ const cat = this.getCategory(key);
711
+ const lim = this.getCategoryLimit(cat);
712
+ if (size > lim.maxSizeBytes * 0.5) {
713
+ this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
714
+ return;
715
+ }
716
+ const existingEntry = this.cache.get(key);
717
+ if (existingEntry) {
718
+ this.totalSize -= existingEntry.size;
719
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
720
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
721
+ this.cache.delete(key);
722
+ }
723
+ this.ensureCapacity(cat, size);
724
+ const now = Date.now();
725
+ const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
726
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
727
+ if (!existingEntry) this.bloom.add(key);
728
+ this.maybeRebuildBloom();
729
+ this.totalSize += size;
730
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
731
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
732
+ let ks = this.categoryKeys.get(cat);
733
+ if (!ks) {
734
+ ks = /* @__PURE__ */ new Set();
735
+ this.categoryKeys.set(cat, ks);
736
+ }
737
+ ks.add(key);
738
+ }
739
+ delete(key) {
740
+ const deleted = this._delete(key, "manual");
741
+ if (deleted) this.maybeRebuildBloom();
742
+ return deleted;
743
+ }
744
+ keysMatchingPattern(pattern) {
745
+ if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
746
+ if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
747
+ const prefix = pattern.slice(0, -1);
748
+ const catKeys = this.categoryKeys.get(prefix);
749
+ if (catKeys !== void 0) return Array.from(catKeys);
750
+ }
751
+ const firstStar = pattern.indexOf("*");
752
+ if (firstStar === pattern.lastIndexOf("*")) {
753
+ const prefix = pattern.slice(0, firstStar);
754
+ const suffix = pattern.slice(firstStar + 1);
755
+ const minLen = prefix.length + suffix.length;
756
+ const out2 = [];
757
+ for (const k of this.cache.keys()) {
758
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
759
+ }
760
+ return out2;
761
+ }
762
+ const parts = pattern.split("*");
763
+ const first = parts[0];
764
+ const last = parts[parts.length - 1];
765
+ const out = [];
766
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
767
+ return out;
768
+ }
769
+ deletePattern(pattern) {
770
+ let n = 0;
771
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
772
+ if (n > 0) this.maybeRebuildBloom();
773
+ return n;
774
+ }
775
+ /** Flush all entries, or only those whose key starts with `prefix`. */
776
+ clear(prefix) {
777
+ if (prefix) {
778
+ const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
779
+ return this.deletePattern(pattern);
780
+ }
781
+ const count = this.cache.size;
782
+ this.cache.clear();
783
+ this.totalSize = 0;
784
+ this.categoryCount.clear();
785
+ this.categorySize.clear();
786
+ this.categoryKeys.clear();
787
+ this.categoryHits.clear();
788
+ this.bloom.reset();
789
+ this._bloomDirtyCount = 0;
790
+ return count;
791
+ }
792
+ /**
793
+ * Evict entries that violate current category or global limits.
794
+ * Returns the number of entries evicted.
795
+ */
796
+ rebalance() {
797
+ const now = Date.now();
798
+ let evicted = 0;
799
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
800
+ const catKeys = this.categoryKeys.get(cat);
801
+ if (!catKeys || catKeys.size === 0) continue;
802
+ let catCnt = this.categoryCount.get(cat) ?? 0;
803
+ let catSz = this.categorySize.get(cat) ?? 0;
804
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
805
+ const candidates = [];
806
+ for (const key of catKeys) {
807
+ const entry = this.cache.get(key);
808
+ if (!entry) continue;
809
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
810
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
811
+ }
812
+ candidates.sort((a, b) => a.score - b.score);
813
+ for (const { key } of candidates) {
814
+ catCnt = this.categoryCount.get(cat) ?? 0;
815
+ catSz = this.categorySize.get(cat) ?? 0;
816
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
817
+ const entry = this.cache.get(key);
818
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
819
+ this._delete(key, "rebalance");
820
+ evicted++;
821
+ }
822
+ }
823
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
824
+ const before = this.cache.size;
825
+ this.smartEvict("default", false);
826
+ if (this.cache.size >= before) break;
827
+ evicted += before - this.cache.size;
828
+ }
829
+ if (evicted > 0) this.maybeRebuildBloom();
830
+ return evicted;
831
+ }
832
+ /**
833
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
834
+ * Only reflects L1 state — does not query Redis or disk.
835
+ */
836
+ ttl(key) {
837
+ const entry = this.cache.get(key);
838
+ if (!entry) return null;
839
+ const remaining = entry.expiresAt - Date.now();
840
+ return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
841
+ }
842
+ /**
843
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
844
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
845
+ * exceeds the configured threshold.
846
+ *
847
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
848
+ * @returns Number of entries evicted
849
+ */
850
+ evictPercentage(pct) {
851
+ if (pct <= 0 || this.cache.size === 0) return 0;
852
+ const now = Date.now();
853
+ const candidates = [];
854
+ for (const [key, entry] of this.cache) {
855
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
856
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
857
+ }
858
+ candidates.sort((a, b) => a.score - b.score);
859
+ const count = Math.max(1, Math.ceil(candidates.length * pct));
860
+ let evicted = 0;
861
+ for (const { key } of candidates.slice(0, count)) {
862
+ const entry = this.cache.get(key);
863
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
864
+ this._delete(key, "oom");
865
+ evicted++;
866
+ }
867
+ return evicted;
868
+ }
869
+ cleanup() {
870
+ const now = Date.now();
871
+ let cleaned = 0;
872
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
873
+ this._delete(key, "ttl");
874
+ cleaned++;
875
+ }
876
+ if (cleaned > 0) {
877
+ this.bloom.rebuild(this.cache.keys());
878
+ this._bloomDirtyCount = 0;
879
+ }
880
+ return cleaned;
881
+ }
882
+ /**
883
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
884
+ *
885
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
886
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
887
+ * Entries written before the disconnect started may have been invalidated by
888
+ * peers while the backplane was down; evicting them forces a controlled
889
+ * cold-start re-fetch from L2 rather than serving silently stale data.
890
+ *
891
+ * Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
892
+ * Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
893
+ * entries with neither field are treated as potentially stale and evicted conservatively.
894
+ *
895
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
896
+ * this time are evicted.
897
+ * @returns Number of entries evicted.
898
+ */
899
+ evictSetBefore(cutoffMs) {
900
+ let evicted = 0;
901
+ for (const [key, entry] of this.cache) {
902
+ if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
903
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
904
+ if (setAt < cutoffMs) {
905
+ this._delete(key, "manual");
906
+ evicted++;
907
+ }
908
+ }
909
+ if (evicted > 0) {
910
+ this.bloom.rebuild(this.cache.keys());
911
+ this._bloomDirtyCount = 0;
912
+ }
913
+ return evicted;
914
+ }
915
+ /**
916
+ * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
917
+ * Used for concurrency-safe compare-and-delete on stale generational reads,
918
+ * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
919
+ */
920
+ deleteIfSetBefore(key, cutoffMs) {
921
+ const entry = this.cache.get(key);
922
+ if (!entry) return false;
923
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
924
+ if (setAt <= cutoffMs) {
925
+ const deleted = this._delete(key, "manual");
926
+ if (deleted) this.maybeRebuildBloom();
927
+ return deleted;
928
+ }
929
+ return false;
930
+ }
931
+ exportEntries(forbiddenPrefixes) {
932
+ const now = Date.now();
933
+ const out = [];
934
+ for (const [key, entry] of this.cache) {
935
+ if (entry.expiresAt <= now) continue;
936
+ if (entry.priority === 4) continue;
937
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
938
+ out.push({ key, entry: { ...entry } });
939
+ }
940
+ return out;
941
+ }
942
+ importEntries(entries, forbiddenPrefixes) {
943
+ const now = Date.now();
944
+ let loaded = 0;
945
+ for (const { key, entry } of entries) {
946
+ if (entry.expiresAt <= now) continue;
947
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
948
+ if (this.cache.has(key)) continue;
949
+ const rawData = entry.data;
950
+ const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
951
+ const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : void 0;
952
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
953
+ this.bloom.add(key);
954
+ loaded++;
955
+ }
956
+ this.recalculateStats();
957
+ return loaded;
958
+ }
959
+ // ── Iterators ─────────────────────────────────────────────────────────────
960
+ /**
961
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
962
+ * Expired entries that are still in the Map (awaiting background cleanup)
963
+ * are silently skipped.
964
+ */
965
+ *liveEntries() {
966
+ const now = Date.now();
967
+ for (const [key, entry] of this.cache) {
968
+ if (entry.expiresAt > now) yield [key, entry];
969
+ }
970
+ }
971
+ /**
972
+ * Non-generator bulk scan over all live entries.
973
+ *
974
+ * Faster than the generator-based iterators for bulk operations because:
975
+ * - No generator state-machine overhead (no yield/resume suspend points).
976
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
977
+ * - The same Map call-site is used by a single plain `for` loop instead of being
978
+ * shared across three competing generator functions, giving V8's IC a cleaner
979
+ * monomorphic profile for this path.
980
+ *
981
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
982
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
983
+ * key, avoiding the allocation entirely for callers that don't.
984
+ *
985
+ * @param fn Called once per live entry.
986
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
987
+ * Pass 0 when no namespace is configured.
988
+ */
989
+ scan(fn, prefixLen) {
990
+ const now = Date.now();
991
+ for (const [key, entry] of this.cache) {
992
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
993
+ }
994
+ }
995
+ /**
996
+ * Yields only the keys of live entries — no intermediate tuple allocation.
997
+ * Use this instead of liveEntries() when you only need keys.
998
+ */
999
+ *liveKeys() {
1000
+ const now = Date.now();
1001
+ for (const [key, entry] of this.cache) {
1002
+ if (entry.expiresAt > now) yield key;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Yields only the resolved values of live entries.
1007
+ * Iterates Map.values() so the key is never loaded into the yielded path.
1008
+ * Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
1009
+ */
1010
+ *liveValues() {
1011
+ const now = Date.now();
1012
+ for (const entry of this.cache.values()) {
1013
+ if (entry.expiresAt > now)
1014
+ yield this.resolveValue(entry);
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Returns the deserialized value for an entry, unpacking from the msgpackr buffer
1019
+ * if the live object was not cached (large-entry optimisation or disk-restored entry).
1020
+ */
1021
+ resolveValue(entry) {
1022
+ return entry.value !== void 0 ? entry.value : unpack(entry.data);
1023
+ }
1024
+ // ── Stats ─────────────────────────────────────────────────────────────────
1025
+ get size() {
1026
+ return this.cache.size;
1027
+ }
1028
+ get memoryUsage() {
1029
+ return this.totalSize;
1030
+ }
1031
+ getStats() {
1032
+ const categories = {};
1033
+ for (const [cat, cnt] of this.categoryCount) {
1034
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
1035
+ }
1036
+ return {
1037
+ entries: this.cache.size,
1038
+ sizeBytes: this.totalSize,
1039
+ sizeKB: Math.round(this.totalSize / 1024),
1040
+ categories,
1041
+ bloom: {
1042
+ checks: this.bloomChecks,
1043
+ falsePositives: this.bloomFalsePos
1044
+ },
1045
+ compression: {
1046
+ compressed: this.compressions,
1047
+ uncompressed: 0,
1048
+ // all entries are now msgpackr-packed
1049
+ bytesSaved: 0
1050
+ // no longer tracked (unified format removes the split path)
1051
+ }
1052
+ };
1053
+ }
1054
+ /**
1055
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
1056
+ * Does NOT count as a hit or perform SWR logic.
1057
+ */
1058
+ getEntry(key) {
1059
+ const entry = this.cache.get(key);
1060
+ if (!entry) return void 0;
1061
+ if (entry.expiresAt <= Date.now()) return void 0;
1062
+ return entry;
1063
+ }
1064
+ /**
1065
+ * Return true if the key exists in L1 and has not expired.
1066
+ * Uses the bloom filter as a fast negative check.
1067
+ */
1068
+ has(key) {
1069
+ if (!this.bloom.mightContain(key)) return false;
1070
+ const entry = this.cache.get(key);
1071
+ if (!entry) return false;
1072
+ if (entry.expiresAt <= Date.now()) {
1073
+ this._delete(key, "ttl");
1074
+ return false;
1075
+ }
1076
+ return true;
1077
+ }
1078
+ /**
1079
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
1080
+ * @param newTtlMs - New TTL from now, in milliseconds.
1081
+ */
1082
+ touch(key, newTtlMs) {
1083
+ const entry = this.cache.get(key);
1084
+ if (!entry) return false;
1085
+ const now = Date.now();
1086
+ if (entry.expiresAt <= now) {
1087
+ this._delete(key, "ttl");
1088
+ return false;
1089
+ }
1090
+ entry.expiresAt = now + newTtlMs;
1091
+ return true;
1092
+ }
1093
+ /**
1094
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
1095
+ * Returns `false` if the key is absent or already expired.
1096
+ */
1097
+ bumpExpiry(key, additionalMs) {
1098
+ const entry = this.cache.get(key);
1099
+ if (!entry) return false;
1100
+ if (entry.expiresAt <= Date.now()) return false;
1101
+ entry.expiresAt += additionalMs;
1102
+ return true;
1103
+ }
1104
+ bloomMightContain(key) {
1105
+ return this.bloom.mightContain(key);
1106
+ }
1107
+ bloomStats() {
1108
+ return this.bloom.stats;
1109
+ }
1110
+ /**
1111
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1112
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1113
+ * Useful for diagnosing which keys are driving cache pressure.
1114
+ *
1115
+ * @param n - Maximum number of entries to return. Default: 10.
1116
+ */
1117
+ hotKeys(n) {
1118
+ const now = Date.now();
1119
+ const out = [];
1120
+ for (const [key, entry] of this.cache) {
1121
+ if (entry.expiresAt <= now) continue;
1122
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1123
+ }
1124
+ out.sort((a, b) => b.hits - a.hits);
1125
+ return out.slice(0, n);
1126
+ }
1127
+ };
1128
+
1129
+ // src/disk-tier.ts
1130
+ import fs from "fs";
1131
+ import path from "path";
1132
+ import crypto from "crypto";
1133
+ import { pack as pack2, unpack as unpack2 } from "msgpackr";
1134
+ var _SqliteDB = null;
1135
+ try {
1136
+ const sqlite = process.getBuiltinModule("node:sqlite");
1137
+ _SqliteDB = sqlite?.DatabaseSync ?? null;
1138
+ } catch {
1139
+ }
1140
+ var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1141
+ var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1142
+ var V2_HEADER_LEN = 16;
1143
+ var DISK_TIER_VERSION = 1;
1144
+ var DiskTier = class {
1145
+ opts;
1146
+ dirReady = false;
1147
+ diskUsageBytes = 0;
1148
+ usageCounted = false;
1149
+ fileCount = 0;
1150
+ // maintained in-memory; avoids walkCacheFiles() in stats
1151
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1152
+ _nextJanitorBucket = 0;
1153
+ // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1154
+ _db = null;
1155
+ _stmtInsert = null;
1156
+ // INSERT OR REPLACE
1157
+ _stmtSelect = null;
1158
+ // SELECT by key_hash
1159
+ _stmtDelete = null;
1160
+ // DELETE by key_hash
1161
+ _stmtExpire = null;
1162
+ // SELECT expired rows
1163
+ _stmtDelExp = null;
1164
+ // DELETE expired rows
1165
+ _stmtStats = null;
1166
+ // COUNT + SUM(size)
1167
+ constructor(opts) {
1168
+ this.opts = opts;
1169
+ }
1170
+ // ── Helpers ───────────────────────────────────────────────────────────────
1171
+ ensureDir() {
1172
+ if (this.dirReady) return;
1173
+ try {
1174
+ fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
1175
+ this.dirReady = true;
1176
+ this._initSqlite();
1177
+ } catch (err) {
1178
+ this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Initialise the SQLite metadata index. Called once after the cache directory
1183
+ * is confirmed to exist. On any failure the instance silently falls back to
1184
+ * file-only mode — all public methods handle `this._db === null`.
1185
+ *
1186
+ * Schema:
1187
+ * meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
1188
+ * idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
1189
+ *
1190
+ * WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
1191
+ * most one WAL frame — acceptable data loss for an L1.5 spill store).
1192
+ */
1193
+ _initSqlite() {
1194
+ if (!_SqliteDB) return;
1195
+ try {
1196
+ const dbPath = path.join(this.opts.dir, "meta.db");
1197
+ this._db = new _SqliteDB(dbPath);
1198
+ this._db.exec(`
1199
+ PRAGMA journal_mode = WAL;
1200
+ PRAGMA synchronous = NORMAL;
1201
+ PRAGMA temp_store = MEMORY;
1202
+ CREATE TABLE IF NOT EXISTS meta (
1203
+ key_hash TEXT PRIMARY KEY,
1204
+ file_path TEXT NOT NULL,
1205
+ expires_at INTEGER NOT NULL,
1206
+ size INTEGER NOT NULL DEFAULT 0
1207
+ );
1208
+ CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
1209
+ `);
1210
+ this._stmtInsert = this._db.prepare(
1211
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
1212
+ );
1213
+ this._stmtSelect = this._db.prepare(
1214
+ "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
1215
+ );
1216
+ this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
1217
+ this._stmtExpire = this._db.prepare(
1218
+ "SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
1219
+ );
1220
+ this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
1221
+ this._stmtStats = this._db.prepare(
1222
+ "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1223
+ );
1224
+ const row = this._stmtStats.get();
1225
+ this.fileCount = row.cnt;
1226
+ this.diskUsageBytes = row.bytes;
1227
+ this.usageCounted = true;
1228
+ this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1229
+ } catch (err) {
1230
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1231
+ this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1232
+ error: err.message
1233
+ });
1234
+ }
1235
+ }
1236
+ ensureUsageCounted() {
1237
+ if (this.usageCounted) return;
1238
+ this.usageCounted = true;
1239
+ if (this._db) return;
1240
+ try {
1241
+ this.ensureDir();
1242
+ let total = 0;
1243
+ const files = this.walkCacheFiles();
1244
+ this.fileCount = files.length;
1245
+ for (const filePath of files) {
1246
+ try {
1247
+ total += fs.statSync(filePath).size;
1248
+ } catch {
1249
+ }
1250
+ }
1251
+ this.diskUsageBytes = total;
1252
+ } catch {
1253
+ this.diskUsageBytes = 0;
1254
+ this.fileCount = 0;
1255
+ }
1256
+ }
1257
+ /**
1258
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1259
+ * Kept separate from path construction so callers can find files by prefix
1260
+ * without knowing which filename generation was used when the file was written.
1261
+ */
1262
+ keyToHash(key) {
1263
+ return crypto.createHash("sha256").update(key, "utf8").digest("hex");
1264
+ }
1265
+ /**
1266
+ * Build the write path for a NEW file (V3 generation).
1267
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1268
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1269
+ *
1270
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1271
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1272
+ *
1273
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1274
+ */
1275
+ hashToWritePath(hash, expiresAt) {
1276
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
1277
+ }
1278
+ /**
1279
+ * Find the on-disk file for a key hash, handling all filename generations:
1280
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1281
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1282
+ * Returns null when the bucket dir does not exist or the key is absent.
1283
+ */
1284
+ findFilePath(hash) {
1285
+ const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
1286
+ let files;
1287
+ try {
1288
+ files = fs.readdirSync(bucketPath);
1289
+ } catch {
1290
+ return null;
1291
+ }
1292
+ let match;
1293
+ for (const f of files) {
1294
+ if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1295
+ }
1296
+ if (!match) return null;
1297
+ return path.join(bucketPath, match);
1298
+ }
1299
+ /**
1300
+ * Recursively list all cache file paths across the 2-level sharded subdirs.
1301
+ * Top-level entries that are not directories are skipped (e.g. stale flat
1302
+ * files written by older versions).
1303
+ */
1304
+ walkCacheFiles() {
1305
+ const results = [];
1306
+ let topEntries;
1307
+ try {
1308
+ topEntries = fs.readdirSync(this.opts.dir);
1309
+ } catch {
1310
+ return results;
1311
+ }
1312
+ for (const top of topEntries) {
1313
+ const topPath = path.join(this.opts.dir, top);
1314
+ try {
1315
+ if (!fs.statSync(topPath).isDirectory()) continue;
1316
+ for (const file of fs.readdirSync(topPath)) {
1317
+ results.push(path.join(topPath, file));
1318
+ }
1319
+ } catch {
1320
+ }
1321
+ }
1322
+ return results;
1323
+ }
1324
+ isForbidden(key) {
1325
+ return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
1326
+ }
1327
+ encrypt(data) {
1328
+ if (!this.opts.encryption) return data;
1329
+ return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
1330
+ }
1331
+ decrypt(data) {
1332
+ const mLen = DISK_MAGIC.length;
1333
+ if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
1334
+ if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
1335
+ return this.opts.encryption.decryptBuffer(data.subarray(mLen));
1336
+ }
1337
+ /**
1338
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
1339
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
1340
+ * Returns the buffer unchanged when no encryption instance is configured.
1341
+ */
1342
+ encryptV2(data) {
1343
+ if (!this.opts.encryption) return data;
1344
+ return this.opts.encryption.encryptBuffer(data);
1345
+ }
1346
+ /**
1347
+ * V2 decryption — inner payload after stripping the 16-byte header.
1348
+ * When an encryption instance is configured the format is the mode-aware
1349
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
1350
+ * without one the payload is raw msgpack.
1351
+ */
1352
+ decryptV2(inner) {
1353
+ if (!this.opts.encryption) return inner;
1354
+ return this.opts.encryption.decryptBuffer(inner);
1355
+ }
1356
+ // ── Public API ────────────────────────────────────────────────────────────
1357
+ /**
1358
+ * Spill an evicted L1 entry to disk.
1359
+ *
1360
+ * Returns a Promise that resolves when the file is durably written. Callers
1361
+ * that treat the spill as fire-and-forget should do:
1362
+ * `void disk.save(key, entry)`
1363
+ *
1364
+ * Implementation notes:
1365
+ * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
1366
+ * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
1367
+ * on any external resource.
1368
+ * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
1369
+ * so the Node.js event loop is never stalled waiting for disk I/O.
1370
+ */
1371
+ async save(key, entry) {
1372
+ if (this.isForbidden(key)) return;
1373
+ if (entry.expiresAt <= Date.now()) return;
1374
+ this.ensureDir();
1375
+ if (!this.dirReady) return;
1376
+ this.ensureUsageCounted();
1377
+ if (this.diskUsageBytes >= this.opts.maxBytes) return;
1378
+ let final;
1379
+ try {
1380
+ const payload = {
1381
+ version: DISK_TIER_VERSION,
1382
+ key,
1383
+ entry: {
1384
+ ...entry,
1385
+ data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
1386
+ },
1387
+ writtenAt: Date.now()
1388
+ };
1389
+ const packed = pack2(payload);
1390
+ if (packed.length > this.opts.entryMaxBytes) return;
1391
+ let toEncrypt = packed;
1392
+ if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
1393
+ toEncrypt = compressWithHeader(packed, this.opts.compression);
1394
+ }
1395
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1396
+ DISK_MAGIC_V2.copy(header, 0);
1397
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1398
+ final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
1399
+ } catch (err) {
1400
+ this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1401
+ return;
1402
+ }
1403
+ const hash = this.keyToHash(key);
1404
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1405
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1406
+ this.diskUsageBytes += final.length;
1407
+ this.fileCount++;
1408
+ try {
1409
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
1410
+ await fs.promises.writeFile(tmpPath, final, { mode: 384 });
1411
+ try {
1412
+ await fs.promises.rename(tmpPath, filePath);
1413
+ } catch (renameErr) {
1414
+ const code = renameErr?.code;
1415
+ if (code === "EBUSY" || code === "EPERM") {
1416
+ await new Promise((resolve) => setTimeout(resolve, 5));
1417
+ await fs.promises.rename(tmpPath, filePath);
1418
+ } else {
1419
+ throw renameErr;
1420
+ }
1421
+ }
1422
+ if (this._db) {
1423
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1424
+ }
1425
+ this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1426
+ } catch (err) {
1427
+ try {
1428
+ await fs.promises.unlink(tmpPath);
1429
+ } catch {
1430
+ }
1431
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1432
+ this.fileCount = Math.max(0, this.fileCount - 1);
1433
+ if (this._db) try {
1434
+ this._stmtDelete.run(hash);
1435
+ } catch {
1436
+ }
1437
+ this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1438
+ }
1439
+ }
1440
+ /** Load a key from disk, or return null on miss/expiry/corruption. */
1441
+ load(key) {
1442
+ if (this.isForbidden(key)) return null;
1443
+ this.ensureDir();
1444
+ if (!this.dirReady) return null;
1445
+ const hash = this.keyToHash(key);
1446
+ let filePath;
1447
+ if (this._db) {
1448
+ const row = this._stmtSelect.get(hash);
1449
+ if (!row) return null;
1450
+ if (row.expires_at <= Date.now()) {
1451
+ this._stmtDelete.run(hash);
1452
+ try {
1453
+ const sz = fs.statSync(row.file_path).size;
1454
+ fs.unlinkSync(row.file_path);
1455
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1456
+ this.fileCount = Math.max(0, this.fileCount - 1);
1457
+ } catch {
1458
+ }
1459
+ return null;
1460
+ }
1461
+ filePath = row.file_path;
1462
+ } else {
1463
+ filePath = this.findFilePath(hash);
1464
+ if (!filePath) return null;
1465
+ }
1466
+ try {
1467
+ if (!this._db) {
1468
+ const filename = path.basename(filePath);
1469
+ if (filename.length === 77 && filename[64] === "_") {
1470
+ const expiresAt = parseInt(filename.slice(65), 16);
1471
+ if (expiresAt <= Date.now()) {
1472
+ try {
1473
+ const sz = fs.statSync(filePath).size;
1474
+ fs.unlinkSync(filePath);
1475
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1476
+ this.fileCount = Math.max(0, this.fileCount - 1);
1477
+ } catch {
1478
+ }
1479
+ return null;
1480
+ }
1481
+ }
1482
+ }
1483
+ const stat = fs.statSync(filePath);
1484
+ if (stat.size > this.opts.entryMaxBytes) {
1485
+ fs.unlinkSync(filePath);
1486
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1487
+ if (this._db) this._stmtDelete.run(hash);
1488
+ return null;
1489
+ }
1490
+ const raw = fs.readFileSync(filePath);
1491
+ try {
1492
+ fs.unlinkSync(filePath);
1493
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1494
+ this.fileCount = Math.max(0, this.fileCount - 1);
1495
+ } catch {
1496
+ }
1497
+ if (this._db) this._stmtDelete.run(hash);
1498
+ let decrypted;
1499
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1500
+ const expiresAt = Number(raw.readBigUInt64LE(8));
1501
+ if (expiresAt <= Date.now()) return null;
1502
+ try {
1503
+ decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
1504
+ } catch {
1505
+ return null;
1506
+ }
1507
+ } else {
1508
+ try {
1509
+ decrypted = this.decrypt(raw);
1510
+ } catch {
1511
+ return null;
1512
+ }
1513
+ }
1514
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
1515
+ const payload = unpack2(uncompressed);
1516
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1517
+ if (payload.entry.expiresAt <= Date.now()) return null;
1518
+ const entry = payload.entry;
1519
+ if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
1520
+ this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1521
+ return entry;
1522
+ } catch (err) {
1523
+ if (this._db) try {
1524
+ this._stmtDelete.run(hash);
1525
+ } catch {
1526
+ }
1527
+ this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1528
+ return null;
1529
+ }
1530
+ }
1531
+ /** Explicitly delete a key from disk (cache invalidation). */
1532
+ delete(key) {
1533
+ const hash = this.keyToHash(key);
1534
+ let filePath;
1535
+ if (this._db) {
1536
+ const row = this._stmtSelect.get(hash);
1537
+ filePath = row?.file_path ?? null;
1538
+ this._stmtDelete.run(hash);
1539
+ } else {
1540
+ filePath = this.findFilePath(hash);
1541
+ }
1542
+ if (!filePath) return;
1543
+ try {
1544
+ const stat = fs.statSync(filePath);
1545
+ fs.unlinkSync(filePath);
1546
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1547
+ this.fileCount = Math.max(0, this.fileCount - 1);
1548
+ } catch {
1549
+ }
1550
+ }
1551
+ /** Purge all expired entries. Returns number deleted. */
1552
+ purgeExpired() {
1553
+ this.ensureDir();
1554
+ if (!this.dirReady) return 0;
1555
+ if (this._db) {
1556
+ const now2 = Date.now();
1557
+ const expired = this._stmtExpire.all(now2);
1558
+ for (const row of expired) {
1559
+ try {
1560
+ fs.unlinkSync(row.file_path);
1561
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1562
+ this.fileCount = Math.max(0, this.fileCount - 1);
1563
+ } catch {
1564
+ }
1565
+ }
1566
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1567
+ return expired.length;
1568
+ }
1569
+ const now = Date.now();
1570
+ let purged = 0;
1571
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1572
+ for (const filePath of this.walkCacheFiles()) {
1573
+ const filename = path.basename(filePath);
1574
+ if (filename.endsWith(".tmp")) {
1575
+ try {
1576
+ const stat = fs.statSync(filePath);
1577
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
1578
+ fs.unlinkSync(filePath);
1579
+ purged++;
1580
+ }
1581
+ } catch {
1582
+ }
1583
+ continue;
1584
+ }
1585
+ if (filename.length === 77 && filename[64] === "_") {
1586
+ const expiresAt = parseInt(filename.slice(65), 16);
1587
+ if (expiresAt <= now) {
1588
+ try {
1589
+ const sz = fs.statSync(filePath).size;
1590
+ fs.unlinkSync(filePath);
1591
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1592
+ this.fileCount = Math.max(0, this.fileCount - 1);
1593
+ purged++;
1594
+ } catch {
1595
+ }
1596
+ }
1597
+ continue;
1598
+ }
1599
+ let fd = -1;
1600
+ try {
1601
+ fd = fs.openSync(filePath, "r");
1602
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1603
+ fs.closeSync(fd);
1604
+ fd = -1;
1605
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1606
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1607
+ if (expiresAt <= now) {
1608
+ try {
1609
+ const sz = fs.statSync(filePath).size;
1610
+ fs.unlinkSync(filePath);
1611
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1612
+ this.fileCount = Math.max(0, this.fileCount - 1);
1613
+ purged++;
1614
+ } catch {
1615
+ }
1616
+ }
1617
+ continue;
1618
+ }
1619
+ const stat = fs.statSync(filePath);
1620
+ if (stat.size > this.opts.entryMaxBytes) {
1621
+ fs.unlinkSync(filePath);
1622
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1623
+ this.fileCount = Math.max(0, this.fileCount - 1);
1624
+ purged++;
1625
+ continue;
1626
+ }
1627
+ const raw = fs.readFileSync(filePath);
1628
+ let dec;
1629
+ try {
1630
+ dec = this.decrypt(raw);
1631
+ } catch {
1632
+ fs.unlinkSync(filePath);
1633
+ this.fileCount = Math.max(0, this.fileCount - 1);
1634
+ purged++;
1635
+ continue;
1636
+ }
1637
+ const payload = unpack2(dec);
1638
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1639
+ fs.unlinkSync(filePath);
1640
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1641
+ this.fileCount = Math.max(0, this.fileCount - 1);
1642
+ purged++;
1643
+ }
1644
+ } catch {
1645
+ } finally {
1646
+ if (fd >= 0) try {
1647
+ fs.closeSync(fd);
1648
+ } catch {
1649
+ }
1650
+ }
1651
+ }
1652
+ return purged;
1653
+ }
1654
+ /**
1655
+ * Purge expired entries. Two modes depending on availability of SQLite:
1656
+ *
1657
+ * SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
1658
+ * One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
1659
+ * wheel. All expired entries are found and deleted in a single pass — the
1660
+ * 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
1661
+ * incremented so tests that inspect the counter continue to work.
1662
+ *
1663
+ * File-only fallback:
1664
+ * Original staggered bucket wheel — purges exactly one of 256 subdirectory
1665
+ * buckets per call, spreading the O(fileCount) work across 256 ticks.
1666
+ *
1667
+ * Returns the number of entries deleted in this tick.
1668
+ */
1669
+ purgeNextBucket() {
1670
+ this.ensureDir();
1671
+ if (!this.dirReady) return 0;
1672
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1673
+ if (this._db) {
1674
+ const now2 = Date.now();
1675
+ const expired = this._stmtExpire.all(now2);
1676
+ for (const row of expired) {
1677
+ try {
1678
+ fs.unlinkSync(row.file_path);
1679
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1680
+ this.fileCount = Math.max(0, this.fileCount - 1);
1681
+ } catch {
1682
+ }
1683
+ }
1684
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1685
+ const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
1686
+ const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
1687
+ let orphanFiles;
1688
+ try {
1689
+ orphanFiles = fs.readdirSync(orphanBucketP);
1690
+ } catch {
1691
+ return expired.length;
1692
+ }
1693
+ for (const file of orphanFiles) {
1694
+ if (file.endsWith(".tmp")) {
1695
+ const fp = path.join(orphanBucketP, file);
1696
+ try {
1697
+ const stat = fs.statSync(fp);
1698
+ if (now2 - stat.mtimeMs > 5 * 60 * 1e3) {
1699
+ fs.unlinkSync(fp);
1700
+ }
1701
+ } catch {
1702
+ }
1703
+ continue;
1704
+ }
1705
+ if (file.length === 77 && file[64] === "_") {
1706
+ const expiresAt = parseInt(file.slice(65), 16);
1707
+ if (expiresAt <= now2) {
1708
+ const fp = path.join(orphanBucketP, file);
1709
+ try {
1710
+ const sz = fs.statSync(fp).size;
1711
+ fs.unlinkSync(fp);
1712
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1713
+ this.fileCount = Math.max(0, this.fileCount - 1);
1714
+ } catch {
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+ return expired.length;
1720
+ }
1721
+ const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
1722
+ const bucketHex = bucket.toString(16).padStart(2, "0");
1723
+ const bucketPath = path.join(this.opts.dir, bucketHex);
1724
+ let files;
1725
+ try {
1726
+ files = fs.readdirSync(bucketPath);
1727
+ } catch {
1728
+ return 0;
1729
+ }
1730
+ const now = Date.now();
1731
+ let purged = 0;
1732
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1733
+ for (const file of files) {
1734
+ if (file.endsWith(".tmp")) {
1735
+ const fp = path.join(bucketPath, file);
1736
+ try {
1737
+ const stat = fs.statSync(fp);
1738
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
1739
+ fs.unlinkSync(fp);
1740
+ purged++;
1741
+ }
1742
+ } catch {
1743
+ }
1744
+ continue;
1745
+ }
1746
+ if (file.length === 77 && file[64] === "_") {
1747
+ const expiresAt = parseInt(file.slice(65), 16);
1748
+ if (expiresAt <= now) {
1749
+ const filePath2 = path.join(bucketPath, file);
1750
+ try {
1751
+ const sz = fs.statSync(filePath2).size;
1752
+ fs.unlinkSync(filePath2);
1753
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1754
+ this.fileCount = Math.max(0, this.fileCount - 1);
1755
+ purged++;
1756
+ } catch {
1757
+ }
1758
+ }
1759
+ continue;
1760
+ }
1761
+ const filePath = path.join(bucketPath, file);
1762
+ let fd = -1;
1763
+ try {
1764
+ fd = fs.openSync(filePath, "r");
1765
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1766
+ fs.closeSync(fd);
1767
+ fd = -1;
1768
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1769
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1770
+ if (expiresAt <= now) {
1771
+ try {
1772
+ const sz = fs.statSync(filePath).size;
1773
+ fs.unlinkSync(filePath);
1774
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1775
+ this.fileCount = Math.max(0, this.fileCount - 1);
1776
+ purged++;
1777
+ } catch {
1778
+ }
1779
+ }
1780
+ continue;
1781
+ }
1782
+ const stat = fs.statSync(filePath);
1783
+ if (stat.size > this.opts.entryMaxBytes) {
1784
+ fs.unlinkSync(filePath);
1785
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1786
+ this.fileCount = Math.max(0, this.fileCount - 1);
1787
+ purged++;
1788
+ continue;
1789
+ }
1790
+ const raw = fs.readFileSync(filePath);
1791
+ let dec;
1792
+ try {
1793
+ dec = this.decrypt(raw);
1794
+ } catch {
1795
+ fs.unlinkSync(filePath);
1796
+ this.fileCount = Math.max(0, this.fileCount - 1);
1797
+ purged++;
1798
+ continue;
1799
+ }
1800
+ const payload = unpack2(dec);
1801
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1802
+ fs.unlinkSync(filePath);
1803
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1804
+ this.fileCount = Math.max(0, this.fileCount - 1);
1805
+ purged++;
1806
+ }
1807
+ } catch {
1808
+ } finally {
1809
+ if (fd >= 0) try {
1810
+ fs.closeSync(fd);
1811
+ } catch {
1812
+ }
1813
+ }
1814
+ }
1815
+ return purged;
1816
+ }
1817
+ /** Delete every file in the disk cache. Returns the count deleted. */
1818
+ clear() {
1819
+ this.ensureDir();
1820
+ if (!this.dirReady) return 0;
1821
+ let cleared = 0;
1822
+ for (const filePath of this.walkCacheFiles()) {
1823
+ try {
1824
+ const stat = fs.statSync(filePath);
1825
+ fs.unlinkSync(filePath);
1826
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1827
+ this.fileCount = Math.max(0, this.fileCount - 1);
1828
+ cleared++;
1829
+ } catch {
1830
+ }
1831
+ }
1832
+ if (this._db) {
1833
+ this._db.exec("DELETE FROM meta");
1834
+ this.diskUsageBytes = 0;
1835
+ this.fileCount = 0;
1836
+ }
1837
+ return cleared;
1838
+ }
1839
+ get stats() {
1840
+ if (this._db) {
1841
+ const row = this._stmtStats.get();
1842
+ this.fileCount = row.cnt;
1843
+ this.diskUsageBytes = row.bytes;
1844
+ }
1845
+ return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1846
+ }
1847
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1848
+ get indexMode() {
1849
+ return this._db ? "sqlite" : "file-only";
1850
+ }
1851
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1852
+ close() {
1853
+ if (this._db) {
1854
+ try {
1855
+ this._db.close();
1856
+ } catch {
1857
+ }
1858
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1859
+ }
1860
+ }
1861
+ };
1862
+
1863
+ // src/cache-service.ts
1864
+ var LUA_COMPARE_AND_DELETE = `
1865
+ local currentTs = redis.call('HGET', KEYS[1], 't')
1866
+ if currentTs and currentTs == ARGV[1] then
1867
+ return redis.call('DEL', KEYS[1])
1868
+ end
1869
+ return 0
1870
+ `;
1871
+ var SNAPSHOT_VERSION = 1;
1872
+ var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
1873
+ var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
1874
+ var DEFAULT_CATEGORY_LIMITS = {
1875
+ "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1876
+ };
1877
+ var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1878
+ var DEFAULT_COUNTER_TTL_SECONDS = 60;
1879
+ var GLOB_REGEX_CACHE_MAX = 256;
1880
+ var globRegexCache = /* @__PURE__ */ new Map();
1881
+ function getGlobRegex(pattern) {
1882
+ let re = globRegexCache.get(pattern);
1883
+ if (re) {
1884
+ globRegexCache.delete(pattern);
1885
+ globRegexCache.set(pattern, re);
1886
+ return re;
1887
+ }
1888
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
1889
+ re = new RegExp("^" + escaped + "$");
1890
+ if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
1891
+ const oldestKey = globRegexCache.keys().next().value;
1892
+ if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
1893
+ }
1894
+ globRegexCache.set(pattern, re);
1895
+ return re;
1896
+ }
1897
+ var L2CircuitBreaker = class {
1898
+ constructor(threshold, cooldownMs) {
1899
+ this.threshold = threshold;
1900
+ this.cooldownMs = cooldownMs;
1901
+ }
1902
+ threshold;
1903
+ cooldownMs;
1904
+ state = 0 /* CLOSED */;
1905
+ failures = 0;
1906
+ openedAt = 0;
1907
+ /** True while the single permitted HALF_OPEN probe is in flight. */
1908
+ probing = false;
1909
+ /**
1910
+ * Call before each Redis attempt. Returns false when the circuit is open.
1911
+ * In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
1912
+ * arriving while a probe is outstanding are rejected (return false) so a
1913
+ * recovering Redis node is not stampeded.
1914
+ */
1915
+ isAllowed() {
1916
+ if (this.state === 0 /* CLOSED */) return true;
1917
+ if (this.state === 2 /* HALF_OPEN */) {
1918
+ if (this.probing) return false;
1919
+ this.probing = true;
1920
+ return true;
1921
+ }
1922
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
1923
+ this.state = 2 /* HALF_OPEN */;
1924
+ this.probing = true;
1925
+ return true;
1926
+ }
1927
+ return false;
1928
+ }
1929
+ /** Call on Redis success. */
1930
+ onSuccess() {
1931
+ this.failures = 0;
1932
+ this.probing = false;
1933
+ this.state = 0 /* CLOSED */;
1934
+ }
1935
+ /** Call on Redis failure. */
1936
+ onFailure() {
1937
+ this.failures++;
1938
+ this.probing = false;
1939
+ if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1940
+ this.state = 1 /* OPEN */;
1941
+ this.openedAt = Date.now();
1942
+ this.failures = 0;
1943
+ }
1944
+ }
1945
+ get isOpen() {
1946
+ return this.state === 1 /* OPEN */;
1947
+ }
1948
+ get currentState() {
1949
+ return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1950
+ }
1951
+ };
1952
+ function deepFreeze(obj) {
1953
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
1954
+ Object.freeze(obj);
1955
+ for (const v of Object.values(obj)) deepFreeze(v);
1956
+ return obj;
1957
+ }
1958
+ var LatencyTracker = class {
1959
+ samples;
1960
+ maxKeys;
1961
+ bufs = /* @__PURE__ */ new Map();
1962
+ meta = /* @__PURE__ */ new Map();
1963
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
1964
+ scratch;
1965
+ constructor(samples, maxKeys) {
1966
+ this.samples = samples;
1967
+ this.maxKeys = maxKeys;
1968
+ this.scratch = new Float64Array(samples);
1969
+ }
1970
+ record(key, deltaMs) {
1971
+ let buf = this.bufs.get(key);
1972
+ let m = this.meta.get(key);
1973
+ if (buf === void 0) {
1974
+ if (this.bufs.size >= this.maxKeys) {
1975
+ const oldest = this.bufs.keys().next().value;
1976
+ this.bufs.delete(oldest);
1977
+ this.meta.delete(oldest);
1978
+ }
1979
+ buf = new Float64Array(this.samples);
1980
+ m = { head: 0, count: 0, p95: 0, dirty: false };
1981
+ this.bufs.set(key, buf);
1982
+ this.meta.set(key, m);
1983
+ }
1984
+ buf[m.head] = deltaMs;
1985
+ m.head = (m.head + 1) % this.samples;
1986
+ if (m.count < this.samples) m.count++;
1987
+ m.dirty = true;
1988
+ }
1989
+ /**
1990
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
1991
+ * Uses the shared scratch buffer — no heap allocation.
1992
+ */
1993
+ _computeP95(buf, m) {
1994
+ const n = m.count;
1995
+ this.scratch.set(buf.subarray(0, n));
1996
+ const view = this.scratch.subarray(0, n);
1997
+ view.sort();
1998
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
1999
+ m.dirty = false;
2000
+ }
2001
+ /**
2002
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
2003
+ * fewer than 5 samples have been collected (not enough data yet).
2004
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
2005
+ */
2006
+ p95(key) {
2007
+ const buf = this.bufs.get(key);
2008
+ const m = this.meta.get(key);
2009
+ if (!buf || !m || m.count < 5) return null;
2010
+ if (m.dirty) this._computeP95(buf, m);
2011
+ return m.p95;
2012
+ }
2013
+ get trackedKeys() {
2014
+ return this.bufs.size;
2015
+ }
2016
+ /**
2017
+ * Top-20 slowest keys by p95, sorted descending.
2018
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
2019
+ *
2020
+ * Only dirty keys (those with new samples since the last call) pay the sort
2021
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
2022
+ * metrics() calls with no intervening fetches are essentially free.
2023
+ */
2024
+ snapshot(prefixLen, multiplierSec, minMs, maxMs) {
2025
+ const out = [];
2026
+ for (const [key, buf] of this.bufs) {
2027
+ const m = this.meta.get(key);
2028
+ if (m.count < 5) continue;
2029
+ if (m.dirty) this._computeP95(buf, m);
2030
+ const p95 = m.p95;
2031
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
2032
+ out.push({
2033
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
2034
+ p95Ms: Math.round(p95),
2035
+ adaptedTtlSec: Math.round(adaptedMs / 1e3)
2036
+ });
2037
+ }
2038
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
2039
+ }
2040
+ };
2041
+ function inferPriority(cacheKey) {
2042
+ if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
2043
+ if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
2044
+ if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
2045
+ return 2 /* NORMAL */;
2046
+ }
2047
+ var GLOBAL_KEY = "__tricache_instance__";
2048
+ function detectServerlessRuntime() {
2049
+ if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
2050
+ if (process.env["K_SERVICE"]) return "Google Cloud Run";
2051
+ if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
2052
+ if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
2053
+ if (process.env["FLY_APP_NAME"]) return "Fly.io";
2054
+ if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
2055
+ if (process.env["VERCEL"]) return "Vercel";
2056
+ return null;
2057
+ }
2058
+ var CacheService = class _CacheService {
2059
+ logger;
2060
+ enc;
2061
+ l1;
2062
+ disk;
2063
+ /** When true, all disk-tier and snapshot operations are skipped. */
2064
+ _diskDisabled = false;
2065
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
2066
+ _workerPool = null;
2067
+ opts;
2068
+ /** Pre-computed once — opts.namespace never changes after construction. */
2069
+ _namespace;
2070
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
2071
+ _redisDisabled;
2072
+ inflight = /* @__PURE__ */ new Map();
2073
+ revalidating = /* @__PURE__ */ new Set();
2074
+ _l1Counters = /* @__PURE__ */ new Map();
2075
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
2076
+ tagIndex = /* @__PURE__ */ new Map();
2077
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
2078
+ tagVersions = /* @__PURE__ */ new Map();
2079
+ /**
2080
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
2081
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
2082
+ */
2083
+ dependencyIndex = /* @__PURE__ */ new Map();
2084
+ redis = null;
2085
+ redisConnecting = null;
2086
+ cb;
2087
+ /** In-process mutex lock map for single-process environments or Redis outages. */
2088
+ _localLocks = /* @__PURE__ */ new Map();
2089
+ /** Active OpenTelemetry monotonic counters. */
2090
+ _otelMetrics = {};
2091
+ snapshotLoaded = false;
2092
+ _readyPromise = Promise.resolve();
2093
+ cleanupInterval = null;
2094
+ diskJanitorInterval = null;
2095
+ oomInterval = null;
2096
+ metricsInterval = null;
2097
+ _shutdownHandler = null;
2098
+ latencyTracker = null;
2099
+ instanceId;
2100
+ backplaneChannel;
2101
+ backplaneStreamKey;
2102
+ subClient = null;
2103
+ streamClient = null;
2104
+ _lastStreamId = "$";
2105
+ _destroyed = false;
2106
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2107
+ _subDisconnectedAt = null;
2108
+ counters = {
2109
+ gets: 0,
2110
+ l1Hits: 0,
2111
+ diskHits: 0,
2112
+ l2Hits: 0,
2113
+ fetches: 0,
2114
+ stampedes: 0,
2115
+ sets: 0,
2116
+ deletes: 0,
2117
+ swrRevalidations: 0,
2118
+ invSent: 0,
2119
+ invReceived: 0,
2120
+ invSkipped: 0,
2121
+ streamEntriesReceived: 0,
2122
+ streamReplays: 0,
2123
+ streamGaps: 0,
2124
+ oomEvictions: 0,
2125
+ oomLastAt: null,
2126
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
2127
+ counterErrors: 0,
2128
+ /** Times a later `create(ns)` call passed options differing from the live singleton. */
2129
+ singletonDivergences: 0,
2130
+ startedAt: Date.now(),
2131
+ bloomChecks: 0,
2132
+ bloomFalsePositives: 0
2133
+ };
2134
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
2135
+ _incrementFallbackWarned = false;
2136
+ // ── Constructor (use CacheService.create() for the recommended singleton) ──
2137
+ constructor(options = {}) {
2138
+ const logger = options.logger ?? consoleLogger;
2139
+ this.logger = logger;
2140
+ const ns = options.namespace?.trim() ?? "";
2141
+ const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
2142
+ this.enc = new CacheEncryption(
2143
+ encKeyRaw,
2144
+ logger,
2145
+ options.encryptionMode,
2146
+ options.previousEncryptionKey,
2147
+ options.previousEncryptionMode
2148
+ );
2149
+ const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2150
+ const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
2151
+ this.opts = {
2152
+ namespace: ns,
2153
+ logger,
2154
+ l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
2155
+ l1MaxEntries: options.l1MaxEntries ?? 2e3,
2156
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2157
+ forbiddenSnapshotPrefixes: forbiddenPrefixes,
2158
+ // Namespace-isolated defaults: separate dir / snapshot per namespace so
2159
+ // two instances with different namespaces never share cache files.
2160
+ diskCacheDir: options.diskCacheDir ?? path2.join(
2161
+ os2.tmpdir(),
2162
+ ns ? `tricache-disk-${ns}` : "tricache-disk"
2163
+ ),
2164
+ diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
2165
+ diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
2166
+ redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2167
+ redisPort: options.redisPort ?? 6379,
2168
+ redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2169
+ disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2170
+ encryptionKey: encKeyRaw,
2171
+ snapshotPath: options.snapshotPath ?? path2.join(
2172
+ os2.tmpdir(),
2173
+ ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
2174
+ ),
2175
+ snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
2176
+ invalidationBackplane: options.invalidationBackplane ?? true,
2177
+ oomProtection: options.oomProtection ?? true,
2178
+ oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
2179
+ oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
2180
+ oomEvictPercent: options.oomEvictPercent ?? 0.2,
2181
+ onMetrics: options.onMetrics,
2182
+ metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
2183
+ staleIfError: options.staleIfError ?? 0,
2184
+ l2WriteMode: options.l2WriteMode ?? "read-write",
2185
+ instanceName: options.instanceName ?? "",
2186
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
2187
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
2188
+ tracer: options.tracer,
2189
+ meter: options.meter,
2190
+ notFoundTtl: options.notFoundTtl ?? 0,
2191
+ warmKeys: options.warmKeys,
2192
+ onHit: options.onHit,
2193
+ onMiss: options.onMiss,
2194
+ frozen: options.frozen ?? false,
2195
+ adaptiveTtl: options.adaptiveTtl ?? false,
2196
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
2197
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
2198
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
2199
+ workerThreads: options.workerThreads ?? false,
2200
+ workerThresholdBytes: options.workerThresholdBytes ?? 131072,
2201
+ // 128 KB
2202
+ workerPoolSize: options.workerPoolSize ?? 0,
2203
+ // 0 = auto (min(4, cpus))
2204
+ backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
2205
+ disableDisk: options.disableDisk ?? false,
2206
+ redisClusterNodes: options.redisClusterNodes,
2207
+ redisSentinel: options.redisSentinel,
2208
+ redisProtocol: options.redisProtocol,
2209
+ useShardedPubSub: options.useShardedPubSub ?? false,
2210
+ compression: options.compression ?? "none",
2211
+ compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
2212
+ strictSingleton: options.strictSingleton ?? false,
2213
+ failClosed: options.failClosed ?? false,
2214
+ tagStrategy: options.tagStrategy ?? "set",
2215
+ tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
2216
+ cloneStrategy: options.cloneStrategy ?? "none",
2217
+ backplaneMode: options.backplaneMode ?? "pubsub",
2218
+ backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2219
+ backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2220
+ backplaneStreamKey: options.backplaneStreamKey
2221
+ };
2222
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2223
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2224
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
2225
+ if (this.opts.adaptiveTtl) {
2226
+ const samples = options.adaptiveTtlSamples ?? 32;
2227
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
2228
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
2229
+ }
2230
+ let diskDisabled = this.opts.disableDisk;
2231
+ if (options.disableDisk === void 0) {
2232
+ const serverless = detectServerlessRuntime();
2233
+ if (serverless !== null) {
2234
+ diskDisabled = true;
2235
+ logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
2236
+ runtime: serverless,
2237
+ hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
2238
+ });
2239
+ }
2240
+ } else if (diskDisabled) {
2241
+ logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
2242
+ }
2243
+ this._diskDisabled = diskDisabled;
2244
+ this.disk = new DiskTier({
2245
+ dir: this.opts.diskCacheDir,
2246
+ maxBytes: this.opts.diskMaxBytes,
2247
+ entryMaxBytes: this.opts.diskEntryMaxBytes,
2248
+ forbiddenPrefixes,
2249
+ encryption: this.enc.isEnabled ? this.enc : null,
2250
+ compression: this.opts.compression,
2251
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2252
+ logger
2253
+ });
2254
+ this._namespace = ns;
2255
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
2256
+ this.l1 = new SmartMemoryCache({
2257
+ maxBytes: this.opts.l1MaxBytes,
2258
+ maxEntries: this.opts.l1MaxEntries,
2259
+ categories: this.opts.categoryLimits,
2260
+ evictionWatermark: this.opts.l1EvictionWatermark,
2261
+ diskSpill: (key, entry) => {
2262
+ if (this._diskDisabled) return;
2263
+ setImmediate(() => {
2264
+ void this.disk.save(key, entry);
2265
+ });
2266
+ },
2267
+ onEviction: options.onEviction,
2268
+ logger
2269
+ });
2270
+ if (!this.snapshotLoaded) {
2271
+ this.snapshotLoaded = true;
2272
+ if (!this._diskDisabled) this.loadSnapshot();
2273
+ }
2274
+ this._shutdownHandler = () => {
2275
+ if (!this._diskDisabled) this.writeSnapshot();
2276
+ process.exit(0);
2277
+ };
2278
+ process.once("SIGTERM", this._shutdownHandler);
2279
+ process.once("SIGINT", this._shutdownHandler);
2280
+ if (this.opts.workerThreads) {
2281
+ try {
2282
+ const encRef = this.enc.toWorkerInit();
2283
+ this._workerPool = new WorkerPool({
2284
+ keyBase64: encRef.keyBase64,
2285
+ mode: encRef.mode,
2286
+ prevKeyBase64: encRef.prevKeyBase64,
2287
+ prevMode: encRef.prevMode,
2288
+ compression: this.opts.compression,
2289
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2290
+ size: this.opts.workerPoolSize || void 0
2291
+ });
2292
+ if (this._workerPool.isAvailable) {
2293
+ logger.info("tricache: worker-thread encryption pool active", {
2294
+ threshold: `${this.opts.workerThresholdBytes / 1024} KB`
2295
+ });
2296
+ } else {
2297
+ this._workerPool = null;
2298
+ logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
2299
+ }
2300
+ } catch {
2301
+ this._workerPool = null;
2302
+ logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
2303
+ }
2304
+ }
2305
+ this.cleanupInterval = setInterval(() => {
2306
+ const cleaned = this.l1.cleanup();
2307
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
2308
+ }, 5 * 60 * 1e3);
2309
+ if (this.cleanupInterval.unref) this.cleanupInterval.unref();
2310
+ if (!this._diskDisabled) {
2311
+ this.diskJanitorInterval = setInterval(() => {
2312
+ const purged = this.disk.purgeNextBucket();
2313
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
2314
+ }, 3e4);
2315
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
2316
+ }
2317
+ if (this.opts.oomProtection) {
2318
+ this.oomInterval = setInterval(() => {
2319
+ const heap = v8.getHeapStatistics();
2320
+ const used = heap.used_heap_size / heap.heap_size_limit;
2321
+ if (used >= this.opts.oomHeapThreshold) {
2322
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
2323
+ this.counters.oomEvictions++;
2324
+ this.counters.oomLastAt = Date.now();
2325
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
2326
+ heapUsedPct: Math.round(used * 100),
2327
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
2328
+ evicted
2329
+ });
2330
+ }
2331
+ }, this.opts.oomCheckIntervalMs);
2332
+ if (this.oomInterval.unref) this.oomInterval.unref();
2333
+ }
2334
+ if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
2335
+ this.metricsInterval = setInterval(() => {
2336
+ try {
2337
+ this.opts.onMetrics(this.metrics());
2338
+ } catch {
2339
+ }
2340
+ }, this.opts.metricsIntervalMs);
2341
+ if (this.metricsInterval.unref) this.metricsInterval.unref();
2342
+ }
2343
+ this.instanceId = crypto2.randomBytes(8).toString("hex");
2344
+ this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2345
+ this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2346
+ this.initBackplane();
2347
+ if (this.opts.warmKeys) {
2348
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
2349
+ }
2350
+ if (this.opts.meter) {
2351
+ this._initOtelMetrics(this.opts.meter);
2352
+ const otel = this._otelMetrics;
2353
+ const nsAttr = this._namespace ? { namespace: this._namespace } : void 0;
2354
+ const targetCounters = this.counters;
2355
+ this.counters = new Proxy(targetCounters, {
2356
+ set(target, prop, value, receiver) {
2357
+ const oldVal = target[prop];
2358
+ const ok = Reflect.set(target, prop, value, receiver);
2359
+ if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
2360
+ const diff = value - oldVal;
2361
+ if (diff > 0 && otel[prop]) {
2362
+ otel[prop].add(diff, nsAttr);
2363
+ }
2364
+ }
2365
+ return ok;
2366
+ }
2367
+ });
2368
+ }
2369
+ }
2370
+ // ── Singleton factory ─────────────────────────────────────────────────────
2371
+ /**
2372
+ * Get (or create) the process-level singleton CacheService instance.
2373
+ *
2374
+ * Options are only applied on first call — subsequent calls return the
2375
+ * existing instance regardless of options passed. When the new options differ
2376
+ * from what the existing singleton was built with, this is a silent no-op by
2377
+ * default; set `strictSingleton: true` to throw instead, or watch the
2378
+ * `singletonDivergences` metric for detection.
2379
+ *
2380
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
2381
+ * with different namespaces return independent instances.
2382
+ */
2383
+ static create(options) {
2384
+ const g = globalThis;
2385
+ const key = _CacheService.globalKey(options);
2386
+ if (!g[key]) {
2387
+ g[key] = new _CacheService(options);
2388
+ return g[key];
2389
+ }
2390
+ const existing = g[key];
2391
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
2392
+ if (diff.length > 0) {
2393
+ existing.bumpSingletonDivergence();
2394
+ const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
2395
+ if (existing.options.strictSingleton) {
2396
+ throw new Error(`strictSingleton: ${msg}`);
2397
+ }
2398
+ (existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
2399
+ }
2400
+ return existing;
2401
+ }
2402
+ /**
2403
+ * Keys that, if set differently on a later `create()` call, represent a
2404
+ * meaningful configuration divergence worth flagging (security/correctness
2405
+ * relevant — not cosmetic, e.g. log level).
2406
+ */
2407
+ static DIVERGENT_KEYS = [
2408
+ "redisHost",
2409
+ "redisPort",
2410
+ "redisTls",
2411
+ "disableRedis",
2412
+ "redisClusterNodes",
2413
+ "redisSentinel",
2414
+ "encryptionKey",
2415
+ "encryptionMode",
2416
+ "l1MaxBytes",
2417
+ "l1MaxEntries",
2418
+ "namespace",
2419
+ "frozen",
2420
+ "adaptiveTtl",
2421
+ "l2WriteMode",
2422
+ "instanceName",
2423
+ "invalidationBackplane"
2424
+ ];
2425
+ /** Returns the names of options that differ between `a` and the live `b`. */
2426
+ static optionsDiff(a, b) {
2427
+ const out = [];
2428
+ for (const k of _CacheService.DIVERGENT_KEYS) {
2429
+ const av = a[k];
2430
+ const bv = b[k];
2431
+ if (av === void 0) continue;
2432
+ const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
2433
+ if (!same) out.push(String(k));
2434
+ }
2435
+ return out;
2436
+ }
2437
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
2438
+ bumpSingletonDivergence() {
2439
+ this.counters.singletonDivergences++;
2440
+ }
2441
+ /** Read-only view of the options the singleton was constructed with. */
2442
+ get options() {
2443
+ const o = this.opts;
2444
+ return {
2445
+ namespace: o.namespace,
2446
+ logger: o.logger,
2447
+ l1MaxBytes: o.l1MaxBytes,
2448
+ l1MaxEntries: o.l1MaxEntries,
2449
+ redisHost: o.redisHost,
2450
+ redisPort: o.redisPort,
2451
+ redisTls: o.redisTls,
2452
+ disableRedis: this._redisDisabled,
2453
+ redisClusterNodes: o.redisClusterNodes,
2454
+ redisSentinel: o.redisSentinel,
2455
+ encryptionKey: o.encryptionKey,
2456
+ l2WriteMode: o.l2WriteMode,
2457
+ instanceName: o.instanceName,
2458
+ frozen: o.frozen,
2459
+ adaptiveTtl: o.adaptiveTtl,
2460
+ invalidationBackplane: o.invalidationBackplane,
2461
+ strictSingleton: o.strictSingleton
2462
+ };
2463
+ }
2464
+ /**
2465
+ * Async factory — accepts a Promise that resolves to CacheOptions.
2466
+ * Useful when config is fetched from a secret store at startup.
2467
+ *
2468
+ * @example
2469
+ * const cache = await CacheService.createAsync(fetchSecrets());
2470
+ */
2471
+ static async createAsync(options) {
2472
+ const resolved = await options;
2473
+ return _CacheService.create(resolved);
2474
+ }
2475
+ /** Replace the singleton (useful in tests). */
2476
+ static reset(options) {
2477
+ const g = globalThis;
2478
+ const key = _CacheService.globalKey(options);
2479
+ const existing = g[key];
2480
+ if (existing) existing.destroy();
2481
+ g[key] = new _CacheService(options);
2482
+ return g[key];
2483
+ }
2484
+ /** Derive the globalThis key for a given set of options. */
2485
+ static globalKey(options) {
2486
+ const ns = options?.namespace?.trim() ?? "";
2487
+ return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
2488
+ }
2489
+ // ── Redis connection ──────────────────────────────────────────────────────
2490
+ /**
2491
+ * Prepend the configured namespace to a raw cache key.
2492
+ * Returns the key unchanged when namespace is empty.
2493
+ *
2494
+ * This is the only place the namespace prefix is applied — callers always
2495
+ * receive and provide un-prefixed keys in the public API.
2496
+ */
2497
+ nk(key) {
2498
+ return this._namespace ? `${this._namespace}:${key}` : key;
2499
+ }
2500
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
2501
+ unnk(key) {
2502
+ return this._namespace ? key.slice(this._namespace.length + 1) : key;
2503
+ }
2504
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
2505
+ _jitterTtl(ttlMs) {
2506
+ const j = this.opts.ttlJitterFactor;
2507
+ if (j === 0) return ttlMs;
2508
+ const rand = crypto2.randomInt(0, 1e5) / 5e4 - 1;
2509
+ return Math.round(ttlMs * (1 + rand * j));
2510
+ }
2511
+ /** Shared no-op span for the common case where no tracer is configured.
2512
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
2513
+ static _nullSpan = {
2514
+ setAttribute() {
2515
+ return this;
2516
+ },
2517
+ setStatus() {
2518
+ return this;
2519
+ },
2520
+ end() {
2521
+ }
2522
+ };
2523
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
2524
+ _startSpan(name) {
2525
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
2526
+ return _CacheService._nullSpan;
2527
+ }
2528
+ createDedicatedRedisClient() {
2529
+ if (this.opts.redisClusterNodes?.length) {
2530
+ return new RedisCluster(this.opts.redisClusterNodes, {
2531
+ redisOptions: {
2532
+ tls: this.opts.redisTls ? {} : void 0,
2533
+ connectTimeout: 1e4,
2534
+ maxRetriesPerRequest: null,
2535
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2536
+ }
2537
+ });
2538
+ } else if (this.opts.redisSentinel) {
2539
+ return new RedisClient({
2540
+ sentinels: this.opts.redisSentinel.sentinels,
2541
+ name: this.opts.redisSentinel.name,
2542
+ tls: this.opts.redisTls ? {} : void 0,
2543
+ connectTimeout: 1e4,
2544
+ lazyConnect: true,
2545
+ maxRetriesPerRequest: null,
2546
+ enableAutoPipelining: false,
2547
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
2548
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2549
+ });
2550
+ } else {
2551
+ return new RedisClient({
2552
+ host: this.opts.redisHost,
2553
+ port: this.opts.redisPort,
2554
+ tls: this.opts.redisTls ? {} : void 0,
2555
+ connectTimeout: 1e4,
2556
+ lazyConnect: true,
2557
+ maxRetriesPerRequest: null,
2558
+ enableAutoPipelining: false,
2559
+ family: 4,
2560
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
2561
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2562
+ });
2563
+ }
2564
+ }
2565
+ initBackplane() {
2566
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2567
+ if (this.opts.backplaneMode === "stream") {
2568
+ if (this.streamClient) return;
2569
+ void this._startStreamConsumer();
2570
+ return;
2571
+ }
2572
+ if (this.subClient) return;
2573
+ const sub = this.createDedicatedRedisClient();
2574
+ sub.on("error", (e) => {
2575
+ this._checkAndLogResp3Hint(e);
2576
+ this.logger.debug("Backplane subscriber error", { error: e.message });
2577
+ });
2578
+ sub.on("close", () => {
2579
+ if (this._subDisconnectedAt === null) {
2580
+ this._subDisconnectedAt = Date.now();
2581
+ this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
2582
+ }
2583
+ });
2584
+ sub.on("ready", () => {
2585
+ if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
2586
+ const gapMs = Date.now() - this._subDisconnectedAt;
2587
+ if (gapMs > this.opts.backplaneMaxStalenessMs) {
2588
+ const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
2589
+ this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
2590
+ gapMs,
2591
+ evicted,
2592
+ hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
2593
+ });
2594
+ }
2595
+ this._subDisconnectedAt = null;
2596
+ }
2597
+ });
2598
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
2599
+ if (isClusterSharded) {
2600
+ sub.on("smessage", (_channel, message) => {
2601
+ this._handleBackplaneMessage(message);
2602
+ });
2603
+ sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
2604
+ channel: this.backplaneChannel,
2605
+ instanceId: this.instanceId
2606
+ })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
2607
+ error: err.message
2608
+ }));
2609
+ } else {
2610
+ sub.on("message", (_channel, message) => {
2611
+ this._handleBackplaneMessage(message);
2612
+ });
2613
+ sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
2614
+ channel: this.backplaneChannel,
2615
+ instanceId: this.instanceId
2616
+ })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
2617
+ error: err.message
2618
+ }));
2619
+ }
2620
+ this.subClient = sub;
2621
+ }
2622
+ async _startStreamConsumer() {
2623
+ const sub = this.streamClient ?? this.createDedicatedRedisClient();
2624
+ this.streamClient = sub;
2625
+ if (typeof sub.on === "function") {
2626
+ sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
2627
+ sub.on("close", () => {
2628
+ if (this._subDisconnectedAt === null) {
2629
+ this._subDisconnectedAt = Date.now();
2630
+ this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
2631
+ }
2632
+ });
2633
+ sub.on("ready", () => {
2634
+ if (this._subDisconnectedAt !== null) {
2635
+ this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
2636
+ this._subDisconnectedAt = null;
2637
+ }
2638
+ });
2639
+ }
2640
+ const runLoop = async () => {
2641
+ while (!this._destroyed && !this._redisDisabled) {
2642
+ try {
2643
+ const res = await sub.xread(
2644
+ "BLOCK",
2645
+ this.opts.backplaneStreamBlockMs,
2646
+ "STREAMS",
2647
+ this.backplaneStreamKey,
2648
+ this._lastStreamId
2649
+ );
2650
+ if (this._destroyed) break;
2651
+ if (res && res.length > 0) {
2652
+ for (const [, entries] of res) {
2653
+ if (entries.length > 0) {
2654
+ if (this._lastStreamId !== "$") {
2655
+ this.counters.streamReplays++;
2656
+ }
2657
+ for (const [id, fields] of entries) {
2658
+ this._lastStreamId = id;
2659
+ this.counters.streamEntriesReceived++;
2660
+ let op = "";
2661
+ let key = "";
2662
+ let src = "";
2663
+ let tagVersion;
2664
+ for (let i = 0; i < fields.length; i += 2) {
2665
+ const f = fields[i];
2666
+ const v = fields[i + 1];
2667
+ if (f === "op") op = v;
2668
+ else if (f === "key") key = v;
2669
+ else if (f === "src") src = v;
2670
+ else if (f === "tagVersion") tagVersion = parseInt(v, 10);
2671
+ }
2672
+ if (src === this.instanceId) {
2673
+ this.counters.invSkipped++;
2674
+ continue;
2675
+ }
2676
+ this.counters.invReceived++;
2677
+ this._applyInvalidationEvent(op, key, tagVersion);
2678
+ }
2679
+ }
2680
+ }
2681
+ } else {
2682
+ await new Promise((resolve) => setTimeout(resolve, 10));
2683
+ }
2684
+ } catch (err) {
2685
+ if (this._destroyed) break;
2686
+ const msg = err.message ?? "";
2687
+ if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
2688
+ this.counters.streamGaps++;
2689
+ this.l1.clear();
2690
+ this._lastStreamId = "$";
2691
+ }
2692
+ await new Promise((resolve) => setTimeout(resolve, 200));
2693
+ }
2694
+ }
2695
+ };
2696
+ void runLoop();
2697
+ }
2698
+ _applyInvalidationEvent(op, key, tagVersion) {
2699
+ if (op === "del") {
2700
+ this.l1.delete(key);
2701
+ setImmediate(() => {
2702
+ if (!this._diskDisabled) this.disk.delete(key);
2703
+ });
2704
+ this._cascadeDependencies(key);
2705
+ } else if (op === "del-glob") {
2706
+ this.l1.deletePattern(key);
2707
+ } else if (op === "tag_incr") {
2708
+ const tag = key;
2709
+ const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
2710
+ this._setLocalTagVersion(tag, ver, Date.now());
2711
+ }
2712
+ this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
2713
+ }
2714
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
2715
+ _handleBackplaneMessage(message) {
2716
+ try {
2717
+ const msg = JSON.parse(message);
2718
+ if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
2719
+ this.logger.warn("Backplane: rejected invalid pubsub message format", {
2720
+ raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
2721
+ });
2722
+ return;
2723
+ }
2724
+ if (msg.src === this.instanceId) {
2725
+ this.counters.invSkipped++;
2726
+ return;
2727
+ }
2728
+ this.counters.invReceived++;
2729
+ this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === "number" ? msg.tagVersion : void 0);
2730
+ } catch {
2731
+ this.logger.warn("Backplane: malformed message JSON parse failed");
2732
+ }
2733
+ }
2734
+ async publishInvalidation(op, key, tagVersion) {
2735
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2736
+ try {
2737
+ const client = await this.getRedis();
2738
+ if (this.opts.backplaneMode === "stream") {
2739
+ const args = [
2740
+ this.backplaneStreamKey,
2741
+ "MAXLEN",
2742
+ "~",
2743
+ String(this.opts.backplaneStreamMaxLen),
2744
+ "*",
2745
+ "op",
2746
+ op,
2747
+ "key",
2748
+ key,
2749
+ "src",
2750
+ this.instanceId
2751
+ ];
2752
+ if (typeof tagVersion === "number") {
2753
+ args.push("tagVersion", String(tagVersion));
2754
+ }
2755
+ await client.xadd(...args);
2756
+ this.counters.invSent++;
2757
+ return;
2758
+ }
2759
+ const payload = JSON.stringify({ op, key, src: this.instanceId, tagVersion });
2760
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
2761
+ if (isClusterSharded && typeof client.spublish === "function") {
2762
+ await client.spublish(
2763
+ this.backplaneChannel,
2764
+ payload
2765
+ );
2766
+ } else {
2767
+ await client.publish(
2768
+ this.backplaneChannel,
2769
+ payload
2770
+ );
2771
+ }
2772
+ this.counters.invSent++;
2773
+ } catch {
2774
+ }
2775
+ }
2776
+ _setLocalTagVersion(tag, version, now = Date.now()) {
2777
+ const existing = this.tagVersions.get(tag)?.version ?? 0;
2778
+ const finalVersion = Math.max(existing, version);
2779
+ if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
2780
+ const oldestKey = this.tagVersions.keys().next().value;
2781
+ if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
2782
+ }
2783
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
2784
+ }
2785
+ async _getTagVersion(tag) {
2786
+ const now = Date.now();
2787
+ const local = this.tagVersions.get(tag);
2788
+ if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
2789
+ return local.version;
2790
+ }
2791
+ if (!this._redisDisabled) {
2792
+ try {
2793
+ const client = await this.getRedis();
2794
+ const raw = await client.get(this.nk(`tag_ver:${tag}`));
2795
+ const version = raw ? parseInt(raw, 10) : 0;
2796
+ this._setLocalTagVersion(tag, version, now);
2797
+ return version;
2798
+ } catch {
2799
+ }
2800
+ }
2801
+ return local?.version ?? 0;
2802
+ }
2803
+ _deleteIfStale(k, setAtMs) {
2804
+ this.l1.deleteIfSetBefore(k, setAtMs);
2805
+ if (!this._diskDisabled) this.disk.delete(k);
2806
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2807
+ void this.getRedis().then((client) => {
2808
+ return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
2809
+ }).catch(() => {
2810
+ });
2811
+ }
2812
+ }
2813
+ /**
2814
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
2815
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
2816
+ */
2817
+ async _serializeAndEncrypt(serialized) {
2818
+ const isCompressed = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
2819
+ if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
2820
+ return this._workerPool.encrypt(serialized);
2821
+ }
2822
+ if (isCompressed) {
2823
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
2824
+ if (this.enc.isEnabled) {
2825
+ const encrypted = this.enc.encryptBuffer(compressed);
2826
+ return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
2827
+ }
2828
+ return PREFIX_COMPRESSED + compressed.toString("base64");
2829
+ }
2830
+ return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2831
+ }
2832
+ /**
2833
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
2834
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
2835
+ */
2836
+ async _decryptAndDeserialize(raw) {
2837
+ let plain;
2838
+ if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
2839
+ plain = await this._workerPool.decrypt(raw);
2840
+ } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
2841
+ const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
2842
+ const decBuf = this.enc.decryptBuffer(encBuf);
2843
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
2844
+ plain = decompressed.toString("utf8");
2845
+ } else if (raw.startsWith(PREFIX_COMPRESSED)) {
2846
+ const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
2847
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
2848
+ plain = decompressed.toString("utf8");
2849
+ } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
2850
+ plain = this.enc.decrypt(raw);
2851
+ } else {
2852
+ plain = raw;
2853
+ }
2854
+ return JSON.parse(plain);
2855
+ }
2856
+ /**
2857
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
2858
+ * For Cluster, iterates every master node independently (SCAN is node-local).
2859
+ */
2860
+ async _scanKeys(client, pattern) {
2861
+ const keys = [];
2862
+ if (client instanceof RedisCluster) {
2863
+ const masters = client.nodes("master");
2864
+ await Promise.all(masters.map(
2865
+ (node) => new Promise((resolve, reject) => {
2866
+ const stream = node.scanStream({ match: pattern, count: 100 });
2867
+ stream.on("data", (chunk) => keys.push(...chunk));
2868
+ stream.on("end", resolve);
2869
+ stream.on("error", reject);
2870
+ })
2871
+ ));
2872
+ } else {
2873
+ await new Promise((resolve, reject) => {
2874
+ const stream = client.scanStream({ match: pattern, count: 100 });
2875
+ stream.on("data", (chunk) => keys.push(...chunk));
2876
+ stream.on("end", resolve);
2877
+ stream.on("error", reject);
2878
+ });
2879
+ }
2880
+ return keys;
2881
+ }
2882
+ _checkAndLogResp3Hint(err) {
2883
+ const msg = err?.message || "";
2884
+ if (!this.opts.redisProtocol && (msg.includes("unknown command") || msg.includes("HELLO") || msg.includes("protocol error") || msg.includes("ProtocolError") || msg.includes("Connection is closed"))) {
2885
+ this.logger.warn(
2886
+ "Redis connection/protocol error detected. If your Redis endpoint or proxy (e.g. Twemproxy, Envoy, older ElastiCache) does not support RESP3, set redisProtocol: 2 in CacheOptions to force RESP2 compatibility.",
2887
+ { hint: "redisProtocol: 2", originalError: msg }
2888
+ );
2889
+ }
2890
+ }
2891
+ async getRedis() {
2892
+ if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
2893
+ if (this.redis) return this.redis;
2894
+ if (this.redisConnecting) return this.redisConnecting;
2895
+ this.redisConnecting = (async () => {
2896
+ try {
2897
+ let client;
2898
+ if (this.opts.redisClusterNodes?.length) {
2899
+ client = new RedisCluster(this.opts.redisClusterNodes, {
2900
+ redisOptions: {
2901
+ tls: this.opts.redisTls ? {} : void 0,
2902
+ connectTimeout: 1e4,
2903
+ maxRetriesPerRequest: 3,
2904
+ keepAlive: 3e4,
2905
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2906
+ },
2907
+ enableAutoPipelining: true,
2908
+ retryDelayOnClusterDown: 200,
2909
+ retryDelayOnFailover: 1e3
2910
+ });
2911
+ client.on("connect", () => this.logger.info("Redis Cluster connected"));
2912
+ client.on("error", (e) => {
2913
+ this._checkAndLogResp3Hint(e);
2914
+ this.logger.error("Redis Cluster error", {}, e);
2915
+ });
2916
+ client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
2917
+ } else if (this.opts.redisSentinel) {
2918
+ client = new RedisClient({
2919
+ sentinels: this.opts.redisSentinel.sentinels,
2920
+ name: this.opts.redisSentinel.name,
2921
+ tls: this.opts.redisTls ? {} : void 0,
2922
+ connectTimeout: 1e4,
2923
+ lazyConnect: false,
2924
+ maxRetriesPerRequest: 3,
2925
+ enableAutoPipelining: true,
2926
+ keepAlive: 3e4,
2927
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
2928
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2929
+ });
2930
+ client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
2931
+ client.on("error", (e) => {
2932
+ this._checkAndLogResp3Hint(e);
2933
+ this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e);
2934
+ });
2935
+ client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
2936
+ } else {
2937
+ client = new RedisClient({
2938
+ host: this.opts.redisHost,
2939
+ port: this.opts.redisPort,
2940
+ tls: this.opts.redisTls ? {} : void 0,
2941
+ connectTimeout: 1e4,
2942
+ lazyConnect: false,
2943
+ maxRetriesPerRequest: 3,
2944
+ enableAutoPipelining: true,
2945
+ keepAlive: 3e4,
2946
+ family: 4,
2947
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
2948
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2949
+ });
2950
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2951
+ client.on("error", (e) => {
2952
+ this._checkAndLogResp3Hint(e);
2953
+ this.logger.error("Redis error", { host: this.opts.redisHost }, e);
2954
+ });
2955
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2956
+ }
2957
+ await new Promise((resolve, reject) => {
2958
+ client.once("ready", resolve);
2959
+ client.once("error", (e) => {
2960
+ this._checkAndLogResp3Hint(e);
2961
+ reject(e);
2962
+ });
2963
+ setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
2964
+ });
2965
+ this.cb.onSuccess();
2966
+ this.redis = client;
2967
+ this.redisConnecting = null;
2968
+ return client;
2969
+ } catch (err) {
2970
+ this.cb.onFailure();
2971
+ this.redisConnecting = null;
2972
+ this._checkAndLogResp3Hint(err);
2973
+ throw err;
2974
+ }
2975
+ })();
2976
+ return this.redisConnecting;
2977
+ }
2978
+ // ── Snapshot (cold-start persistence) ────────────────────────────────────
2979
+ writeSnapshot(altPath) {
2980
+ try {
2981
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2982
+ if (entries.length === 0) return;
2983
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2984
+ const packed = pack3(payload);
2985
+ const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2986
+ const dest = altPath ?? this.opts.snapshotPath;
2987
+ fs2.mkdirSync(path2.dirname(dest), { recursive: true });
2988
+ fs2.writeFileSync(dest, final, { mode: 384 });
2989
+ this.logger.info("Cache snapshot written", {
2990
+ path: dest,
2991
+ entries: entries.length,
2992
+ sizeKB: Math.round(final.length / 1024),
2993
+ encrypted: this.enc.isEnabled
2994
+ });
2995
+ } catch (err) {
2996
+ this.logger.warn("Cache snapshot write failed", { error: err.message });
2997
+ }
2998
+ }
2999
+ loadSnapshot() {
3000
+ const snapshotPath = this.opts.snapshotPath;
3001
+ try {
3002
+ if (!fs2.existsSync(snapshotPath)) return;
3003
+ const stat = fs2.statSync(snapshotPath);
3004
+ if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
3005
+ this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
3006
+ fs2.unlinkSync(snapshotPath);
3007
+ return;
3008
+ }
3009
+ const raw = fs2.readFileSync(snapshotPath);
3010
+ fs2.unlinkSync(snapshotPath);
3011
+ let buf;
3012
+ try {
3013
+ buf = this.enc.decryptBuffer(raw);
3014
+ } catch (e) {
3015
+ this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
3016
+ return;
3017
+ }
3018
+ const snapshot = unpack3(buf);
3019
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3020
+ this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
3021
+ return;
3022
+ }
3023
+ const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
3024
+ if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
3025
+ this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
3026
+ return;
3027
+ }
3028
+ if (!Array.isArray(snapshot.entries)) {
3029
+ this.logger.warn("Snapshot rejected: entries is not an array");
3030
+ return;
3031
+ }
3032
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
3033
+ this.logger.info("Cache snapshot loaded (L1 is warm)", {
3034
+ loaded,
3035
+ total: snapshot.entries.length,
3036
+ sizeKB: this.l1.getStats().sizeKB
3037
+ });
3038
+ } catch (err) {
3039
+ this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
3040
+ try {
3041
+ fs2.unlinkSync(snapshotPath);
3042
+ } catch {
3043
+ }
3044
+ }
3045
+ }
3046
+ // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
3047
+ /**
3048
+ * Get a value from cache, or fetch and cache it.
3049
+ *
3050
+ * @param cacheKey - Unique key identifying this value
3051
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
3052
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
3053
+ * @param opts.priority - Override the auto-inferred eviction priority
3054
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
3055
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
3056
+ * is triggered proactively while the caller still receives the
3057
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
3058
+ * Requires `fetchFn` to be stable across calls.
3059
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
3060
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
3061
+ * Complementary to refreshAhead — uses recompute cost (delta) to
3062
+ * decide probabilistically rather than at a fixed threshold.
3063
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
3064
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
3065
+ */
3066
+ async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
3067
+ const span = this._startSpan("tricache.get");
3068
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3069
+ const k = this.nk(cacheKey);
3070
+ this.counters.gets++;
3071
+ const optSwr = opts.swr ?? 0;
3072
+ const optPriority = opts.priority;
3073
+ const optRefreshAhead = opts.refreshAhead;
3074
+ const optXfetchBeta = opts.xfetchBeta;
3075
+ const optNotFoundTtl = opts.notFoundTtl;
3076
+ const optTags = opts.tags;
3077
+ const l1Hit = this.l1.get(k);
3078
+ if (l1Hit !== null) {
3079
+ let isGenerationalStale = false;
3080
+ if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3081
+ for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3082
+ const currentVer = await this._getTagVersion(tag);
3083
+ if (currentVer > entryVer) {
3084
+ isGenerationalStale = true;
3085
+ break;
3086
+ }
3087
+ }
3088
+ }
3089
+ if (isGenerationalStale) {
3090
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
3091
+ } else {
3092
+ if (l1Hit.isStale) {
3093
+ const swrGraceMs2 = optSwr * 1e3;
3094
+ if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
3095
+ const priority2 = optPriority ?? inferPriority(cacheKey);
3096
+ this.revalidating.add(k);
3097
+ void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
3098
+ this.counters.swrRevalidations++;
3099
+ this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
3100
+ } else {
3101
+ this.logger.debug("L1 hit");
3102
+ }
3103
+ } else {
3104
+ this.logger.debug("L1 hit");
3105
+ const ra = optRefreshAhead;
3106
+ const xb = optXfetchBeta;
3107
+ if (ra || xb) {
3108
+ const now = l1Hit.fetchedAt ?? Date.now();
3109
+ const remaining = l1Hit.expiresAt - now;
3110
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
3111
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
3112
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
3113
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3114
+ const priority2 = optPriority ?? inferPriority(cacheKey);
3115
+ this.revalidating.add(k);
3116
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
3117
+ this.counters.swrRevalidations++;
3118
+ this.logger.debug(
3119
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
3120
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
3121
+ );
3122
+ }
3123
+ }
3124
+ }
3125
+ this.counters.l1Hits++;
3126
+ this.opts.onHit?.(cacheKey, "l1");
3127
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
3128
+ span.setAttribute("cache.hit", "l1").end();
3129
+ return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3130
+ }
3131
+ }
3132
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3133
+ const swrGraceMs = optSwr * 1e3;
3134
+ const priority = optPriority ?? inferPriority(cacheKey);
3135
+ if (!this._redisDisabled) {
3136
+ try {
3137
+ const client = await this.getRedis();
3138
+ if (this.opts.tagStrategy === "generational") {
3139
+ const hashData = await client.hgetall(k);
3140
+ this.cb.onSuccess();
3141
+ if (hashData && hashData.d) {
3142
+ let isStale = false;
3143
+ let storedTagVersions = {};
3144
+ if (hashData.tv) {
3145
+ try {
3146
+ storedTagVersions = JSON.parse(hashData.tv);
3147
+ } catch {
3148
+ }
3149
+ }
3150
+ for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3151
+ const currentVer = await this._getTagVersion(tag);
3152
+ if (currentVer > entryVer) {
3153
+ isStale = true;
3154
+ break;
3155
+ }
3156
+ }
3157
+ if (isStale) {
3158
+ const setAtMs = parseInt(hashData.t, 10) || 0;
3159
+ this._deleteIfStale(k, setAtMs);
3160
+ } else {
3161
+ const parsed = await this._decryptAndDeserialize(hashData.d);
3162
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3163
+ this.counters.l2Hits++;
3164
+ this.opts.onHit?.(cacheKey, "l2");
3165
+ this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3166
+ span.setAttribute("cache.hit", "l2").end();
3167
+ if (this.opts.frozen) deepFreeze(parsed);
3168
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3169
+ }
3170
+ }
3171
+ } else {
3172
+ const raw = await client.get(k);
3173
+ this.cb.onSuccess();
3174
+ if (raw) {
3175
+ const parsed = await this._decryptAndDeserialize(raw);
3176
+ this.l1.set(k, parsed, ttlMs, priority);
3177
+ this.counters.l2Hits++;
3178
+ this.opts.onHit?.(cacheKey, "l2");
3179
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
3180
+ span.setAttribute("cache.hit", "l2").end();
3181
+ if (this.opts.frozen) deepFreeze(parsed);
3182
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3183
+ }
3184
+ }
3185
+ } catch (err) {
3186
+ this.cb.onFailure();
3187
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3188
+ }
3189
+ }
3190
+ if (!this._diskDisabled) {
3191
+ const diskHit = this.disk.load(k);
3192
+ if (diskHit !== null) {
3193
+ let isDiskStale = false;
3194
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3195
+ for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3196
+ const currentVer = await this._getTagVersion(tag);
3197
+ if (currentVer > entryVer) {
3198
+ isDiskStale = true;
3199
+ break;
3200
+ }
3201
+ }
3202
+ }
3203
+ if (isDiskStale) {
3204
+ this.disk.delete(k);
3205
+ } else {
3206
+ const promoted = this.l1.importEntries(
3207
+ [{ key: k, entry: diskHit }],
3208
+ this.opts.forbiddenSnapshotPrefixes
3209
+ );
3210
+ if (promoted > 0) {
3211
+ const l1Check = this.l1.get(k);
3212
+ if (l1Check !== null) {
3213
+ this.counters.diskHits++;
3214
+ this.opts.onHit?.(cacheKey, "disk");
3215
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3216
+ span.setAttribute("cache.hit", "disk").end();
3217
+ if (this.opts.frozen) deepFreeze(l1Check.value);
3218
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
3219
+ }
3220
+ }
3221
+ }
3222
+ }
3223
+ }
3224
+ span.setAttribute("cache.hit", "miss");
3225
+ this.opts.onMiss?.(cacheKey);
3226
+ const existing = this.inflight.get(k);
3227
+ if (existing) {
3228
+ this.counters.stampedes++;
3229
+ this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
3230
+ span.end();
3231
+ return existing;
3232
+ }
3233
+ const fetchPromise = (async () => {
3234
+ try {
3235
+ this.counters.fetches++;
3236
+ const fetchStart = Date.now();
3237
+ const data = await fetchFn();
3238
+ const delta = Date.now() - fetchStart;
3239
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
3240
+ let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
3241
+ if (this.latencyTracker && data != null) {
3242
+ this.latencyTracker.record(k, delta);
3243
+ const p95 = this.latencyTracker.p95(k);
3244
+ if (p95 !== null) {
3245
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
3246
+ effectiveTtl = Math.max(
3247
+ this.opts.adaptiveTtlMinMs,
3248
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
3249
+ );
3250
+ }
3251
+ }
3252
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
3253
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
3254
+ let activeTagVersions;
3255
+ if (optTags?.length) {
3256
+ if (this.opts.tagStrategy === "generational") {
3257
+ activeTagVersions = {};
3258
+ for (const tag of optTags) {
3259
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3260
+ }
3261
+ } else {
3262
+ await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3263
+ }
3264
+ }
3265
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
3266
+ if (!this._redisDisabled) {
3267
+ try {
3268
+ const client = await this.getRedis();
3269
+ const serialized = JSON.stringify(data);
3270
+ const toStore = await this._serializeAndEncrypt(serialized);
3271
+ const ttlSec = Math.ceil(effectiveTtl / 1e3);
3272
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3273
+ const now = Date.now();
3274
+ const tx = client.multi();
3275
+ tx.hset(k, {
3276
+ d: toStore,
3277
+ t: String(now),
3278
+ tv: JSON.stringify(activeTagVersions)
3279
+ });
3280
+ tx.expire(k, ttlSec);
3281
+ await tx.exec();
3282
+ } else {
3283
+ await client.setex(k, ttlSec, toStore);
3284
+ }
3285
+ this.cb.onSuccess();
3286
+ this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
3287
+ } catch {
3288
+ this.cb.onFailure();
3289
+ this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
3290
+ }
3291
+ } else {
3292
+ this.logger.debug("Cached L1", { cacheKey });
3293
+ }
3294
+ if (this.opts.frozen) deepFreeze(data);
3295
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
3296
+ } finally {
3297
+ this.inflight.delete(k);
3298
+ span.end();
3299
+ }
3300
+ })();
3301
+ this.inflight.set(k, fetchPromise);
3302
+ return fetchPromise;
3303
+ }
3304
+ /**
3305
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
3306
+ *
3307
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
3308
+ * from `cache-manager` and `keyv`.
3309
+ *
3310
+ * @param cacheKey - Unique cache key.
3311
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
3312
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
3313
+ *
3314
+ * @example
3315
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
3316
+ * ttl: 300,
3317
+ * swr: 60,
3318
+ * tags: ['users'],
3319
+ * });
3320
+ */
3321
+ wrap(cacheKey, fetchFn, options) {
3322
+ const ttl = options?.ttl ?? 300;
3323
+ return this.get(cacheKey, fetchFn, ttl, options);
3324
+ }
3325
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
3326
+ try {
3327
+ const fetchStart = Date.now();
3328
+ const data = await fetchFn();
3329
+ const delta = Date.now() - fetchStart;
3330
+ const staleAt = Date.now() + ttlMs;
3331
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
3332
+ let activeTagVersions;
3333
+ const l1Existing = this.l1.get(cacheKey);
3334
+ if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
3335
+ activeTagVersions = {};
3336
+ for (const tag of Object.keys(l1Existing.tagVersions)) {
3337
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3338
+ }
3339
+ }
3340
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
3341
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3342
+ try {
3343
+ const client = await this.getRedis();
3344
+ const s = JSON.stringify(data);
3345
+ const stored = await this._serializeAndEncrypt(s);
3346
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3347
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3348
+ const now = Date.now();
3349
+ const tx = client.multi();
3350
+ tx.hset(cacheKey, {
3351
+ d: stored,
3352
+ t: String(now),
3353
+ tv: JSON.stringify(activeTagVersions)
3354
+ });
3355
+ tx.expire(cacheKey, ttlSec);
3356
+ await tx.exec();
3357
+ } else {
3358
+ await client.setex(cacheKey, ttlSec, stored);
3359
+ }
3360
+ } catch {
3361
+ }
3362
+ }
3363
+ this.logger.debug("SWR: revalidation complete", { cacheKey });
3364
+ } catch (err) {
3365
+ if (this.opts.staleIfError > 0) {
3366
+ const additionalMs = this.opts.staleIfError * 1e3;
3367
+ this.l1.bumpExpiry(cacheKey, additionalMs);
3368
+ this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
3369
+ cacheKey,
3370
+ staleIfErrorSecs: this.opts.staleIfError
3371
+ });
3372
+ } else {
3373
+ this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
3374
+ }
3375
+ } finally {
3376
+ this.revalidating.delete(cacheKey);
3377
+ }
3378
+ }
3379
+ // ── Explicit set / delete ─────────────────────────────────────────────────
3380
+ /** Explicitly write a value into L1 (+ L2 in production). */
3381
+ async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3382
+ const span = this._startSpan("tricache.set");
3383
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3384
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3385
+ const p = priority ?? inferPriority(cacheKey);
3386
+ const k = this.nk(cacheKey);
3387
+ this.counters.sets++;
3388
+ let activeTagVersions;
3389
+ if (opts?.tags?.length) {
3390
+ if (this.opts.tagStrategy === "generational") {
3391
+ activeTagVersions = {};
3392
+ for (const tag of opts.tags) {
3393
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3394
+ }
3395
+ } else {
3396
+ await this._registerTags(k, opts.tags, ttlSeconds);
3397
+ }
3398
+ }
3399
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3400
+ if (opts?.dependsOn?.length) {
3401
+ for (const pattern of opts.dependsOn) {
3402
+ const nsPattern = this.nk(pattern);
3403
+ let deps = this.dependencyIndex.get(nsPattern);
3404
+ if (!deps) {
3405
+ deps = /* @__PURE__ */ new Set();
3406
+ this.dependencyIndex.set(nsPattern, deps);
3407
+ }
3408
+ deps.add(k);
3409
+ }
3410
+ }
3411
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3412
+ try {
3413
+ const client = await this.getRedis();
3414
+ const s = JSON.stringify(data);
3415
+ const stored = await this._serializeAndEncrypt(s);
3416
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3417
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3418
+ const now = Date.now();
3419
+ const tx = client.multi();
3420
+ tx.hset(k, {
3421
+ d: stored,
3422
+ t: String(now),
3423
+ tv: JSON.stringify(activeTagVersions)
3424
+ });
3425
+ tx.expire(k, ttlSec);
3426
+ await tx.exec();
3427
+ } else {
3428
+ await client.setex(k, ttlSec, stored);
3429
+ }
3430
+ this.cb.onSuccess();
3431
+ } catch (err) {
3432
+ this.cb.onFailure();
3433
+ this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
3434
+ }
3435
+ }
3436
+ void this.publishInvalidation("del", k);
3437
+ span.end();
3438
+ }
3439
+ /**
3440
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
3441
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
3442
+ */
3443
+ async _registerTags(k, tags, ttlSeconds) {
3444
+ for (const tag of tags) {
3445
+ const tagKey = this.nk(`_tag_:${tag}`);
3446
+ let members = this.tagIndex.get(tagKey);
3447
+ if (!members) {
3448
+ members = /* @__PURE__ */ new Set();
3449
+ this.tagIndex.set(tagKey, members);
3450
+ }
3451
+ members.add(k);
3452
+ }
3453
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3454
+ try {
3455
+ const client = await this.getRedis();
3456
+ const pl = client.pipeline();
3457
+ for (const tag of tags) {
3458
+ const tagKey = this.nk(`_tag_:${tag}`);
3459
+ pl.sadd(tagKey, k);
3460
+ pl.expire(tagKey, ttlSeconds + 3600);
3461
+ }
3462
+ await pl.exec();
3463
+ this.cb.onSuccess();
3464
+ } catch {
3465
+ this.cb.onFailure();
3466
+ }
3467
+ }
3468
+ }
3469
+ /**
3470
+ * Delete one key or a glob pattern (supports `*` wildcard).
3471
+ *
3472
+ * @example
3473
+ * await cache.delete('user:abc:profile'); // exact key
3474
+ * await cache.delete('user:abc:*'); // all keys for user abc
3475
+ */
3476
+ async delete(cacheKey) {
3477
+ const span = this._startSpan("tricache.delete");
3478
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3479
+ const isPattern = cacheKey.includes("*");
3480
+ const k = this.nk(cacheKey);
3481
+ this.counters.deletes++;
3482
+ if (isPattern) {
3483
+ this.l1.deletePattern(k);
3484
+ } else {
3485
+ this.l1.delete(k);
3486
+ setImmediate(() => {
3487
+ if (!this._diskDisabled) this.disk.delete(k);
3488
+ });
3489
+ this._cascadeDependencies(k);
3490
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
3491
+ }
3492
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3493
+ try {
3494
+ const client = await this.getRedis();
3495
+ if (isPattern) {
3496
+ const keys = await this._scanKeys(client, k);
3497
+ if (keys.length > 0) await client.del(...keys);
3498
+ } else {
3499
+ await client.del(k);
3500
+ }
3501
+ this.cb.onSuccess();
3502
+ } catch (err) {
3503
+ this.cb.onFailure();
3504
+ this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
3505
+ }
3506
+ }
3507
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
3508
+ span.end();
3509
+ }
3510
+ // ── Counter (distributed rate limiting) ──────────────────────────────────
3511
+ /**
3512
+ * Distributed counter.
3513
+ *
3514
+ * When Redis is active, atomically increments the key via `INCR` and returns
3515
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
3516
+ * and, by default, fails OPEN — returning `0` so a caller's
3517
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
3518
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
3519
+ * when Redis is unavailable.
3520
+ *
3521
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
3522
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
3523
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
3524
+ * a one-time warning is logged because rate-limiting is then per-instance, not
3525
+ * fleet-wide.
3526
+ */
3527
+ async increment(cacheKey, ttlSeconds) {
3528
+ const k = this.nk(cacheKey);
3529
+ if (this._redisDisabled) {
3530
+ if (!this._incrementFallbackWarned) {
3531
+ this._incrementFallbackWarned = true;
3532
+ this.logger.warn(
3533
+ "tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
3534
+ { cacheKey }
3535
+ );
3536
+ }
3537
+ const now = Date.now();
3538
+ const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1e3;
3539
+ const entry = this._l1Counters.get(k);
3540
+ if (entry && entry.expiresAt > now) {
3541
+ entry.value++;
3542
+ return entry.value;
3543
+ }
3544
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
3545
+ return 1;
3546
+ }
3547
+ try {
3548
+ const client = await this.getRedis();
3549
+ const count = await client.incr(k);
3550
+ if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
3551
+ return count;
3552
+ } catch (err) {
3553
+ this.counters.counterErrors++;
3554
+ this.cb.onFailure();
3555
+ this.logger.error("increment: Redis error", { cacheKey }, err);
3556
+ if (this.opts.failClosed) throw err;
3557
+ return 0;
3558
+ }
3559
+ }
3560
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
3561
+ /**
3562
+ * Flush all cached entries, or only those whose key starts with `prefix`.
3563
+ *
3564
+ * @example
3565
+ * await cache.clear(); // flush everything
3566
+ * await cache.clear('user:abc'); // flush all keys for one user
3567
+ */
3568
+ async clear(prefix) {
3569
+ this.counters.deletes++;
3570
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
3571
+ if (k) {
3572
+ this.l1.deletePattern(k);
3573
+ } else {
3574
+ this.l1.clear();
3575
+ if (!this._diskDisabled) this.disk.clear();
3576
+ this._l1Counters.clear();
3577
+ this.tagIndex.clear();
3578
+ this.tagVersions.clear();
3579
+ }
3580
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3581
+ try {
3582
+ const client = await this.getRedis();
3583
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
3584
+ const keys = await this._scanKeys(client, pattern);
3585
+ if (keys.length > 0) await client.del(...keys);
3586
+ } catch (err) {
3587
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
3588
+ }
3589
+ }
3590
+ void this.publishInvalidation(
3591
+ "del-glob",
3592
+ k ?? (this._namespace ? `${this._namespace}:*` : "*")
3593
+ );
3594
+ }
3595
+ /**
3596
+ * Evict L1 entries that violate the current category or global capacity limits.
3597
+ * Useful after a write burst or after adding stricter `categoryLimits`.
3598
+ * Returns the number of entries evicted.
3599
+ */
3600
+ rebalance() {
3601
+ return this.l1.rebalance();
3602
+ }
3603
+ /**
3604
+ * Return the remaining TTL in seconds for a key currently in L1.
3605
+ * Returns null if the key is absent from L1 or has already expired.
3606
+ * Only reflects L1 state — does not query Redis or disk.
3607
+ */
3608
+ ttl(cacheKey) {
3609
+ return this.l1.ttl(this.nk(cacheKey));
3610
+ }
3611
+ /**
3612
+ * Return true if the key exists in L1 and has not expired.
3613
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
3614
+ */
3615
+ has(cacheKey) {
3616
+ return this.l1.has(this.nk(cacheKey));
3617
+ }
3618
+ // ── Iteration ─────────────────────────────────────────────────────────────
3619
+ /**
3620
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
3621
+ *
3622
+ * @example
3623
+ * for (const key of cache.keys()) console.log(key);
3624
+ */
3625
+ *keys() {
3626
+ const prefix = this._namespace ? this._namespace + ":" : "";
3627
+ for (const key of this.l1.liveKeys()) {
3628
+ if (prefix && !key.startsWith(prefix)) continue;
3629
+ yield prefix ? key.slice(prefix.length) : key;
3630
+ }
3631
+ }
3632
+ /**
3633
+ * Lazily yield every non-expired L1 value.
3634
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
3635
+ *
3636
+ * @example
3637
+ * for (const val of cache.values<User>()) console.log(val.id);
3638
+ */
3639
+ *values() {
3640
+ const prefix = this._namespace ? this._namespace + ":" : "";
3641
+ if (!prefix) {
3642
+ yield* this.l1.liveValues();
3643
+ } else {
3644
+ for (const [key, entry] of this.l1.liveEntries()) {
3645
+ if (!key.startsWith(prefix)) continue;
3646
+ yield this.l1.resolveValue(entry);
3647
+ }
3648
+ }
3649
+ }
3650
+ /**
3651
+ * Lazily yield every non-expired L1 [key, value] pair.
3652
+ * Keys are stripped of their namespace prefix.
3653
+ *
3654
+ * @example
3655
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
3656
+ */
3657
+ *entries() {
3658
+ const prefix = this._namespace ? this._namespace + ":" : "";
3659
+ for (const [key, entry] of this.l1.liveEntries()) {
3660
+ if (prefix && !key.startsWith(prefix)) continue;
3661
+ yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry)];
3662
+ }
3663
+ }
3664
+ /**
3665
+ * High-throughput bulk scan over all live L1 entries.
3666
+ *
3667
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
3668
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
3669
+ * caller uses the `offset` parameter instead of pre-slicing.
3670
+ *
3671
+ * ```typescript
3672
+ * // Zero extra string allocations — use rawKey + offset directly:
3673
+ * cache.scan((rawKey, value, offset) => {
3674
+ * const key = rawKey.slice(offset); // allocate only if needed
3675
+ * sync(key, value as User);
3676
+ * });
3677
+ * ```
3678
+ *
3679
+ * @param fn Called once per live L1 entry.
3680
+ * `rawKey` — key with namespace prefix still attached.
3681
+ * `value` — deserialized cached value.
3682
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
3683
+ */
3684
+ scan(fn) {
3685
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3686
+ this.l1.scan((key, entry, pfx) => {
3687
+ const value = entry.value !== void 0 ? entry.value : entry.data;
3688
+ fn(key, value, pfx);
3689
+ }, prefixLen);
3690
+ }
3691
+ /**
3692
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
3693
+ * Returns `false` if the key is absent or already expired.
3694
+ *
3695
+ * @param newTtlSeconds - The new TTL from now, in seconds.
3696
+ */
3697
+ async touch(cacheKey, newTtlSeconds) {
3698
+ const k = this.nk(cacheKey);
3699
+ const hit = this.l1.touch(k, newTtlSeconds * 1e3);
3700
+ if (hit && !this._redisDisabled) {
3701
+ try {
3702
+ const client = await this.getRedis();
3703
+ void client.expire(k, newTtlSeconds);
3704
+ } catch {
3705
+ }
3706
+ }
3707
+ return hit;
3708
+ }
3709
+ /**
3710
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
3711
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
3712
+ *
3713
+ * @example
3714
+ * const fresh = cache.getIfFresh('user:123');
3715
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
3716
+ */
3717
+ getIfFresh(cacheKey) {
3718
+ const k = this.nk(cacheKey);
3719
+ const entry = this.l1.getEntry(k);
3720
+ if (!entry) return null;
3721
+ const now = Date.now();
3722
+ if (entry.expiresAt <= now) return null;
3723
+ if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
3724
+ return entry.value !== void 0 ? entry.value : unpack3(entry.data);
3725
+ }
3726
+ /**
3727
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
3728
+ * Returns the cached value if found and valid, or `null` if absent / expired.
3729
+ * Does not write dummy entries on misses or trigger side-effects.
3730
+ *
3731
+ * @example
3732
+ * const val = await cache.peek<User>('user:123');
3733
+ */
3734
+ async peek(cacheKey) {
3735
+ const k = this.nk(cacheKey);
3736
+ const l1Hit = this.l1.get(k);
3737
+ if (l1Hit !== null) {
3738
+ this.counters.gets++;
3739
+ this.counters.l1Hits++;
3740
+ const val = l1Hit.value;
3741
+ if (this.opts.frozen) deepFreeze(val);
3742
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
3743
+ }
3744
+ if (!this._diskDisabled) {
3745
+ const diskHit = this.disk.load(k);
3746
+ if (diskHit !== null) {
3747
+ const promoted = this.l1.importEntries(
3748
+ [{ key: k, entry: diskHit }],
3749
+ this.opts.forbiddenSnapshotPrefixes
3750
+ );
3751
+ if (promoted > 0) {
3752
+ const l1Check = this.l1.get(k);
3753
+ if (l1Check !== null) {
3754
+ this.counters.gets++;
3755
+ this.counters.diskHits++;
3756
+ const val = l1Check.value;
3757
+ if (this.opts.frozen) deepFreeze(val);
3758
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
3759
+ }
3760
+ }
3761
+ }
3762
+ }
3763
+ if (!this._redisDisabled && !this.cb.isOpen) {
3764
+ try {
3765
+ const client = await this.getRedis();
3766
+ const raw = await client.get(k);
3767
+ if (raw !== null) {
3768
+ const parsed = await this._decryptAndDeserialize(raw);
3769
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
3770
+ this.counters.gets++;
3771
+ this.counters.l2Hits++;
3772
+ this.cb.onSuccess();
3773
+ if (this.opts.frozen) deepFreeze(parsed);
3774
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3775
+ }
3776
+ } catch (err) {
3777
+ this.cb.onFailure();
3778
+ this.logger.debug("peek: Redis read failed", { cacheKey, error: err.message });
3779
+ }
3780
+ }
3781
+ return null;
3782
+ }
3783
+ /**
3784
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
3785
+ * Preserves input ordering. Uses inflight coalescing per key.
3786
+ *
3787
+ * @param keys - Array of cache keys.
3788
+ * @param fetchFn - Called with only the keys that missed L1.
3789
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
3790
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
3791
+ */
3792
+ async mget(keys, fetchFn, ttl = 300, priority) {
3793
+ const result = Array.from({ length: keys.length });
3794
+ const missIndexes = [];
3795
+ const missKeys = [];
3796
+ for (let i = 0; i < keys.length; i++) {
3797
+ const k = this.nk(keys[i]);
3798
+ const entry = this.l1.getEntry(k);
3799
+ if (entry && entry.expiresAt > Date.now()) {
3800
+ result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
3801
+ this.counters.l1Hits++;
3802
+ } else {
3803
+ missIndexes.push(i);
3804
+ missKeys.push(keys[i]);
3805
+ }
3806
+ }
3807
+ if (missKeys.length === 0) return result;
3808
+ if (!this._redisDisabled) {
3809
+ try {
3810
+ const client = await this.getRedis();
3811
+ const nsKeys = missKeys.map((k) => this.nk(k));
3812
+ const pipeline = client.multi();
3813
+ for (const nk of nsKeys) pipeline.get(nk);
3814
+ const raws = await pipeline.exec();
3815
+ this.cb.onSuccess();
3816
+ for (let j = 0; j < missKeys.length; j++) {
3817
+ const raw = raws[j] ? raws[j][1] : null;
3818
+ const idx = missIndexes[j];
3819
+ if (raw) {
3820
+ const parsed = await this._decryptAndDeserialize(raw);
3821
+ const k = nsKeys[j];
3822
+ const p = priority ?? inferPriority(missKeys[j]);
3823
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
3824
+ this.counters.l2Hits++;
3825
+ result[idx] = parsed;
3826
+ missIndexes[j] = -1;
3827
+ missKeys[j] = "";
3828
+ }
3829
+ }
3830
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
3831
+ const remainingKeys = missKeys.filter((k) => k !== "");
3832
+ missIndexes.length = 0;
3833
+ missKeys.length = 0;
3834
+ missIndexes.push(...remainingIdx);
3835
+ missKeys.push(...remainingKeys);
3836
+ if (missKeys.length === 0) return result;
3837
+ } catch (err) {
3838
+ this.cb.onFailure();
3839
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
3840
+ }
3841
+ }
3842
+ if (!this._diskDisabled) {
3843
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3844
+ const k = this.nk(missKeys[j]);
3845
+ const diskHit = this.disk.load(k);
3846
+ if (diskHit !== null) {
3847
+ const promoted = this.l1.importEntries(
3848
+ [{ key: k, entry: diskHit }],
3849
+ this.opts.forbiddenSnapshotPrefixes
3850
+ );
3851
+ if (promoted > 0) {
3852
+ const l1Check = this.l1.get(k);
3853
+ if (l1Check !== null) {
3854
+ this.counters.diskHits++;
3855
+ result[missIndexes[j]] = l1Check.value;
3856
+ missIndexes.splice(j, 1);
3857
+ missKeys.splice(j, 1);
3858
+ }
3859
+ }
3860
+ }
3861
+ }
3862
+ if (missKeys.length === 0) return result;
3863
+ }
3864
+ if (missKeys.length > 0) {
3865
+ this.counters.fetches++;
3866
+ const fetched = await fetchFn(missKeys);
3867
+ for (let j = 0; j < missKeys.length; j++) {
3868
+ const v = fetched[missKeys[j]];
3869
+ result[missIndexes[j]] = v;
3870
+ if (v !== void 0) {
3871
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
3872
+ await this.set(missKeys[j], v, resolvedTtl, priority);
3873
+ }
3874
+ }
3875
+ }
3876
+ return result;
3877
+ }
3878
+ /**
3879
+ * Returns a Promise that resolves once the cache is fully initialised and any
3880
+ * startup warming configured via `warmKeys` has completed.
3881
+ *
3882
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
3883
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
3884
+ *
3885
+ * @example
3886
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
3887
+ * await cache.ready(); // gate traffic until warm
3888
+ */
3889
+ ready() {
3890
+ return this._readyPromise;
3891
+ }
3892
+ /**
3893
+ * Batch write — set multiple entries in a single call.
3894
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
3895
+ *
3896
+ * @example
3897
+ * await cache.mset({
3898
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
3899
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
3900
+ * });
3901
+ */
3902
+ async mset(entries) {
3903
+ const keys = Object.keys(entries);
3904
+ await Promise.all(keys.map((key) => {
3905
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3906
+ const hasOpts = tags?.length || dependsOn?.length;
3907
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
3908
+ }));
3909
+ }
3910
+ /**
3911
+ * Batch delete — delete multiple exact keys in a single call.
3912
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
3913
+ *
3914
+ * @example
3915
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
3916
+ */
3917
+ async mdel(keys) {
3918
+ await Promise.all(keys.map((k) => this.delete(k)));
3919
+ }
3920
+ /**
3921
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
3922
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
3923
+ * the local snapshot is unavailable or too stale.
3924
+ *
3925
+ * Returns the number of keys loaded into L1.
3926
+ *
3927
+ * @example
3928
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
3929
+ * const loaded = await cache.warmFromL2('org:*');
3930
+ * console.log(`Warmed ${loaded} keys from Redis`);
3931
+ */
3932
+ async warmFromL2(pattern, opts) {
3933
+ if (this._redisDisabled) return 0;
3934
+ try {
3935
+ const client = await this.getRedis();
3936
+ const nsPattern = this.nk(pattern);
3937
+ const matchedKeys = await this._scanKeys(client, nsPattern);
3938
+ if (matchedKeys.length === 0) {
3939
+ this.cb.onSuccess();
3940
+ return 0;
3941
+ }
3942
+ const pl = client.pipeline();
3943
+ for (const k of matchedKeys) pl.get(k);
3944
+ const results = await pl.exec();
3945
+ this.cb.onSuccess();
3946
+ let loaded = 0;
3947
+ const now = Date.now();
3948
+ for (let i = 0; i < matchedKeys.length; i++) {
3949
+ const [err, raw] = results[i];
3950
+ if (err || raw == null) continue;
3951
+ try {
3952
+ const parsed = await this._decryptAndDeserialize(raw);
3953
+ const remainingMs = 10 * 60 * 1e3;
3954
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3955
+ loaded++;
3956
+ } catch {
3957
+ }
3958
+ }
3959
+ void now;
3960
+ this.logger.info("warmFromL2 complete", {
3961
+ pattern,
3962
+ matched: matchedKeys.length,
3963
+ loaded
3964
+ });
3965
+ return loaded;
3966
+ } catch (err) {
3967
+ this.cb.onFailure();
3968
+ this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
3969
+ return 0;
3970
+ }
3971
+ }
3972
+ /**
3973
+ * Invalidate all keys associated with a tag.
3974
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
3975
+ *
3976
+ * @example
3977
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
3978
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3979
+ */
3980
+ async invalidateTag(tag) {
3981
+ if (this.opts.tagStrategy === "generational") {
3982
+ let newVer = 1;
3983
+ if (!this._redisDisabled) {
3984
+ try {
3985
+ const client = await this.getRedis();
3986
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3987
+ } catch (err) {
3988
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
3989
+ const current = this.tagVersions.get(tag)?.version ?? 0;
3990
+ newVer = current + 1;
3991
+ }
3992
+ } else {
3993
+ const current = this.tagVersions.get(tag)?.version ?? 0;
3994
+ newVer = current + 1;
3995
+ }
3996
+ this._setLocalTagVersion(tag, newVer, Date.now());
3997
+ void this.publishInvalidation("tag_incr", tag, newVer);
3998
+ return;
3999
+ }
4000
+ const tagKey = this.nk(`_tag_:${tag}`);
4001
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4002
+ for (const k of members) {
4003
+ this.l1.delete(k);
4004
+ if (!this._diskDisabled) this.disk.delete(k);
4005
+ }
4006
+ this.tagIndex.delete(tagKey);
4007
+ if (!this._redisDisabled) {
4008
+ try {
4009
+ const client = await this.getRedis();
4010
+ const redisMembers = await client.smembers(tagKey);
4011
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
4012
+ if (toDelete.length > 0) {
4013
+ await client.del(...toDelete, tagKey);
4014
+ } else {
4015
+ await client.del(tagKey);
4016
+ }
4017
+ } catch (err) {
4018
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4019
+ }
4020
+ }
4021
+ }
4022
+ /**
4023
+ * Invalidate all keys associated with any of the given tags in a single operation.
4024
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
4025
+ * reducing latency when invalidating several related tags together.
4026
+ *
4027
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
4028
+ * synchronously before the Redis round-trip.
4029
+ *
4030
+ * @example
4031
+ * // Instead of three serial round-trips:
4032
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
4033
+ */
4034
+ async invalidateTags(tags) {
4035
+ if (tags.length === 0) return;
4036
+ if (tags.length === 1) {
4037
+ await this.invalidateTag(tags[0]);
4038
+ return;
4039
+ }
4040
+ if (this.opts.tagStrategy === "generational") {
4041
+ const now = Date.now();
4042
+ if (!this._redisDisabled) {
4043
+ try {
4044
+ const client = await this.getRedis();
4045
+ const pl = client.pipeline();
4046
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
4047
+ const results = await pl.exec();
4048
+ for (let i = 0; i < tags.length; i++) {
4049
+ const [err, newVer] = results[i] ?? [null, null];
4050
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4051
+ this._setLocalTagVersion(tags[i], ver, now);
4052
+ void this.publishInvalidation("tag_incr", tags[i], ver);
4053
+ }
4054
+ return;
4055
+ } catch (err) {
4056
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
4057
+ }
4058
+ }
4059
+ for (const tag of tags) {
4060
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4061
+ this._setLocalTagVersion(tag, ver, now);
4062
+ void this.publishInvalidation("tag_incr", tag, ver);
4063
+ }
4064
+ return;
4065
+ }
4066
+ const tagKeys = [];
4067
+ const allMembers = /* @__PURE__ */ new Set();
4068
+ for (const tag of tags) {
4069
+ const tagKey = this.nk(`_tag_:${tag}`);
4070
+ tagKeys.push(tagKey);
4071
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4072
+ for (const k of members) allMembers.add(k);
4073
+ this.tagIndex.delete(tagKey);
4074
+ }
4075
+ for (const k of allMembers) {
4076
+ this.l1.delete(k);
4077
+ this.disk.delete(k);
4078
+ }
4079
+ if (!this._redisDisabled) {
4080
+ try {
4081
+ const client = await this.getRedis();
4082
+ const pl = client.pipeline();
4083
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
4084
+ const smResults = await pl.exec();
4085
+ const toDelete = [...allMembers];
4086
+ for (const [err, redisMembers] of smResults) {
4087
+ if (!err && redisMembers) {
4088
+ for (const k of redisMembers) {
4089
+ if (!allMembers.has(k)) toDelete.push(k);
4090
+ }
4091
+ }
4092
+ }
4093
+ const keysToRemove = [...toDelete, ...tagKeys];
4094
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
4095
+ } catch (err) {
4096
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
4097
+ }
4098
+ }
4099
+ }
4100
+ /**
4101
+ * Get the current generational tag version for a tag (synced with Redis when due).
4102
+ */
4103
+ async getTagVersion(tag) {
4104
+ return this._getTagVersion(tag);
4105
+ }
4106
+ /**
4107
+ * Measure L1 / disk / Redis latency.
4108
+ * Useful for health checks and dashboards.
4109
+ *
4110
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
4111
+ * `l2` is `null` when Redis is disabled.
4112
+ */
4113
+ async ping() {
4114
+ const t0 = Date.now();
4115
+ this.l1.has("__ping__");
4116
+ const l1 = Date.now() - t0;
4117
+ const t1 = Date.now();
4118
+ void this.disk.stats;
4119
+ const disk = Date.now() - t1;
4120
+ let l2 = null;
4121
+ if (!this._redisDisabled) {
4122
+ try {
4123
+ const client = await this.getRedis();
4124
+ const t2 = Date.now();
4125
+ await client.ping();
4126
+ l2 = Date.now() - t2;
4127
+ } catch {
4128
+ l2 = null;
4129
+ }
4130
+ }
4131
+ return { l1, disk, l2 };
4132
+ }
4133
+ /**
4134
+ * Export all live L1 entries to Redis via a single pipeline.
4135
+ * Useful for warming a new Redis instance or for zero-downtime failover.
4136
+ * Returns the number of keys written.
4137
+ */
4138
+ async drainToL2() {
4139
+ if (this._redisDisabled) return 0;
4140
+ try {
4141
+ const client = await this.getRedis();
4142
+ const entries = this.l1.exportEntries([]);
4143
+ const now = Date.now();
4144
+ if (entries.length === 0) return 0;
4145
+ const pl = client.pipeline();
4146
+ for (const { key, entry } of entries) {
4147
+ const remainingMs = entry.expiresAt - now;
4148
+ if (remainingMs <= 0) continue;
4149
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
4150
+ const s = JSON.stringify(entry.value);
4151
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
4152
+ pl.setex(key, ttlSecs, stored);
4153
+ }
4154
+ await pl.exec();
4155
+ return entries.length;
4156
+ } catch (err) {
4157
+ this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
4158
+ return 0;
4159
+ }
4160
+ }
4161
+ // ── Stats ─────────────────────────────────────────────────────────────
4162
+ stats() {
4163
+ return {
4164
+ l1: this.l1.getStats(),
4165
+ disk: this.disk.stats
4166
+ };
4167
+ }
4168
+ // ── Conditional write ─────────────────────────────────────────────────
4169
+ /**
4170
+ * Write `value` only if the key is not already cached.
4171
+ * Returns `true` if the write happened, `false` if the key already existed.
4172
+ *
4173
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
4174
+ * is safe to use for idempotency keys and "first writer wins" patterns across
4175
+ * multiple instances. L1 is populated on success.
4176
+ *
4177
+ * @example
4178
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
4179
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
4180
+ */
4181
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
4182
+ const k = this.nk(cacheKey);
4183
+ if (this.l1.has(k)) return false;
4184
+ if (!this._redisDisabled) {
4185
+ try {
4186
+ const client = await this.getRedis();
4187
+ const serialized = JSON.stringify(value);
4188
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
4189
+ const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
4190
+ this.cb.onSuccess();
4191
+ if (result === null) return false;
4192
+ } catch (err) {
4193
+ this.cb.onFailure();
4194
+ this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
4195
+ if (this.l1.has(k)) return false;
4196
+ }
4197
+ }
4198
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
4199
+ const p = priority ?? inferPriority(cacheKey);
4200
+ this.l1.set(k, value, ttlMs, p);
4201
+ this.counters.sets++;
4202
+ return true;
4203
+ }
4204
+ // ── Distributed / In-Process Mutex Lock ───────────────────────────────────
4205
+ /**
4206
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
4207
+ * execute `fn`, and automatically release the lock on completion or error.
4208
+ *
4209
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
4210
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
4211
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
4212
+ *
4213
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
4214
+ * @param fn Task to run exclusively while holding the lock.
4215
+ * @param options TTL, acquire timeout, and retry polling intervals.
4216
+ */
4217
+ async lock(resourceKey, fn, options) {
4218
+ const ttlSeconds = Math.max(1, options?.ttl ?? 30);
4219
+ const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
4220
+ const retryInterval = Math.max(10, options?.retryInterval ?? 100);
4221
+ const lockKey = this.nk(`lock:${resourceKey}`);
4222
+ const token = crypto2.randomUUID();
4223
+ const deadline = Date.now() + acquireTimeout;
4224
+ let acquired = false;
4225
+ if (!this._redisDisabled) {
4226
+ try {
4227
+ const client = await this.getRedis();
4228
+ while (Date.now() <= deadline) {
4229
+ const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4230
+ if (res === "OK") {
4231
+ acquired = true;
4232
+ break;
4233
+ }
4234
+ const remaining = deadline - Date.now();
4235
+ if (remaining <= 0) break;
4236
+ await new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)));
4237
+ }
4238
+ if (!acquired) {
4239
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4240
+ }
4241
+ try {
4242
+ return await fn();
4243
+ } finally {
4244
+ try {
4245
+ const LUA_RELEASE_LOCK = `
4246
+ if redis.call("get", KEYS[1]) == ARGV[1] then
4247
+ return redis.call("del", KEYS[1])
4248
+ else
4249
+ return 0
4250
+ end
4251
+ `;
4252
+ await client.eval(LUA_RELEASE_LOCK, 1, lockKey, token);
4253
+ } catch {
4254
+ }
4255
+ }
4256
+ } catch (err) {
4257
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4258
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4259
+ resourceKey,
4260
+ error: err.message
4261
+ });
4262
+ }
4263
+ }
4264
+ let unlock = () => {
4265
+ };
4266
+ const lockPromise = new Promise((resolve) => {
4267
+ unlock = resolve;
4268
+ });
4269
+ while (Date.now() <= deadline) {
4270
+ const existing = this._localLocks.get(lockKey);
4271
+ if (!existing) {
4272
+ this._localLocks.set(lockKey, lockPromise);
4273
+ acquired = true;
4274
+ break;
4275
+ }
4276
+ const remaining = deadline - Date.now();
4277
+ if (remaining <= 0) break;
4278
+ await Promise.race([
4279
+ existing,
4280
+ new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)))
4281
+ ]);
4282
+ }
4283
+ if (!acquired) {
4284
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4285
+ }
4286
+ try {
4287
+ return await fn();
4288
+ } finally {
4289
+ unlock();
4290
+ if (this._localLocks.get(lockKey) === lockPromise) {
4291
+ this._localLocks.delete(lockKey);
4292
+ }
4293
+ }
4294
+ }
4295
+ // ── OpenTelemetry Metrics Integration ──────────────────────────────────────
4296
+ _initOtelMetrics(meter) {
4297
+ try {
4298
+ this._otelMetrics.gets = meter.createCounter("tricache.gets.total", { description: "Total cache get operations" });
4299
+ this._otelMetrics.l1Hits = meter.createCounter("tricache.l1.hits", { description: "L1 RAM cache hits" });
4300
+ this._otelMetrics.l2Hits = meter.createCounter("tricache.l2.hits", { description: "L2 Redis cache hits" });
4301
+ this._otelMetrics.diskHits = meter.createCounter("tricache.disk.hits", { description: "L1.5 disk cache hits" });
4302
+ this._otelMetrics.fetches = meter.createCounter("tricache.fetches", { description: "Cache miss fetch calls" });
4303
+ this._otelMetrics.stampedes = meter.createCounter("tricache.stampedes.prevented", { description: "Coalesced duplicate inflight requests" });
4304
+ this._otelMetrics.sets = meter.createCounter("tricache.sets.total", { description: "Total set operations" });
4305
+ this._otelMetrics.deletes = meter.createCounter("tricache.deletes.total", { description: "Total delete operations" });
4306
+ this._otelMetrics.swrRevalidations = meter.createCounter("tricache.swr.revalidations", { description: "SWR background revalidations" });
4307
+ const gL1Entries = meter.createObservableGauge("tricache.l1.entries", { description: "Current L1 entry count" });
4308
+ const gL1Bytes = meter.createObservableGauge("tricache.l1.bytes", { description: "Current L1 memory usage in bytes" });
4309
+ const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
4310
+ const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
4311
+ const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
4312
+ meter.addBatchObservableCallback((observableResult) => {
4313
+ const stats = this.stats();
4314
+ const l1 = stats.l1;
4315
+ const disk = stats.disk;
4316
+ const checks = this.counters.bloomChecks;
4317
+ const fps = this.counters.bloomFalsePositives;
4318
+ const fpr = checks > 0 ? fps / checks : 0;
4319
+ const attrs = this._namespace ? { namespace: this._namespace } : void 0;
4320
+ observableResult.observe(gL1Entries, l1.entries, attrs);
4321
+ observableResult.observe(gL1Bytes, l1.sizeBytes, attrs);
4322
+ observableResult.observe(gDiskFiles, disk.files, attrs);
4323
+ observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
4324
+ observableResult.observe(gBloomFpr, fpr, attrs);
4325
+ }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
4326
+ } catch (err) {
4327
+ this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
4328
+ }
4329
+ }
4330
+ // ── Hot key introspection ─────────────────────────────────────────────
4331
+ /**
4332
+ * Return the top-N live L1 keys by historical access frequency.
4333
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
4334
+ * whose historical frequency exceeds their current in-memory hit count.
4335
+ *
4336
+ * Useful for diagnosing what is driving L1 pressure without any extra data
4337
+ * collection overhead.
4338
+ *
4339
+ * @param n - Maximum number of keys to return. Default: 10.
4340
+ *
4341
+ * @example
4342
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
4343
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
4344
+ */
4345
+ hotKeys(n = 10) {
4346
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4347
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
4348
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
4349
+ hits,
4350
+ sizeBytes
4351
+ }));
4352
+ }
4353
+ // ── Dependency cascade helpers ────────────────────────────────────────
4354
+ /**
4355
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
4356
+ * pattern that may contain `*` wildcards).
4357
+ */
4358
+ _matchesGlob(key, pattern) {
4359
+ if (!pattern.includes("*")) return key === pattern;
4360
+ return getGlobRegex(pattern).test(key);
4361
+ }
4362
+ /**
4363
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
4364
+ * that was registered via `dependsOn` and whose source pattern matches.
4365
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
4366
+ */
4367
+ _cascadeDependencies(deletedKey, visited = /* @__PURE__ */ new Set()) {
4368
+ if (visited.has(deletedKey)) return;
4369
+ visited.add(deletedKey);
4370
+ for (const [pattern, dependents] of this.dependencyIndex) {
4371
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
4372
+ for (const dep of dependents) {
4373
+ if (visited.has(dep)) continue;
4374
+ this.l1.delete(dep);
4375
+ if (!this._diskDisabled) this.disk.delete(dep);
4376
+ void this.publishInvalidation("del", dep);
4377
+ this.logger.debug("Dependency cascade: invalidated dependent key", {
4378
+ trigger: deletedKey.slice(0, 60),
4379
+ dependent: dep.slice(0, 60)
4380
+ });
4381
+ this._cascadeDependencies(dep, visited);
4382
+ }
4383
+ }
4384
+ }
4385
+ // ── Observability ──────────────────────────────────────────────────────────────────
4386
+ /** Return a full metrics snapshot. */
4387
+ metrics() {
4388
+ const c = this.counters;
4389
+ const l1s = this.l1.getStats();
4390
+ const div = (n, d) => d > 0 ? n / d : 0;
4391
+ return {
4392
+ namespace: this.opts.namespace,
4393
+ uptimeMs: Date.now() - c.startedAt,
4394
+ gets: {
4395
+ total: c.gets,
4396
+ l1Hits: c.l1Hits,
4397
+ l1HitRate: div(c.l1Hits, c.gets),
4398
+ diskHits: c.diskHits,
4399
+ diskHitRate: div(c.diskHits, c.gets),
4400
+ l2Hits: c.l2Hits,
4401
+ l2HitRate: div(c.l2Hits, c.gets),
4402
+ fetches: c.fetches,
4403
+ fetchRate: div(c.fetches, c.gets),
4404
+ stampedePrevented: c.stampedes
4405
+ },
4406
+ sets: { total: c.sets },
4407
+ deletes: { total: c.deletes },
4408
+ revalidations: { total: c.swrRevalidations },
4409
+ counters: {
4410
+ errors: c.counterErrors,
4411
+ singletonDivergences: c.singletonDivergences
4412
+ },
4413
+ bloom: {
4414
+ checksTotal: l1s.bloom.checks,
4415
+ falsePositives: l1s.bloom.falsePositives,
4416
+ falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks)
4417
+ },
4418
+ compression: {
4419
+ entriesCompressed: l1s.compression.compressed,
4420
+ entriesUncompressed: l1s.compression.uncompressed,
4421
+ bytesSaved: l1s.compression.bytesSaved
4422
+ },
4423
+ backplane: {
4424
+ enabled: this.opts.invalidationBackplane && !this._redisDisabled,
4425
+ mode: this.opts.backplaneMode,
4426
+ sent: c.invSent,
4427
+ received: c.invReceived,
4428
+ skipped: c.invSkipped,
4429
+ streamEntriesReceived: c.streamEntriesReceived,
4430
+ streamReplays: c.streamReplays,
4431
+ streamGaps: c.streamGaps
4432
+ },
4433
+ l2CircuitBreaker: {
4434
+ state: this.cb.currentState
4435
+ },
4436
+ oom: {
4437
+ enabled: this.opts.oomProtection,
4438
+ evictions: c.oomEvictions,
4439
+ lastTriggeredAt: c.oomLastAt
4440
+ },
4441
+ l1: {
4442
+ entries: l1s.entries,
4443
+ sizeBytes: this.l1.memoryUsage,
4444
+ maxBytes: this.opts.l1MaxBytes
4445
+ },
4446
+ disk: { ...this.disk.stats, disabled: this._diskDisabled },
4447
+ ...this.latencyTracker && {
4448
+ adaptiveTtl: {
4449
+ enabled: true,
4450
+ trackedKeys: this.latencyTracker.trackedKeys,
4451
+ slowestKeys: this.latencyTracker.snapshot(
4452
+ this._namespace ? this._namespace.length + 1 : 0,
4453
+ // strip "namespace:" prefix
4454
+ this.opts.adaptiveTtlMultiplier,
4455
+ this.opts.adaptiveTtlMinMs,
4456
+ this.opts.adaptiveTtlMaxMs
4457
+ )
4458
+ }
4459
+ }
4460
+ };
4461
+ }
4462
+ /**
4463
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
4464
+ * Paste the result into your `/metrics` endpoint.
4465
+ *
4466
+ * @param m - Snapshot returned by `cache.metrics()`
4467
+ * @param prefix - Metric name prefix. Default: `"tricache"`
4468
+ */
4469
+ static toPrometheusText(m, prefix = "tricache", instanceName) {
4470
+ const parts = [];
4471
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
4472
+ if (instanceName) parts.push(`instance="${instanceName}"`);
4473
+ const lbl = parts.length ? `{${parts.join(",")}}` : "";
4474
+ const lines = [];
4475
+ const counter = (name, val, help) => {
4476
+ lines.push(`# HELP ${prefix}_${name}_total ${help}`);
4477
+ lines.push(`# TYPE ${prefix}_${name}_total counter`);
4478
+ lines.push(`${prefix}_${name}_total${lbl} ${val}`);
4479
+ };
4480
+ const gauge = (name, val, help) => {
4481
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
4482
+ lines.push(`# TYPE ${prefix}_${name} gauge`);
4483
+ lines.push(`${prefix}_${name}${lbl} ${val}`);
4484
+ };
4485
+ counter("gets", m.gets.total, "Total get() calls");
4486
+ counter("l1_hits", m.gets.l1Hits, "L1 RAM cache hits");
4487
+ counter("disk_hits", m.gets.diskHits, "L1.5 disk tier hits");
4488
+ counter("l2_hits", m.gets.l2Hits, "L2 Redis hits");
4489
+ counter("fetches", m.gets.fetches, "fetchFn calls (cache misses)");
4490
+ counter("stampedes_prevented", m.gets.stampedePrevented, "Coalesced duplicate inflight requests");
4491
+ counter("sets", m.sets.total, "Total set() calls");
4492
+ counter("deletes", m.deletes.total, "Total delete() calls");
4493
+ counter("swr_revalidations", m.revalidations.total, "Stale-While-Revalidate background refreshes");
4494
+ gauge("l1_hit_rate", m.gets.l1HitRate, "Fraction of gets served from L1 RAM (0-1)");
4495
+ gauge("disk_hit_rate", m.gets.diskHitRate, "Fraction of gets served from disk (0-1)");
4496
+ gauge("l2_hit_rate", m.gets.l2HitRate, "Fraction of gets served from Redis (0-1)");
4497
+ gauge("fetch_rate", m.gets.fetchRate, "Fraction of gets calling fetchFn (0-1)");
4498
+ gauge("l1_entries", m.l1.entries, "Current L1 entry count");
4499
+ gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
4500
+ gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
4501
+ gauge(
4502
+ "bloom_false_positive_rate",
4503
+ m.bloom.falsePositiveRate,
4504
+ "Bloom filter false-positive rate; increase capacity if > 0.01"
4505
+ );
4506
+ gauge(
4507
+ "compression_bytes_saved",
4508
+ m.compression.bytesSaved,
4509
+ "Approximate bytes saved by msgpackr compression"
4510
+ );
4511
+ if (m.backplane.enabled) {
4512
+ counter("backplane_sent", m.backplane.sent, "Invalidation messages sent via Pub/Sub");
4513
+ counter("backplane_received", m.backplane.received, "Invalidation messages received from peers");
4514
+ }
4515
+ if (m.oom.enabled) {
4516
+ counter(
4517
+ "oom_evictions",
4518
+ m.oom.evictions,
4519
+ "Emergency L1 eviction rounds triggered by heap pressure"
4520
+ );
4521
+ }
4522
+ return lines.join("\n");
4523
+ }
4524
+ // ── Lifecycle ────────────────────────────────────────────────────────────
4525
+ /**
4526
+ * Dynamically rotate the active encryption key at runtime without restarting.
4527
+ * Installs the new key as primary for all subsequent writes, while preserving
4528
+ * the previous key for seamless fallback decryption of existing cache entries.
4529
+ */
4530
+ async rotateEncryptionKey(newKeyBase64, newMode) {
4531
+ this.enc.rotateKey(newKeyBase64, newMode);
4532
+ if (this._workerPool) {
4533
+ await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
4534
+ }
4535
+ this.logger.info("tricache: encryption key rotated dynamically", { mode: this.enc.mode });
4536
+ }
4537
+ /** Close Redis connections and stop all background timers. */
4538
+ async destroy() {
4539
+ this._destroyed = true;
4540
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4541
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4542
+ if (this.oomInterval) clearInterval(this.oomInterval);
4543
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
4544
+ if (this._shutdownHandler) {
4545
+ process.off("SIGTERM", this._shutdownHandler);
4546
+ process.off("SIGINT", this._shutdownHandler);
4547
+ this._shutdownHandler = null;
4548
+ }
4549
+ if (this._workerPool) {
4550
+ await this._workerPool.destroy();
4551
+ this._workerPool = null;
4552
+ }
4553
+ if (this.subClient) {
4554
+ try {
4555
+ this.subClient.disconnect();
4556
+ } catch {
4557
+ }
4558
+ this.subClient = null;
4559
+ }
4560
+ if (this.streamClient) {
4561
+ try {
4562
+ this.streamClient.disconnect();
4563
+ } catch {
4564
+ }
4565
+ this.streamClient = null;
4566
+ }
4567
+ if (this.redis) {
4568
+ try {
4569
+ await this.redis.disconnect();
4570
+ } catch {
4571
+ }
4572
+ this.redis = null;
4573
+ }
4574
+ if (!this._diskDisabled) this.disk.close();
4575
+ }
4576
+ };
4577
+
4578
+ export {
4579
+ WasmBloomFilter,
4580
+ SmartMemoryCache,
4581
+ DiskTier,
4582
+ CacheService
4583
+ };