tricache 0.6.0 → 0.6.2

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 (42) hide show
  1. package/README.md +119 -0
  2. package/dist/chunk-F24NEZGQ.js +342 -0
  3. package/dist/index.cjs +494 -164
  4. package/dist/index.d.cts +125 -0
  5. package/dist/index.d.ts +1552 -18
  6. package/dist/index.js +3524 -25
  7. package/dist/serialize-worker.cjs +366 -0
  8. package/dist/serialize-worker.d.cts +2 -0
  9. package/dist/serialize-worker.d.ts +2 -0
  10. package/dist/serialize-worker.js +35 -0
  11. package/package.json +5 -5
  12. package/src/cache-service.ts +310 -93
  13. package/src/serialize-worker.ts +56 -0
  14. package/src/smart-memory-cache.ts +42 -1
  15. package/src/types.ts +99 -1
  16. package/src/worker-pool.ts +190 -0
  17. package/dist/cache-service.d.ts +0 -419
  18. package/dist/cache-service.d.ts.map +0 -1
  19. package/dist/cache-service.js +0 -1788
  20. package/dist/cache-service.js.map +0 -1
  21. package/dist/disk-tier.d.ts +0 -150
  22. package/dist/disk-tier.d.ts.map +0 -1
  23. package/dist/disk-tier.js +0 -808
  24. package/dist/disk-tier.js.map +0 -1
  25. package/dist/encryption.d.ts +0 -90
  26. package/dist/encryption.d.ts.map +0 -1
  27. package/dist/encryption.js +0 -393
  28. package/dist/encryption.js.map +0 -1
  29. package/dist/index.d.ts.map +0 -1
  30. package/dist/index.js.map +0 -1
  31. package/dist/smart-memory-cache.d.ts +0 -208
  32. package/dist/smart-memory-cache.d.ts.map +0 -1
  33. package/dist/smart-memory-cache.js +0 -933
  34. package/dist/smart-memory-cache.js.map +0 -1
  35. package/dist/types.d.ts +0 -537
  36. package/dist/types.d.ts.map +0 -1
  37. package/dist/types.js +0 -20
  38. package/dist/types.js.map +0 -1
  39. package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
  40. package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
  41. package/dist/wasm/bloom-filter-wasm.js +0 -83
  42. package/dist/wasm/bloom-filter-wasm.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,25 +1,3524 @@
1
- /**
2
- * tricache — three-tier cache for Node.js
3
- *
4
- * L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
5
- *
6
- * Quick start:
7
- * import { CacheService, CachePriority } from 'tricache';
8
- *
9
- * const cache = CacheService.create({ redisHost: 'localhost' });
10
- *
11
- * const user = await cache.get(
12
- * `user:${userId}`,
13
- * () => db.users.findById(userId),
14
- * 300, // 5-minute TTL
15
- * );
16
- *
17
- * await cache.delete(`user:${userId}`);
18
- */
19
- export { CacheService } from './cache-service';
20
- export { CacheEncryption } from './encryption';
21
- export { SmartMemoryCache } from './smart-memory-cache';
22
- export { DiskTier } from './disk-tier';
23
- export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
24
- export { CachePriority, consoleLogger, } from './types';
25
- //# sourceMappingURL=index.js.map
1
+ import {
2
+ CacheEncryption,
3
+ __require
4
+ } from "./chunk-F24NEZGQ.js";
5
+
6
+ // src/cache-service.ts
7
+ import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
8
+ import { pack as pack3, unpack as unpack3 } from "msgpackr";
9
+ import crypto2 from "crypto";
10
+ import os from "os";
11
+
12
+ // src/worker-pool.ts
13
+ import { Worker } from "worker_threads";
14
+ import { fileURLToPath } from "url";
15
+ import { dirname, join } from "path";
16
+ import { existsSync } from "fs";
17
+ var _workerFile;
18
+ var _workerExecArgv = [];
19
+ try {
20
+ const dir = dirname(fileURLToPath(import.meta.url));
21
+ const jsPath = join(dir, "serialize-worker.js");
22
+ const tsPath = join(dir, "serialize-worker.ts");
23
+ if (existsSync(jsPath)) {
24
+ _workerFile = jsPath;
25
+ } else if (existsSync(tsPath)) {
26
+ _workerFile = tsPath;
27
+ _workerExecArgv = ["--import", "tsx"];
28
+ } else {
29
+ _workerFile = jsPath;
30
+ }
31
+ } catch {
32
+ _workerFile = join(__dirname, "serialize-worker.js");
33
+ }
34
+ var WorkerPool = class {
35
+ workers = [];
36
+ pending = [];
37
+ _nextId = 0;
38
+ _robin = 0;
39
+ _available = false;
40
+ constructor(opts) {
41
+ const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
42
+ const workerData = {
43
+ keyBase64: opts.keyBase64,
44
+ mode: opts.mode,
45
+ prevKeyBase64: opts.prevKeyBase64 ?? "",
46
+ prevMode: opts.prevMode
47
+ };
48
+ try {
49
+ for (let i = 0; i < size; i++) {
50
+ const worker = new Worker(_workerFile, {
51
+ workerData,
52
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
53
+ });
54
+ const pending = /* @__PURE__ */ new Map();
55
+ worker.on("message", (msg) => {
56
+ const entry = pending.get(msg.id);
57
+ if (!entry) return;
58
+ pending.delete(msg.id);
59
+ if (pending.size === 0) worker.unref();
60
+ if (msg.error !== void 0) {
61
+ entry.reject(new Error(msg.error));
62
+ } else {
63
+ entry.resolve(msg.result);
64
+ }
65
+ });
66
+ worker.on("error", (err) => {
67
+ for (const [, entry] of pending) entry.reject(err);
68
+ pending.clear();
69
+ worker.unref();
70
+ });
71
+ worker.unref();
72
+ this.workers.push(worker);
73
+ this.pending.push(pending);
74
+ }
75
+ this._available = true;
76
+ } catch {
77
+ this._destroy();
78
+ }
79
+ }
80
+ get isAvailable() {
81
+ return this._available;
82
+ }
83
+ /** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
84
+ encrypt(payload) {
85
+ return this._dispatch("encrypt", payload);
86
+ }
87
+ /** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
88
+ decrypt(payload) {
89
+ return this._dispatch("decrypt", payload);
90
+ }
91
+ _dispatch(type, payload) {
92
+ const id = this._nextId++;
93
+ const idx = this._robin;
94
+ const worker = this.workers[idx];
95
+ const pending = this.pending[idx];
96
+ this._robin = (this._robin + 1) % this.workers.length;
97
+ return new Promise((resolve, reject) => {
98
+ pending.set(id, { resolve, reject });
99
+ worker.ref();
100
+ worker.postMessage({ id, type, payload });
101
+ });
102
+ }
103
+ /** Terminate all worker threads. In-flight promises are rejected. */
104
+ async destroy() {
105
+ this._available = false;
106
+ this._destroy();
107
+ }
108
+ _destroy() {
109
+ for (let i = 0; i < this.workers.length; i++) {
110
+ for (const [, entry] of this.pending[i] ?? []) {
111
+ entry.reject(new Error("WorkerPool destroyed"));
112
+ }
113
+ this.pending[i]?.clear();
114
+ this.workers[i]?.terminate().catch(() => {
115
+ });
116
+ }
117
+ }
118
+ };
119
+ function availableCpus() {
120
+ try {
121
+ const os2 = __require("os");
122
+ return os2.availableParallelism?.() ?? os2.cpus().length;
123
+ } catch {
124
+ return 2;
125
+ }
126
+ }
127
+
128
+ // src/cache-service.ts
129
+ import v8 from "v8";
130
+ import fs2 from "fs";
131
+ import path2 from "path";
132
+
133
+ // src/types.ts
134
+ var consoleLogger = {
135
+ debug: (msg, meta) => {
136
+ },
137
+ info: (msg, meta) => console.info("[tricache]", msg, meta ?? ""),
138
+ warn: (msg, meta) => console.warn("[tricache]", msg, meta ?? ""),
139
+ error: (msg, meta, err) => console.error("[tricache]", msg, meta ?? "", err ?? "")
140
+ };
141
+ var CachePriority = /* @__PURE__ */ ((CachePriority2) => {
142
+ CachePriority2[CachePriority2["LOW"] = 1] = "LOW";
143
+ CachePriority2[CachePriority2["NORMAL"] = 2] = "NORMAL";
144
+ CachePriority2[CachePriority2["HIGH"] = 3] = "HIGH";
145
+ CachePriority2[CachePriority2["CRITICAL"] = 4] = "CRITICAL";
146
+ return CachePriority2;
147
+ })(CachePriority || {});
148
+
149
+ // src/smart-memory-cache.ts
150
+ import { pack, unpack } from "msgpackr";
151
+
152
+ // src/wasm/bloom-filter-wasm.ts
153
+ var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
154
+ var KEY_STAGING_OFFSET = 2e4;
155
+ var MAX_KEY_BYTES = 512;
156
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
157
+ var WasmBloomFilter = class {
158
+ exports;
159
+ mem;
160
+ encoder = new TextEncoder();
161
+ numBits = 1e5;
162
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
163
+ _maxCapacity;
164
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
165
+ _insertionCount = 0;
166
+ constructor() {
167
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
168
+ this.exports = instance.exports;
169
+ this.mem = new Uint8Array(this.exports.memory.buffer);
170
+ const k = 7, p = 0.01;
171
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
172
+ }
173
+ writeKey(key) {
174
+ if (key.length === 0) return 0;
175
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
176
+ return this.encoder.encodeInto(key, target).written;
177
+ }
178
+ add(key) {
179
+ const len = this.writeKey(key);
180
+ if (len === 0) return;
181
+ this.exports.add(KEY_STAGING_OFFSET, len);
182
+ this._insertionCount++;
183
+ }
184
+ mightContain(key) {
185
+ const len = this.writeKey(key);
186
+ if (len === 0) return true;
187
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
188
+ }
189
+ reset() {
190
+ this.exports.reset();
191
+ this._insertionCount = 0;
192
+ }
193
+ rebuild(keys) {
194
+ this.reset();
195
+ for (const key of keys) this.add(key);
196
+ }
197
+ get stats() {
198
+ const bitsSet = this.exports.countBits();
199
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
200
+ }
201
+ /** Number of add() calls since last reset/rebuild. */
202
+ get insertions() {
203
+ return this._insertionCount;
204
+ }
205
+ /**
206
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
207
+ * Exact formula for k=7 hash rounds, m=100 000 bits:
208
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
209
+ */
210
+ get maxCapacity() {
211
+ return this._maxCapacity;
212
+ }
213
+ };
214
+
215
+ // src/smart-memory-cache.ts
216
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
217
+ var EVICTION_BATCH_PERCENT = 0.2;
218
+ var EVICTION_SAMPLE = 16;
219
+ var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
220
+ var JsBloomFilter = class {
221
+ bits;
222
+ numBits;
223
+ k;
224
+ /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
225
+ _maxCapacity;
226
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
227
+ _insertionCount = 0;
228
+ constructor(numBits = 1e5, k = 7) {
229
+ this.numBits = numBits;
230
+ this.k = k;
231
+ this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
232
+ const p = 0.01;
233
+ this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
234
+ }
235
+ fnv1a32(s) {
236
+ let h = 2166136261;
237
+ for (let i = 0; i < s.length; i++) {
238
+ h ^= s.charCodeAt(i);
239
+ h = Math.imul(h, 16777619) >>> 0;
240
+ }
241
+ return h >>> 0;
242
+ }
243
+ djb2(s) {
244
+ let h = 5381;
245
+ for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) >>> 0;
246
+ return h >>> 0;
247
+ }
248
+ setBit(i) {
249
+ this.bits[i >>> 3] |= 1 << (i & 7);
250
+ }
251
+ getBit(i) {
252
+ return (this.bits[i >>> 3] & 1 << (i & 7)) !== 0;
253
+ }
254
+ add(key) {
255
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
256
+ for (let i = 0; i < this.k; i++) this.setBit((h1 + i * h2 >>> 0) % this.numBits);
257
+ this._insertionCount++;
258
+ }
259
+ mightContain(key) {
260
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
261
+ for (let i = 0; i < this.k; i++) if (!this.getBit((h1 + i * h2 >>> 0) % this.numBits)) return false;
262
+ return true;
263
+ }
264
+ reset() {
265
+ this.bits.fill(0);
266
+ this._insertionCount = 0;
267
+ }
268
+ rebuild(keys) {
269
+ this.bits.fill(0);
270
+ this._insertionCount = 0;
271
+ for (const k of keys) this.add(k);
272
+ }
273
+ /** Number of add() calls since last reset/rebuild. */
274
+ get insertions() {
275
+ return this._insertionCount;
276
+ }
277
+ /**
278
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
279
+ * Exact formula for the configured k and target p=1 %:
280
+ * n_max = -m * ln(1 - p^(1/k)) / k
281
+ */
282
+ get maxCapacity() {
283
+ return this._maxCapacity;
284
+ }
285
+ get stats() {
286
+ let bitsSet = 0;
287
+ for (const byte of this.bits) {
288
+ let b = byte;
289
+ while (b) {
290
+ bitsSet++;
291
+ b &= b - 1;
292
+ }
293
+ }
294
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
295
+ }
296
+ };
297
+ function createBloomFilter(logger, maxEntries) {
298
+ const LN2_SQ = Math.LN2 * Math.LN2;
299
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
300
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
301
+ try {
302
+ const wasm = new WasmBloomFilter();
303
+ if (wasm.maxCapacity >= maxEntries) {
304
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
305
+ return wasm;
306
+ }
307
+ logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
308
+ wasmCapacity: wasm.maxCapacity,
309
+ maxEntries,
310
+ optimalBits
311
+ });
312
+ } catch (err) {
313
+ logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
314
+ }
315
+ return new JsBloomFilter(optimalBits, optimalK);
316
+ }
317
+ var SKETCH_ROWS = 4;
318
+ var SKETCH_WIDTH = 512;
319
+ var SKETCH_MASK = SKETCH_WIDTH - 1;
320
+ var SKETCH_DECAY_THRESHOLD = 1e5;
321
+ var CountMinSketch = class {
322
+ table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
323
+ inserts = 0;
324
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
325
+ fnv32(key) {
326
+ let h = 2166136261;
327
+ for (let i = 0; i < key.length; i++) {
328
+ h ^= key.charCodeAt(i);
329
+ h = Math.imul(h, 16777619) >>> 0;
330
+ }
331
+ return h;
332
+ }
333
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
334
+ increment(key) {
335
+ const h = this.fnv32(key);
336
+ const h1 = (h ^ h >>> 16) >>> 0;
337
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
338
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
339
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
340
+ const t = this.table;
341
+ const i0 = h1 & SKETCH_MASK;
342
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
343
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
344
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
345
+ if (t[i0] < 65535) t[i0]++;
346
+ if (t[i1] < 65535) t[i1]++;
347
+ if (t[i2] < 65535) t[i2]++;
348
+ if (t[i3] < 65535) t[i3]++;
349
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
350
+ }
351
+ /** Minimum-across-rows frequency estimate. */
352
+ estimate(key) {
353
+ const h = this.fnv32(key);
354
+ const h1 = (h ^ h >>> 16) >>> 0;
355
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
356
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
357
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
358
+ const t = this.table;
359
+ return Math.min(
360
+ t[h1 & SKETCH_MASK],
361
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
362
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
363
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
364
+ );
365
+ }
366
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
367
+ decay() {
368
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
369
+ this.inserts = 0;
370
+ }
371
+ };
372
+ function globMatchParts(parts, first, last, key) {
373
+ if (first.length > 0 && !key.startsWith(first)) return false;
374
+ if (last.length > 0 && !key.endsWith(last)) return false;
375
+ if (first.length + last.length > key.length) return false;
376
+ let pos = first.length;
377
+ const end = key.length - last.length;
378
+ for (let i = 1; i < parts.length - 1; i++) {
379
+ const seg = parts[i];
380
+ if (seg.length === 0) continue;
381
+ const idx = key.indexOf(seg, pos);
382
+ if (idx === -1 || idx + seg.length > end) return false;
383
+ pos = idx + seg.length;
384
+ }
385
+ return true;
386
+ }
387
+ var SmartMemoryCache = class {
388
+ cache = /* @__PURE__ */ new Map();
389
+ opts;
390
+ bloom;
391
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
392
+ categoryPrefixes;
393
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
394
+ sketch = new CountMinSketch();
395
+ totalSize = 0;
396
+ categoryCount = /* @__PURE__ */ new Map();
397
+ categorySize = /* @__PURE__ */ new Map();
398
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
399
+ categoryKeys = /* @__PURE__ */ new Map();
400
+ // ── Observability counters ──────────────────────────────────────────────────────
401
+ bloomChecks = 0;
402
+ bloomFalsePos = 0;
403
+ compressions = 0;
404
+ categoryHits = /* @__PURE__ */ new Map();
405
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
406
+ _bloomDirtyCount = 0;
407
+ /**
408
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
409
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
410
+ * that is overwritten in-place rather than replaced with a new object literal.
411
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
412
+ * any other code can observe the pool state.
413
+ */
414
+ _evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
415
+ _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
416
+ constructor(opts, existing) {
417
+ this.opts = opts;
418
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
419
+ this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
420
+ if (existing) {
421
+ for (const [k, v] of existing) this.cache.set(k, v);
422
+ this.recalculateStats();
423
+ for (const key of this.cache.keys()) this.bloom.add(key);
424
+ }
425
+ }
426
+ // ── Internal helpers ──────────────────────────────────────────────────────
427
+ recalculateStats() {
428
+ this.totalSize = 0;
429
+ this.categoryCount.clear();
430
+ this.categorySize.clear();
431
+ this.categoryKeys.clear();
432
+ for (const [key, entry] of this.cache) {
433
+ this.totalSize += entry.size;
434
+ const cat = this.getCategory(key);
435
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
436
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
437
+ let ks = this.categoryKeys.get(cat);
438
+ if (!ks) {
439
+ ks = /* @__PURE__ */ new Set();
440
+ this.categoryKeys.set(cat, ks);
441
+ }
442
+ ks.add(key);
443
+ }
444
+ }
445
+ getCategory(key) {
446
+ for (const prefix of this.categoryPrefixes) {
447
+ if (key.startsWith(prefix)) return prefix;
448
+ }
449
+ return "default";
450
+ }
451
+ getCategoryLimit(cat) {
452
+ return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
453
+ }
454
+ _delete(key, reason = "manual") {
455
+ const entry = this.cache.get(key);
456
+ if (!entry) return false;
457
+ const cat = this.getCategory(key);
458
+ this.totalSize -= entry.size;
459
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
460
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
461
+ this.categoryKeys.get(cat)?.delete(key);
462
+ this._bloomDirtyCount++;
463
+ const deleted = this.cache.delete(key);
464
+ if (deleted && this.opts.onEviction) {
465
+ try {
466
+ this.opts.onEviction(key, reason);
467
+ } catch {
468
+ }
469
+ }
470
+ return deleted;
471
+ }
472
+ ensureCapacity(category, neededSize) {
473
+ const lim = this.getCategoryLimit(category);
474
+ const catCnt = this.categoryCount.get(category) ?? 0;
475
+ const catSz = this.categorySize.get(category) ?? 0;
476
+ const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
477
+ const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
478
+ if (!catOvf && !glbOvf) {
479
+ const wm = this.opts.evictionWatermark ?? 0.9;
480
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
481
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
482
+ if (entryWatermark || byteWatermark) {
483
+ this.smartEvict(category, false);
484
+ }
485
+ return;
486
+ }
487
+ this.smartEvict(category, catOvf);
488
+ }
489
+ score(entry, catBonus, now, key) {
490
+ const age = now - entry.lastAccess;
491
+ const ttl = Math.max(0, entry.expiresAt - now);
492
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
493
+ return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
494
+ }
495
+ /**
496
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
497
+ * saturated the filter past its ~1 % FP capacity.
498
+ *
499
+ * Trigger: (insertions − live entries) > maxCapacity
500
+ *
501
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
502
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
503
+ * cache holds more entries than the filter's rated capacity — which would
504
+ * stall the write path entirely.
505
+ *
506
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
507
+ */
508
+ maybeRebuildBloom() {
509
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
510
+ if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
511
+ this.bloom.rebuild(this.cache.keys());
512
+ this._bloomDirtyCount = 0;
513
+ }
514
+ }
515
+ smartEvict(targetCat, catOvf) {
516
+ const now = Date.now();
517
+ const pool = this._evictPool;
518
+ const gPool = this._evictGPool;
519
+ let poolLen = 0;
520
+ if (catOvf) {
521
+ const catKeySet = this.categoryKeys.get(targetCat);
522
+ if (catKeySet) {
523
+ let catSeen = 0;
524
+ for (const key of catKeySet) {
525
+ const entry = this.cache.get(key);
526
+ if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
527
+ catSeen++;
528
+ const s = this.score(entry, 100, now, key);
529
+ if (poolLen < EVICT_COUNT) {
530
+ pool[poolLen].key = key;
531
+ pool[poolLen].score = s;
532
+ poolLen++;
533
+ } else {
534
+ const j = Math.floor(Math.random() * catSeen);
535
+ if (j < EVICT_COUNT) {
536
+ pool[j].key = key;
537
+ pool[j].score = s;
538
+ }
539
+ }
540
+ }
541
+ }
542
+ }
543
+ if (poolLen < EVICT_COUNT) {
544
+ const remaining = EVICTION_SAMPLE - poolLen;
545
+ let globalSeen = 0;
546
+ let gLen = 0;
547
+ for (const [key, entry] of this.cache) {
548
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
549
+ if (catOvf && this.getCategory(key) === targetCat) continue;
550
+ globalSeen++;
551
+ const s = this.score(entry, 0, now, key);
552
+ if (gLen < remaining) {
553
+ gPool[gLen].key = key;
554
+ gPool[gLen].score = s;
555
+ gLen++;
556
+ } else {
557
+ const j = Math.floor(Math.random() * globalSeen);
558
+ if (j < remaining) {
559
+ gPool[j].key = key;
560
+ gPool[j].score = s;
561
+ }
562
+ }
563
+ }
564
+ for (let i = 0; i < gLen; i++) {
565
+ pool[poolLen].key = gPool[i].key;
566
+ pool[poolLen].score = gPool[i].score;
567
+ poolLen++;
568
+ }
569
+ }
570
+ if (poolLen === 0) return;
571
+ for (let i = 1; i < poolLen; i++) {
572
+ const sk = pool[i].key, ss = pool[i].score;
573
+ let j = i - 1;
574
+ while (j >= 0 && pool[j].score > ss) {
575
+ pool[j + 1].key = pool[j].key;
576
+ pool[j + 1].score = pool[j].score;
577
+ j--;
578
+ }
579
+ pool[j + 1].key = sk;
580
+ pool[j + 1].score = ss;
581
+ }
582
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
583
+ for (let i = 0; i < toEvict; i++) {
584
+ const key = pool[i].key;
585
+ const entry = this.cache.get(key);
586
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
587
+ this._delete(key, "capacity");
588
+ }
589
+ }
590
+ // ── Public API ────────────────────────────────────────────────────────────
591
+ get(key) {
592
+ this.bloomChecks++;
593
+ if (!this.bloom.mightContain(key)) return null;
594
+ const entry = this.cache.get(key);
595
+ if (!entry) {
596
+ this.bloomFalsePos++;
597
+ return null;
598
+ }
599
+ const now = Date.now();
600
+ if (entry.expiresAt < now) {
601
+ this._delete(key, "ttl");
602
+ return null;
603
+ }
604
+ entry.hits++;
605
+ entry.lastAccess = now;
606
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
607
+ const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
608
+ _hit.value = value;
609
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
610
+ _hit.expiresAt = entry.expiresAt;
611
+ _hit.ttlMs = entry.ttlMs;
612
+ _hit.delta = entry.delta;
613
+ _hit.fetchedAt = now;
614
+ return _hit;
615
+ }
616
+ set(key, data, ttlMs, priority = 2, staleAt, delta) {
617
+ const packed = pack(data);
618
+ const size = packed.byteLength;
619
+ this.compressions++;
620
+ this.sketch.increment(key);
621
+ const cat = this.getCategory(key);
622
+ const lim = this.getCategoryLimit(cat);
623
+ if (size > lim.maxSizeBytes * 0.5) {
624
+ this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
625
+ return;
626
+ }
627
+ const existingEntry = this.cache.get(key);
628
+ if (existingEntry) {
629
+ this.totalSize -= existingEntry.size;
630
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
631
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
632
+ this.cache.delete(key);
633
+ }
634
+ this.ensureCapacity(cat, size);
635
+ const now = Date.now();
636
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
637
+ if (!existingEntry) this.bloom.add(key);
638
+ this.maybeRebuildBloom();
639
+ this.totalSize += size;
640
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
641
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
642
+ let ks = this.categoryKeys.get(cat);
643
+ if (!ks) {
644
+ ks = /* @__PURE__ */ new Set();
645
+ this.categoryKeys.set(cat, ks);
646
+ }
647
+ ks.add(key);
648
+ }
649
+ delete(key) {
650
+ const deleted = this._delete(key, "manual");
651
+ if (deleted) this.maybeRebuildBloom();
652
+ return deleted;
653
+ }
654
+ keysMatchingPattern(pattern) {
655
+ if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
656
+ if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
657
+ const prefix = pattern.slice(0, -1);
658
+ const catKeys = this.categoryKeys.get(prefix);
659
+ if (catKeys !== void 0) return Array.from(catKeys);
660
+ }
661
+ const firstStar = pattern.indexOf("*");
662
+ if (firstStar === pattern.lastIndexOf("*")) {
663
+ const prefix = pattern.slice(0, firstStar);
664
+ const suffix = pattern.slice(firstStar + 1);
665
+ const minLen = prefix.length + suffix.length;
666
+ const out2 = [];
667
+ for (const k of this.cache.keys()) {
668
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
669
+ }
670
+ return out2;
671
+ }
672
+ const parts = pattern.split("*");
673
+ const first = parts[0];
674
+ const last = parts[parts.length - 1];
675
+ const out = [];
676
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
677
+ return out;
678
+ }
679
+ deletePattern(pattern) {
680
+ let n = 0;
681
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
682
+ if (n > 0) this.maybeRebuildBloom();
683
+ return n;
684
+ }
685
+ /** Flush all entries, or only those whose key starts with `prefix`. */
686
+ clear(prefix) {
687
+ if (prefix) {
688
+ const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
689
+ return this.deletePattern(pattern);
690
+ }
691
+ const count = this.cache.size;
692
+ this.cache.clear();
693
+ this.totalSize = 0;
694
+ this.categoryCount.clear();
695
+ this.categorySize.clear();
696
+ this.categoryKeys.clear();
697
+ this.categoryHits.clear();
698
+ this.bloom.reset();
699
+ this._bloomDirtyCount = 0;
700
+ return count;
701
+ }
702
+ /**
703
+ * Evict entries that violate current category or global limits.
704
+ * Returns the number of entries evicted.
705
+ */
706
+ rebalance() {
707
+ const now = Date.now();
708
+ let evicted = 0;
709
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
710
+ const catKeys = this.categoryKeys.get(cat);
711
+ if (!catKeys || catKeys.size === 0) continue;
712
+ let catCnt = this.categoryCount.get(cat) ?? 0;
713
+ let catSz = this.categorySize.get(cat) ?? 0;
714
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
715
+ const candidates = [];
716
+ for (const key of catKeys) {
717
+ const entry = this.cache.get(key);
718
+ if (!entry) continue;
719
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
720
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
721
+ }
722
+ candidates.sort((a, b) => a.score - b.score);
723
+ for (const { key } of candidates) {
724
+ catCnt = this.categoryCount.get(cat) ?? 0;
725
+ catSz = this.categorySize.get(cat) ?? 0;
726
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
727
+ const entry = this.cache.get(key);
728
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
729
+ this._delete(key, "rebalance");
730
+ evicted++;
731
+ }
732
+ }
733
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
734
+ const before = this.cache.size;
735
+ this.smartEvict("default", false);
736
+ if (this.cache.size >= before) break;
737
+ evicted += before - this.cache.size;
738
+ }
739
+ if (evicted > 0) this.maybeRebuildBloom();
740
+ return evicted;
741
+ }
742
+ /**
743
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
744
+ * Only reflects L1 state — does not query Redis or disk.
745
+ */
746
+ ttl(key) {
747
+ const entry = this.cache.get(key);
748
+ if (!entry) return null;
749
+ const remaining = entry.expiresAt - Date.now();
750
+ return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
751
+ }
752
+ /**
753
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
754
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
755
+ * exceeds the configured threshold.
756
+ *
757
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
758
+ * @returns Number of entries evicted
759
+ */
760
+ evictPercentage(pct) {
761
+ if (pct <= 0 || this.cache.size === 0) return 0;
762
+ const now = Date.now();
763
+ const candidates = [];
764
+ for (const [key, entry] of this.cache) {
765
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
766
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
767
+ }
768
+ candidates.sort((a, b) => a.score - b.score);
769
+ const count = Math.max(1, Math.ceil(candidates.length * pct));
770
+ let evicted = 0;
771
+ for (const { key } of candidates.slice(0, count)) {
772
+ const entry = this.cache.get(key);
773
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
774
+ this._delete(key, "oom");
775
+ evicted++;
776
+ }
777
+ return evicted;
778
+ }
779
+ cleanup() {
780
+ const now = Date.now();
781
+ let cleaned = 0;
782
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
783
+ this._delete(key, "ttl");
784
+ cleaned++;
785
+ }
786
+ if (cleaned > 0) {
787
+ this.bloom.rebuild(this.cache.keys());
788
+ this._bloomDirtyCount = 0;
789
+ }
790
+ return cleaned;
791
+ }
792
+ /**
793
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
794
+ *
795
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
796
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
797
+ * Entries written before the disconnect started may have been invalidated by
798
+ * peers while the backplane was down; evicting them forces a controlled
799
+ * cold-start re-fetch from L2 rather than serving silently stale data.
800
+ *
801
+ * Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
802
+ * Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
803
+ * conservatively.
804
+ *
805
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
806
+ * this time are evicted.
807
+ * @returns Number of entries evicted.
808
+ */
809
+ evictSetBefore(cutoffMs) {
810
+ let evicted = 0;
811
+ for (const [key, entry] of this.cache) {
812
+ if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
813
+ const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
814
+ if (setAt < cutoffMs) {
815
+ this._delete(key, "manual");
816
+ evicted++;
817
+ }
818
+ }
819
+ if (evicted > 0) {
820
+ this.bloom.rebuild(this.cache.keys());
821
+ this._bloomDirtyCount = 0;
822
+ }
823
+ return evicted;
824
+ }
825
+ exportEntries(forbiddenPrefixes) {
826
+ const now = Date.now();
827
+ const out = [];
828
+ for (const [key, entry] of this.cache) {
829
+ if (entry.expiresAt <= now) continue;
830
+ if (entry.priority === 4) continue;
831
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
832
+ out.push({ key, entry: { ...entry } });
833
+ }
834
+ return out;
835
+ }
836
+ importEntries(entries, forbiddenPrefixes) {
837
+ const now = Date.now();
838
+ let loaded = 0;
839
+ for (const { key, entry } of entries) {
840
+ if (entry.expiresAt <= now) continue;
841
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
842
+ if (this.cache.has(key)) continue;
843
+ const rawData = entry.data;
844
+ const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
845
+ const value = unpack(data);
846
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
847
+ this.bloom.add(key);
848
+ loaded++;
849
+ }
850
+ this.recalculateStats();
851
+ return loaded;
852
+ }
853
+ // ── Iterators ─────────────────────────────────────────────────────────────
854
+ /**
855
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
856
+ * Expired entries that are still in the Map (awaiting background cleanup)
857
+ * are silently skipped.
858
+ */
859
+ *liveEntries() {
860
+ const now = Date.now();
861
+ for (const [key, entry] of this.cache) {
862
+ if (entry.expiresAt > now) yield [key, entry];
863
+ }
864
+ }
865
+ /**
866
+ * Non-generator bulk scan over all live entries.
867
+ *
868
+ * Faster than the generator-based iterators for bulk operations because:
869
+ * - No generator state-machine overhead (no yield/resume suspend points).
870
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
871
+ * - The same Map call-site is used by a single plain `for` loop instead of being
872
+ * shared across three competing generator functions, giving V8's IC a cleaner
873
+ * monomorphic profile for this path.
874
+ *
875
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
876
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
877
+ * key, avoiding the allocation entirely for callers that don't.
878
+ *
879
+ * @param fn Called once per live entry.
880
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
881
+ * Pass 0 when no namespace is configured.
882
+ */
883
+ scan(fn, prefixLen) {
884
+ const now = Date.now();
885
+ for (const [key, entry] of this.cache) {
886
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
887
+ }
888
+ }
889
+ /**
890
+ * Yields only the keys of live entries — no intermediate tuple allocation.
891
+ * Use this instead of liveEntries() when you only need keys.
892
+ */
893
+ *liveKeys() {
894
+ const now = Date.now();
895
+ for (const [key, entry] of this.cache) {
896
+ if (entry.expiresAt > now) yield key;
897
+ }
898
+ }
899
+ /**
900
+ * Yields only the resolved values of live entries.
901
+ * Iterates Map.values() so the key is never loaded into the yielded path.
902
+ * Returns the cached deserialized object when available (entry.value), otherwise
903
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
904
+ */
905
+ *liveValues() {
906
+ const now = Date.now();
907
+ for (const entry of this.cache.values()) {
908
+ if (entry.expiresAt > now)
909
+ yield entry.value !== void 0 ? entry.value : entry.data;
910
+ }
911
+ }
912
+ // ── Stats ─────────────────────────────────────────────────────────────────
913
+ get size() {
914
+ return this.cache.size;
915
+ }
916
+ get memoryUsage() {
917
+ return this.totalSize;
918
+ }
919
+ getStats() {
920
+ const categories = {};
921
+ for (const [cat, cnt] of this.categoryCount) {
922
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
923
+ }
924
+ return {
925
+ entries: this.cache.size,
926
+ sizeBytes: this.totalSize,
927
+ sizeKB: Math.round(this.totalSize / 1024),
928
+ categories,
929
+ bloom: {
930
+ checks: this.bloomChecks,
931
+ falsePositives: this.bloomFalsePos
932
+ },
933
+ compression: {
934
+ compressed: this.compressions,
935
+ uncompressed: 0,
936
+ // all entries are now msgpackr-packed
937
+ bytesSaved: 0
938
+ // no longer tracked (unified format removes the split path)
939
+ }
940
+ };
941
+ }
942
+ /**
943
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
944
+ * Does NOT count as a hit or perform SWR logic.
945
+ */
946
+ getEntry(key) {
947
+ const entry = this.cache.get(key);
948
+ if (!entry) return void 0;
949
+ if (entry.expiresAt <= Date.now()) return void 0;
950
+ return entry;
951
+ }
952
+ /**
953
+ * Return true if the key exists in L1 and has not expired.
954
+ * Uses the bloom filter as a fast negative check.
955
+ */
956
+ has(key) {
957
+ if (!this.bloom.mightContain(key)) return false;
958
+ const entry = this.cache.get(key);
959
+ if (!entry) return false;
960
+ if (entry.expiresAt <= Date.now()) {
961
+ this._delete(key, "ttl");
962
+ return false;
963
+ }
964
+ return true;
965
+ }
966
+ /**
967
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
968
+ * @param newTtlMs - New TTL from now, in milliseconds.
969
+ */
970
+ touch(key, newTtlMs) {
971
+ const entry = this.cache.get(key);
972
+ if (!entry) return false;
973
+ const now = Date.now();
974
+ if (entry.expiresAt <= now) {
975
+ this._delete(key, "ttl");
976
+ return false;
977
+ }
978
+ entry.expiresAt = now + newTtlMs;
979
+ return true;
980
+ }
981
+ /**
982
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
983
+ * Returns `false` if the key is absent or already expired.
984
+ */
985
+ bumpExpiry(key, additionalMs) {
986
+ const entry = this.cache.get(key);
987
+ if (!entry) return false;
988
+ if (entry.expiresAt <= Date.now()) return false;
989
+ entry.expiresAt += additionalMs;
990
+ return true;
991
+ }
992
+ bloomMightContain(key) {
993
+ return this.bloom.mightContain(key);
994
+ }
995
+ bloomStats() {
996
+ return this.bloom.stats;
997
+ }
998
+ /**
999
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1000
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1001
+ * Useful for diagnosing which keys are driving cache pressure.
1002
+ *
1003
+ * @param n - Maximum number of entries to return. Default: 10.
1004
+ */
1005
+ hotKeys(n) {
1006
+ const now = Date.now();
1007
+ const out = [];
1008
+ for (const [key, entry] of this.cache) {
1009
+ if (entry.expiresAt <= now) continue;
1010
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1011
+ }
1012
+ out.sort((a, b) => b.hits - a.hits);
1013
+ return out.slice(0, n);
1014
+ }
1015
+ };
1016
+
1017
+ // src/disk-tier.ts
1018
+ import fs from "fs";
1019
+ import path from "path";
1020
+ import crypto from "crypto";
1021
+ import { createRequire } from "module";
1022
+ import { pack as pack2, unpack as unpack2 } from "msgpackr";
1023
+ var _SqliteDB = null;
1024
+ try {
1025
+ const _req = createRequire(import.meta.url);
1026
+ _SqliteDB = _req("node:sqlite").DatabaseSync;
1027
+ } catch {
1028
+ }
1029
+ var AES_ALGO = "aes-256-gcm";
1030
+ var IV_BYTES = 12;
1031
+ var TAG_BYTES = 16;
1032
+ var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1033
+ var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1034
+ var V2_HEADER_LEN = 16;
1035
+ var DISK_TIER_VERSION = 1;
1036
+ var DiskTier = class {
1037
+ opts;
1038
+ dirReady = false;
1039
+ diskUsageBytes = 0;
1040
+ usageCounted = false;
1041
+ fileCount = 0;
1042
+ // maintained in-memory; avoids walkCacheFiles() in stats
1043
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1044
+ _nextJanitorBucket = 0;
1045
+ // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1046
+ _db = null;
1047
+ _stmtInsert = null;
1048
+ // INSERT OR REPLACE
1049
+ _stmtSelect = null;
1050
+ // SELECT by key_hash
1051
+ _stmtDelete = null;
1052
+ // DELETE by key_hash
1053
+ _stmtExpire = null;
1054
+ // SELECT expired rows
1055
+ _stmtDelExp = null;
1056
+ // DELETE expired rows
1057
+ _stmtStats = null;
1058
+ // COUNT + SUM(size)
1059
+ constructor(opts) {
1060
+ this.opts = opts;
1061
+ }
1062
+ // ── Helpers ───────────────────────────────────────────────────────────────
1063
+ ensureDir() {
1064
+ if (this.dirReady) return;
1065
+ try {
1066
+ fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
1067
+ this.dirReady = true;
1068
+ this._initSqlite();
1069
+ } catch (err) {
1070
+ this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Initialise the SQLite metadata index. Called once after the cache directory
1075
+ * is confirmed to exist. On any failure the instance silently falls back to
1076
+ * file-only mode — all public methods handle `this._db === null`.
1077
+ *
1078
+ * Schema:
1079
+ * meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
1080
+ * idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
1081
+ *
1082
+ * WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
1083
+ * most one WAL frame — acceptable data loss for an L1.5 spill store).
1084
+ */
1085
+ _initSqlite() {
1086
+ if (!_SqliteDB) return;
1087
+ try {
1088
+ const dbPath = path.join(this.opts.dir, "meta.db");
1089
+ this._db = new _SqliteDB(dbPath);
1090
+ this._db.exec(`
1091
+ PRAGMA journal_mode = WAL;
1092
+ PRAGMA synchronous = NORMAL;
1093
+ PRAGMA temp_store = MEMORY;
1094
+ CREATE TABLE IF NOT EXISTS meta (
1095
+ key_hash TEXT PRIMARY KEY,
1096
+ file_path TEXT NOT NULL,
1097
+ expires_at INTEGER NOT NULL,
1098
+ size INTEGER NOT NULL DEFAULT 0
1099
+ );
1100
+ CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
1101
+ `);
1102
+ this._stmtInsert = this._db.prepare(
1103
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
1104
+ );
1105
+ this._stmtSelect = this._db.prepare(
1106
+ "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
1107
+ );
1108
+ this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
1109
+ this._stmtExpire = this._db.prepare(
1110
+ "SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
1111
+ );
1112
+ this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
1113
+ this._stmtStats = this._db.prepare(
1114
+ "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1115
+ );
1116
+ const row = this._stmtStats.get();
1117
+ this.fileCount = row.cnt;
1118
+ this.diskUsageBytes = row.bytes;
1119
+ this.usageCounted = true;
1120
+ this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1121
+ } catch (err) {
1122
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1123
+ this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1124
+ error: err.message
1125
+ });
1126
+ }
1127
+ }
1128
+ ensureUsageCounted() {
1129
+ if (this.usageCounted) return;
1130
+ this.usageCounted = true;
1131
+ if (this._db) return;
1132
+ try {
1133
+ this.ensureDir();
1134
+ let total = 0;
1135
+ const files = this.walkCacheFiles();
1136
+ this.fileCount = files.length;
1137
+ for (const filePath of files) {
1138
+ try {
1139
+ total += fs.statSync(filePath).size;
1140
+ } catch {
1141
+ }
1142
+ }
1143
+ this.diskUsageBytes = total;
1144
+ } catch {
1145
+ this.diskUsageBytes = 0;
1146
+ this.fileCount = 0;
1147
+ }
1148
+ }
1149
+ /**
1150
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1151
+ * Kept separate from path construction so callers can find files by prefix
1152
+ * without knowing which filename generation was used when the file was written.
1153
+ */
1154
+ keyToHash(key) {
1155
+ return crypto.createHash("sha256").update(key, "utf8").digest("hex");
1156
+ }
1157
+ /**
1158
+ * Build the write path for a NEW file (V3 generation).
1159
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1160
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1161
+ *
1162
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1163
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1164
+ *
1165
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1166
+ */
1167
+ hashToWritePath(hash, expiresAt) {
1168
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
1169
+ }
1170
+ /**
1171
+ * Find the on-disk file for a key hash, handling all filename generations:
1172
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1173
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1174
+ * Returns null when the bucket dir does not exist or the key is absent.
1175
+ */
1176
+ findFilePath(hash) {
1177
+ const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
1178
+ let files;
1179
+ try {
1180
+ files = fs.readdirSync(bucketPath);
1181
+ } catch {
1182
+ return null;
1183
+ }
1184
+ let match;
1185
+ for (const f of files) {
1186
+ if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1187
+ }
1188
+ if (!match) return null;
1189
+ return path.join(bucketPath, match);
1190
+ }
1191
+ /**
1192
+ * Recursively list all cache file paths across the 2-level sharded subdirs.
1193
+ * Top-level entries that are not directories are skipped (e.g. stale flat
1194
+ * files written by older versions).
1195
+ */
1196
+ walkCacheFiles() {
1197
+ const results = [];
1198
+ let topEntries;
1199
+ try {
1200
+ topEntries = fs.readdirSync(this.opts.dir);
1201
+ } catch {
1202
+ return results;
1203
+ }
1204
+ for (const top of topEntries) {
1205
+ const topPath = path.join(this.opts.dir, top);
1206
+ try {
1207
+ if (!fs.statSync(topPath).isDirectory()) continue;
1208
+ for (const file of fs.readdirSync(topPath)) {
1209
+ results.push(path.join(topPath, file));
1210
+ }
1211
+ } catch {
1212
+ }
1213
+ }
1214
+ return results;
1215
+ }
1216
+ isForbidden(key) {
1217
+ return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
1218
+ }
1219
+ encrypt(data) {
1220
+ const key = this.opts.encryptionKey;
1221
+ if (!key) return data;
1222
+ const iv = crypto.randomBytes(IV_BYTES);
1223
+ const c = crypto.createCipheriv(AES_ALGO, key, iv);
1224
+ const enc = Buffer.concat([c.update(data), c.final()]);
1225
+ const tag = c.getAuthTag();
1226
+ return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
1227
+ }
1228
+ decrypt(data) {
1229
+ const mLen = DISK_MAGIC.length;
1230
+ if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
1231
+ const key = this.opts.encryptionKey;
1232
+ if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
1233
+ const iv = data.subarray(mLen, mLen + IV_BYTES);
1234
+ const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
1235
+ const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
1236
+ const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1237
+ d.setAuthTag(tag);
1238
+ return Buffer.concat([d.update(ct), d.final()]);
1239
+ }
1240
+ /**
1241
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1242
+ * the outer 16-byte header alongside the plaintext expiresAt).
1243
+ * Returns the buffer unchanged when no encryption key is configured.
1244
+ */
1245
+ encryptV2(data) {
1246
+ const key = this.opts.encryptionKey;
1247
+ if (!key) return data;
1248
+ const iv = crypto.randomBytes(IV_BYTES);
1249
+ const c = crypto.createCipheriv(AES_ALGO, key, iv);
1250
+ const enc = Buffer.concat([c.update(data), c.final()]);
1251
+ const tag = c.getAuthTag();
1252
+ return Buffer.concat([iv, tag, enc]);
1253
+ }
1254
+ /**
1255
+ * V2 decryption — inner payload after stripping the 16-byte header.
1256
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1257
+ * without a key the payload is raw msgpack.
1258
+ */
1259
+ decryptV2(inner) {
1260
+ const key = this.opts.encryptionKey;
1261
+ if (!key) return inner;
1262
+ const iv = inner.subarray(0, IV_BYTES);
1263
+ const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
1264
+ const ct = inner.subarray(IV_BYTES + TAG_BYTES);
1265
+ const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1266
+ d.setAuthTag(tag);
1267
+ return Buffer.concat([d.update(ct), d.final()]);
1268
+ }
1269
+ // ── Public API ────────────────────────────────────────────────────────────
1270
+ /**
1271
+ * Spill an evicted L1 entry to disk.
1272
+ *
1273
+ * Returns a Promise that resolves when the file is durably written. Callers
1274
+ * that treat the spill as fire-and-forget should do:
1275
+ * `void disk.save(key, entry)`
1276
+ *
1277
+ * Implementation notes:
1278
+ * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
1279
+ * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
1280
+ * on any external resource.
1281
+ * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
1282
+ * so the Node.js event loop is never stalled waiting for disk I/O.
1283
+ */
1284
+ async save(key, entry) {
1285
+ if (this.isForbidden(key)) return;
1286
+ if (entry.expiresAt <= Date.now()) return;
1287
+ this.ensureDir();
1288
+ if (!this.dirReady) return;
1289
+ this.ensureUsageCounted();
1290
+ if (this.diskUsageBytes >= this.opts.maxBytes) return;
1291
+ let final;
1292
+ try {
1293
+ const payload = {
1294
+ version: DISK_TIER_VERSION,
1295
+ key,
1296
+ entry: {
1297
+ ...entry,
1298
+ data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
1299
+ },
1300
+ writtenAt: Date.now()
1301
+ };
1302
+ const packed = pack2(payload);
1303
+ if (packed.length > this.opts.entryMaxBytes) return;
1304
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1305
+ DISK_MAGIC_V2.copy(header, 0);
1306
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1307
+ final = Buffer.concat([header, this.encryptV2(packed)]);
1308
+ } catch (err) {
1309
+ this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1310
+ return;
1311
+ }
1312
+ const hash = this.keyToHash(key);
1313
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1314
+ this.diskUsageBytes += final.length;
1315
+ this.fileCount++;
1316
+ try {
1317
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
1318
+ await fs.promises.writeFile(filePath, final, { mode: 384 });
1319
+ if (this._db) {
1320
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1321
+ }
1322
+ this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1323
+ } catch (err) {
1324
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1325
+ this.fileCount = Math.max(0, this.fileCount - 1);
1326
+ if (this._db) try {
1327
+ this._stmtDelete.run(hash);
1328
+ } catch {
1329
+ }
1330
+ this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1331
+ }
1332
+ }
1333
+ /** Load a key from disk, or return null on miss/expiry/corruption. */
1334
+ load(key) {
1335
+ if (this.isForbidden(key)) return null;
1336
+ this.ensureDir();
1337
+ if (!this.dirReady) return null;
1338
+ const hash = this.keyToHash(key);
1339
+ let filePath;
1340
+ if (this._db) {
1341
+ const row = this._stmtSelect.get(hash);
1342
+ if (!row) return null;
1343
+ if (row.expires_at <= Date.now()) {
1344
+ this._stmtDelete.run(hash);
1345
+ try {
1346
+ const sz = fs.statSync(row.file_path).size;
1347
+ fs.unlinkSync(row.file_path);
1348
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1349
+ this.fileCount = Math.max(0, this.fileCount - 1);
1350
+ } catch {
1351
+ }
1352
+ return null;
1353
+ }
1354
+ filePath = row.file_path;
1355
+ } else {
1356
+ filePath = this.findFilePath(hash);
1357
+ if (!filePath) return null;
1358
+ }
1359
+ try {
1360
+ if (!this._db) {
1361
+ const filename = path.basename(filePath);
1362
+ if (filename.length === 77 && filename[64] === "_") {
1363
+ const expiresAt = parseInt(filename.slice(65), 16);
1364
+ if (expiresAt <= Date.now()) {
1365
+ try {
1366
+ const sz = fs.statSync(filePath).size;
1367
+ fs.unlinkSync(filePath);
1368
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1369
+ this.fileCount = Math.max(0, this.fileCount - 1);
1370
+ } catch {
1371
+ }
1372
+ return null;
1373
+ }
1374
+ }
1375
+ }
1376
+ const stat = fs.statSync(filePath);
1377
+ if (stat.size > this.opts.entryMaxBytes) {
1378
+ fs.unlinkSync(filePath);
1379
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1380
+ if (this._db) this._stmtDelete.run(hash);
1381
+ return null;
1382
+ }
1383
+ const raw = fs.readFileSync(filePath);
1384
+ try {
1385
+ fs.unlinkSync(filePath);
1386
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1387
+ this.fileCount = Math.max(0, this.fileCount - 1);
1388
+ } catch {
1389
+ }
1390
+ if (this._db) this._stmtDelete.run(hash);
1391
+ let decrypted;
1392
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1393
+ const expiresAt = Number(raw.readBigUInt64LE(8));
1394
+ if (expiresAt <= Date.now()) return null;
1395
+ try {
1396
+ decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
1397
+ } catch {
1398
+ return null;
1399
+ }
1400
+ } else {
1401
+ try {
1402
+ decrypted = this.decrypt(raw);
1403
+ } catch {
1404
+ return null;
1405
+ }
1406
+ }
1407
+ const payload = unpack2(decrypted);
1408
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1409
+ if (payload.entry.expiresAt <= Date.now()) return null;
1410
+ const entry = payload.entry;
1411
+ if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
1412
+ this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1413
+ return entry;
1414
+ } catch (err) {
1415
+ if (this._db) try {
1416
+ this._stmtDelete.run(hash);
1417
+ } catch {
1418
+ }
1419
+ this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1420
+ return null;
1421
+ }
1422
+ }
1423
+ /** Explicitly delete a key from disk (cache invalidation). */
1424
+ delete(key) {
1425
+ const hash = this.keyToHash(key);
1426
+ let filePath;
1427
+ if (this._db) {
1428
+ const row = this._stmtSelect.get(hash);
1429
+ filePath = row?.file_path ?? null;
1430
+ this._stmtDelete.run(hash);
1431
+ } else {
1432
+ filePath = this.findFilePath(hash);
1433
+ }
1434
+ if (!filePath) return;
1435
+ try {
1436
+ const stat = fs.statSync(filePath);
1437
+ fs.unlinkSync(filePath);
1438
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1439
+ this.fileCount = Math.max(0, this.fileCount - 1);
1440
+ } catch {
1441
+ }
1442
+ }
1443
+ /** Purge all expired entries. Returns number deleted. */
1444
+ purgeExpired() {
1445
+ this.ensureDir();
1446
+ if (!this.dirReady) return 0;
1447
+ if (this._db) {
1448
+ const now2 = Date.now();
1449
+ const expired = this._stmtExpire.all(now2);
1450
+ for (const row of expired) {
1451
+ try {
1452
+ fs.unlinkSync(row.file_path);
1453
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1454
+ this.fileCount = Math.max(0, this.fileCount - 1);
1455
+ } catch {
1456
+ }
1457
+ }
1458
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1459
+ return expired.length;
1460
+ }
1461
+ const now = Date.now();
1462
+ let purged = 0;
1463
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1464
+ for (const filePath of this.walkCacheFiles()) {
1465
+ const filename = path.basename(filePath);
1466
+ if (filename.length === 77 && filename[64] === "_") {
1467
+ const expiresAt = parseInt(filename.slice(65), 16);
1468
+ if (expiresAt <= now) {
1469
+ try {
1470
+ const sz = fs.statSync(filePath).size;
1471
+ fs.unlinkSync(filePath);
1472
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1473
+ this.fileCount = Math.max(0, this.fileCount - 1);
1474
+ purged++;
1475
+ } catch {
1476
+ }
1477
+ }
1478
+ continue;
1479
+ }
1480
+ let fd = -1;
1481
+ try {
1482
+ fd = fs.openSync(filePath, "r");
1483
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1484
+ fs.closeSync(fd);
1485
+ fd = -1;
1486
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1487
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1488
+ if (expiresAt <= now) {
1489
+ try {
1490
+ const sz = fs.statSync(filePath).size;
1491
+ fs.unlinkSync(filePath);
1492
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1493
+ this.fileCount = Math.max(0, this.fileCount - 1);
1494
+ purged++;
1495
+ } catch {
1496
+ }
1497
+ }
1498
+ continue;
1499
+ }
1500
+ const stat = fs.statSync(filePath);
1501
+ if (stat.size > this.opts.entryMaxBytes) {
1502
+ fs.unlinkSync(filePath);
1503
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1504
+ this.fileCount = Math.max(0, this.fileCount - 1);
1505
+ purged++;
1506
+ continue;
1507
+ }
1508
+ const raw = fs.readFileSync(filePath);
1509
+ let dec;
1510
+ try {
1511
+ dec = this.decrypt(raw);
1512
+ } catch {
1513
+ fs.unlinkSync(filePath);
1514
+ this.fileCount = Math.max(0, this.fileCount - 1);
1515
+ purged++;
1516
+ continue;
1517
+ }
1518
+ const payload = unpack2(dec);
1519
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1520
+ fs.unlinkSync(filePath);
1521
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1522
+ this.fileCount = Math.max(0, this.fileCount - 1);
1523
+ purged++;
1524
+ }
1525
+ } catch {
1526
+ } finally {
1527
+ if (fd >= 0) try {
1528
+ fs.closeSync(fd);
1529
+ } catch {
1530
+ }
1531
+ }
1532
+ }
1533
+ return purged;
1534
+ }
1535
+ /**
1536
+ * Purge expired entries. Two modes depending on availability of SQLite:
1537
+ *
1538
+ * SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
1539
+ * One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
1540
+ * wheel. All expired entries are found and deleted in a single pass — the
1541
+ * 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
1542
+ * incremented so tests that inspect the counter continue to work.
1543
+ *
1544
+ * File-only fallback:
1545
+ * Original staggered bucket wheel — purges exactly one of 256 subdirectory
1546
+ * buckets per call, spreading the O(fileCount) work across 256 ticks.
1547
+ *
1548
+ * Returns the number of entries deleted in this tick.
1549
+ */
1550
+ purgeNextBucket() {
1551
+ this.ensureDir();
1552
+ if (!this.dirReady) return 0;
1553
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1554
+ if (this._db) {
1555
+ const now2 = Date.now();
1556
+ const expired = this._stmtExpire.all(now2);
1557
+ for (const row of expired) {
1558
+ try {
1559
+ fs.unlinkSync(row.file_path);
1560
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1561
+ this.fileCount = Math.max(0, this.fileCount - 1);
1562
+ } catch {
1563
+ }
1564
+ }
1565
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1566
+ const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
1567
+ const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
1568
+ let orphanFiles;
1569
+ try {
1570
+ orphanFiles = fs.readdirSync(orphanBucketP);
1571
+ } catch {
1572
+ return expired.length;
1573
+ }
1574
+ for (const file of orphanFiles) {
1575
+ if (file.length === 77 && file[64] === "_") {
1576
+ const expiresAt = parseInt(file.slice(65), 16);
1577
+ if (expiresAt <= now2) {
1578
+ const fp = path.join(orphanBucketP, file);
1579
+ try {
1580
+ const sz = fs.statSync(fp).size;
1581
+ fs.unlinkSync(fp);
1582
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1583
+ this.fileCount = Math.max(0, this.fileCount - 1);
1584
+ } catch {
1585
+ }
1586
+ }
1587
+ }
1588
+ }
1589
+ return expired.length;
1590
+ }
1591
+ const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
1592
+ const bucketHex = bucket.toString(16).padStart(2, "0");
1593
+ const bucketPath = path.join(this.opts.dir, bucketHex);
1594
+ let files;
1595
+ try {
1596
+ files = fs.readdirSync(bucketPath);
1597
+ } catch {
1598
+ return 0;
1599
+ }
1600
+ const now = Date.now();
1601
+ let purged = 0;
1602
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1603
+ for (const file of files) {
1604
+ if (file.length === 77 && file[64] === "_") {
1605
+ const expiresAt = parseInt(file.slice(65), 16);
1606
+ if (expiresAt <= now) {
1607
+ const filePath2 = path.join(bucketPath, file);
1608
+ try {
1609
+ const sz = fs.statSync(filePath2).size;
1610
+ fs.unlinkSync(filePath2);
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 filePath = path.join(bucketPath, file);
1620
+ let fd = -1;
1621
+ try {
1622
+ fd = fs.openSync(filePath, "r");
1623
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1624
+ fs.closeSync(fd);
1625
+ fd = -1;
1626
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1627
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1628
+ if (expiresAt <= now) {
1629
+ try {
1630
+ const sz = fs.statSync(filePath).size;
1631
+ fs.unlinkSync(filePath);
1632
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1633
+ this.fileCount = Math.max(0, this.fileCount - 1);
1634
+ purged++;
1635
+ } catch {
1636
+ }
1637
+ }
1638
+ continue;
1639
+ }
1640
+ const stat = fs.statSync(filePath);
1641
+ if (stat.size > this.opts.entryMaxBytes) {
1642
+ fs.unlinkSync(filePath);
1643
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1644
+ this.fileCount = Math.max(0, this.fileCount - 1);
1645
+ purged++;
1646
+ continue;
1647
+ }
1648
+ const raw = fs.readFileSync(filePath);
1649
+ let dec;
1650
+ try {
1651
+ dec = this.decrypt(raw);
1652
+ } catch {
1653
+ fs.unlinkSync(filePath);
1654
+ this.fileCount = Math.max(0, this.fileCount - 1);
1655
+ purged++;
1656
+ continue;
1657
+ }
1658
+ const payload = unpack2(dec);
1659
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1660
+ fs.unlinkSync(filePath);
1661
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1662
+ this.fileCount = Math.max(0, this.fileCount - 1);
1663
+ purged++;
1664
+ }
1665
+ } catch {
1666
+ } finally {
1667
+ if (fd >= 0) try {
1668
+ fs.closeSync(fd);
1669
+ } catch {
1670
+ }
1671
+ }
1672
+ }
1673
+ return purged;
1674
+ }
1675
+ /** Delete every file in the disk cache. Returns the count deleted. */
1676
+ clear() {
1677
+ this.ensureDir();
1678
+ if (!this.dirReady) return 0;
1679
+ let cleared = 0;
1680
+ for (const filePath of this.walkCacheFiles()) {
1681
+ try {
1682
+ const stat = fs.statSync(filePath);
1683
+ fs.unlinkSync(filePath);
1684
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1685
+ this.fileCount = Math.max(0, this.fileCount - 1);
1686
+ cleared++;
1687
+ } catch {
1688
+ }
1689
+ }
1690
+ if (this._db) {
1691
+ this._db.exec("DELETE FROM meta");
1692
+ this.diskUsageBytes = 0;
1693
+ this.fileCount = 0;
1694
+ }
1695
+ return cleared;
1696
+ }
1697
+ get stats() {
1698
+ if (this._db) {
1699
+ const row = this._stmtStats.get();
1700
+ this.fileCount = row.cnt;
1701
+ this.diskUsageBytes = row.bytes;
1702
+ }
1703
+ return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1704
+ }
1705
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1706
+ get indexMode() {
1707
+ return this._db ? "sqlite" : "file-only";
1708
+ }
1709
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1710
+ close() {
1711
+ if (this._db) {
1712
+ try {
1713
+ this._db.close();
1714
+ } catch {
1715
+ }
1716
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1717
+ }
1718
+ }
1719
+ };
1720
+
1721
+ // src/cache-service.ts
1722
+ var SNAPSHOT_VERSION = 1;
1723
+ var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
1724
+ var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
1725
+ var DEFAULT_CATEGORY_LIMITS = {
1726
+ "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1727
+ };
1728
+ var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1729
+ var L2CircuitBreaker = class {
1730
+ constructor(threshold, cooldownMs) {
1731
+ this.threshold = threshold;
1732
+ this.cooldownMs = cooldownMs;
1733
+ }
1734
+ threshold;
1735
+ cooldownMs;
1736
+ state = 0 /* CLOSED */;
1737
+ failures = 0;
1738
+ openedAt = 0;
1739
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
1740
+ isAllowed() {
1741
+ if (this.state === 0 /* CLOSED */) return true;
1742
+ if (this.state === 2 /* HALF_OPEN */) return true;
1743
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
1744
+ this.state = 2 /* HALF_OPEN */;
1745
+ return true;
1746
+ }
1747
+ return false;
1748
+ }
1749
+ /** Call on Redis success. */
1750
+ onSuccess() {
1751
+ this.failures = 0;
1752
+ this.state = 0 /* CLOSED */;
1753
+ }
1754
+ /** Call on Redis failure. */
1755
+ onFailure() {
1756
+ this.failures++;
1757
+ if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1758
+ this.state = 1 /* OPEN */;
1759
+ this.openedAt = Date.now();
1760
+ this.failures = 0;
1761
+ }
1762
+ }
1763
+ get isOpen() {
1764
+ return this.state === 1 /* OPEN */;
1765
+ }
1766
+ get currentState() {
1767
+ return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1768
+ }
1769
+ };
1770
+ function deepFreeze(obj) {
1771
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
1772
+ Object.freeze(obj);
1773
+ for (const v of Object.values(obj)) deepFreeze(v);
1774
+ return obj;
1775
+ }
1776
+ var LatencyTracker = class {
1777
+ samples;
1778
+ maxKeys;
1779
+ bufs = /* @__PURE__ */ new Map();
1780
+ meta = /* @__PURE__ */ new Map();
1781
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
1782
+ scratch;
1783
+ constructor(samples, maxKeys) {
1784
+ this.samples = samples;
1785
+ this.maxKeys = maxKeys;
1786
+ this.scratch = new Float64Array(samples);
1787
+ }
1788
+ record(key, deltaMs) {
1789
+ let buf = this.bufs.get(key);
1790
+ let m = this.meta.get(key);
1791
+ if (buf === void 0) {
1792
+ if (this.bufs.size >= this.maxKeys) {
1793
+ const oldest = this.bufs.keys().next().value;
1794
+ this.bufs.delete(oldest);
1795
+ this.meta.delete(oldest);
1796
+ }
1797
+ buf = new Float64Array(this.samples);
1798
+ m = { head: 0, count: 0, p95: 0, dirty: false };
1799
+ this.bufs.set(key, buf);
1800
+ this.meta.set(key, m);
1801
+ }
1802
+ buf[m.head] = deltaMs;
1803
+ m.head = (m.head + 1) % this.samples;
1804
+ if (m.count < this.samples) m.count++;
1805
+ m.dirty = true;
1806
+ }
1807
+ /**
1808
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
1809
+ * Uses the shared scratch buffer — no heap allocation.
1810
+ */
1811
+ _computeP95(buf, m) {
1812
+ const n = m.count;
1813
+ this.scratch.set(buf.subarray(0, n));
1814
+ const view = this.scratch.subarray(0, n);
1815
+ view.sort();
1816
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
1817
+ m.dirty = false;
1818
+ }
1819
+ /**
1820
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
1821
+ * fewer than 5 samples have been collected (not enough data yet).
1822
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
1823
+ */
1824
+ p95(key) {
1825
+ const buf = this.bufs.get(key);
1826
+ const m = this.meta.get(key);
1827
+ if (!buf || !m || m.count < 5) return null;
1828
+ if (m.dirty) this._computeP95(buf, m);
1829
+ return m.p95;
1830
+ }
1831
+ get trackedKeys() {
1832
+ return this.bufs.size;
1833
+ }
1834
+ /**
1835
+ * Top-20 slowest keys by p95, sorted descending.
1836
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
1837
+ *
1838
+ * Only dirty keys (those with new samples since the last call) pay the sort
1839
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
1840
+ * metrics() calls with no intervening fetches are essentially free.
1841
+ */
1842
+ snapshot(prefixLen, multiplierSec, minMs, maxMs) {
1843
+ const out = [];
1844
+ for (const [key, buf] of this.bufs) {
1845
+ const m = this.meta.get(key);
1846
+ if (m.count < 5) continue;
1847
+ if (m.dirty) this._computeP95(buf, m);
1848
+ const p95 = m.p95;
1849
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
1850
+ out.push({
1851
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
1852
+ p95Ms: Math.round(p95),
1853
+ adaptedTtlSec: Math.round(adaptedMs / 1e3)
1854
+ });
1855
+ }
1856
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
1857
+ }
1858
+ };
1859
+ function inferPriority(cacheKey) {
1860
+ if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1861
+ if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
1862
+ if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
1863
+ return 2 /* NORMAL */;
1864
+ }
1865
+ var GLOBAL_KEY = "__tricache_instance__";
1866
+ function detectServerlessRuntime() {
1867
+ if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
1868
+ if (process.env["K_SERVICE"]) return "Google Cloud Run";
1869
+ if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
1870
+ if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
1871
+ if (process.env["FLY_APP_NAME"]) return "Fly.io";
1872
+ if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
1873
+ if (process.env["VERCEL"]) return "Vercel";
1874
+ return null;
1875
+ }
1876
+ var CacheService = class _CacheService {
1877
+ logger;
1878
+ enc;
1879
+ l1;
1880
+ disk;
1881
+ /** When true, all disk-tier and snapshot operations are skipped. */
1882
+ _diskDisabled = false;
1883
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
1884
+ _workerPool = null;
1885
+ opts;
1886
+ /** Pre-computed once — opts.namespace never changes after construction. */
1887
+ _namespace;
1888
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
1889
+ _redisDisabled;
1890
+ inflight = /* @__PURE__ */ new Map();
1891
+ revalidating = /* @__PURE__ */ new Set();
1892
+ _l1Counters = /* @__PURE__ */ new Map();
1893
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1894
+ tagIndex = /* @__PURE__ */ new Map();
1895
+ /**
1896
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
1897
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
1898
+ */
1899
+ dependencyIndex = /* @__PURE__ */ new Map();
1900
+ redis = null;
1901
+ redisConnecting = null;
1902
+ cb;
1903
+ snapshotLoaded = false;
1904
+ _readyPromise = Promise.resolve();
1905
+ cleanupInterval = null;
1906
+ diskJanitorInterval = null;
1907
+ oomInterval = null;
1908
+ metricsInterval = null;
1909
+ _shutdownHandler = null;
1910
+ latencyTracker = null;
1911
+ instanceId;
1912
+ backplaneChannel;
1913
+ subClient = null;
1914
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
1915
+ _subDisconnectedAt = null;
1916
+ counters = {
1917
+ gets: 0,
1918
+ l1Hits: 0,
1919
+ diskHits: 0,
1920
+ l2Hits: 0,
1921
+ fetches: 0,
1922
+ stampedes: 0,
1923
+ sets: 0,
1924
+ deletes: 0,
1925
+ swrRevalidations: 0,
1926
+ invSent: 0,
1927
+ invReceived: 0,
1928
+ invSkipped: 0,
1929
+ oomEvictions: 0,
1930
+ oomLastAt: null,
1931
+ startedAt: Date.now()
1932
+ };
1933
+ // ── Constructor (use CacheService.create() for the recommended singleton) ──
1934
+ constructor(options = {}) {
1935
+ const logger = options.logger ?? consoleLogger;
1936
+ this.logger = logger;
1937
+ const ns = options.namespace?.trim() ?? "";
1938
+ const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
1939
+ this.enc = new CacheEncryption(
1940
+ encKeyRaw,
1941
+ logger,
1942
+ options.encryptionMode,
1943
+ options.previousEncryptionKey,
1944
+ options.previousEncryptionMode
1945
+ );
1946
+ const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
1947
+ const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
1948
+ this.opts = {
1949
+ namespace: ns,
1950
+ logger,
1951
+ l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
1952
+ l1MaxEntries: options.l1MaxEntries ?? 2e3,
1953
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits ?? {} },
1954
+ forbiddenSnapshotPrefixes: forbiddenPrefixes,
1955
+ // Namespace-isolated defaults: separate dir / snapshot per namespace so
1956
+ // two instances with different namespaces never share cache files.
1957
+ diskCacheDir: options.diskCacheDir ?? path2.join(
1958
+ os.tmpdir(),
1959
+ ns ? `tricache-disk-${ns}` : "tricache-disk"
1960
+ ),
1961
+ diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
1962
+ diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
1963
+ redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
1964
+ redisPort: options.redisPort ?? 6379,
1965
+ redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
1966
+ disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
1967
+ encryptionKey: encKeyRaw,
1968
+ snapshotPath: options.snapshotPath ?? path2.join(
1969
+ os.tmpdir(),
1970
+ ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
1971
+ ),
1972
+ snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
1973
+ invalidationBackplane: options.invalidationBackplane ?? true,
1974
+ oomProtection: options.oomProtection ?? true,
1975
+ oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
1976
+ oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
1977
+ oomEvictPercent: options.oomEvictPercent ?? 0.2,
1978
+ onMetrics: options.onMetrics,
1979
+ metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1980
+ staleIfError: options.staleIfError ?? 0,
1981
+ l2WriteMode: options.l2WriteMode ?? "read-write",
1982
+ instanceName: options.instanceName ?? "",
1983
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
1984
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1985
+ tracer: options.tracer,
1986
+ notFoundTtl: options.notFoundTtl ?? 0,
1987
+ warmKeys: options.warmKeys,
1988
+ onHit: options.onHit,
1989
+ onMiss: options.onMiss,
1990
+ frozen: options.frozen ?? false,
1991
+ adaptiveTtl: options.adaptiveTtl ?? false,
1992
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
1993
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
1994
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
1995
+ workerThreads: options.workerThreads ?? false,
1996
+ workerThresholdBytes: options.workerThresholdBytes ?? 131072,
1997
+ // 128 KB
1998
+ workerPoolSize: options.workerPoolSize ?? 0,
1999
+ // 0 = auto (min(4, cpus))
2000
+ backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
2001
+ disableDisk: options.disableDisk ?? false,
2002
+ redisClusterNodes: options.redisClusterNodes,
2003
+ redisSentinel: options.redisSentinel
2004
+ };
2005
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2006
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2007
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
2008
+ if (this.opts.adaptiveTtl) {
2009
+ const samples = options.adaptiveTtlSamples ?? 32;
2010
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
2011
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
2012
+ }
2013
+ let diskDisabled = this.opts.disableDisk;
2014
+ if (options.disableDisk === void 0) {
2015
+ const serverless = detectServerlessRuntime();
2016
+ if (serverless !== null) {
2017
+ diskDisabled = true;
2018
+ logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
2019
+ runtime: serverless,
2020
+ hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
2021
+ });
2022
+ }
2023
+ } else if (diskDisabled) {
2024
+ logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
2025
+ }
2026
+ this._diskDisabled = diskDisabled;
2027
+ this.disk = new DiskTier({
2028
+ dir: this.opts.diskCacheDir,
2029
+ maxBytes: this.opts.diskMaxBytes,
2030
+ entryMaxBytes: this.opts.diskEntryMaxBytes,
2031
+ forbiddenPrefixes,
2032
+ encryptionKey: this.enc.isEnabled ? this.enc["_key"] : null,
2033
+ logger
2034
+ });
2035
+ this._namespace = ns;
2036
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
2037
+ this.l1 = new SmartMemoryCache({
2038
+ maxBytes: this.opts.l1MaxBytes,
2039
+ maxEntries: this.opts.l1MaxEntries,
2040
+ categories: this.opts.categoryLimits,
2041
+ evictionWatermark: this.opts.l1EvictionWatermark,
2042
+ diskSpill: (key, entry) => {
2043
+ if (this._diskDisabled) return;
2044
+ setImmediate(() => {
2045
+ void this.disk.save(key, entry);
2046
+ });
2047
+ },
2048
+ onEviction: options.onEviction,
2049
+ logger
2050
+ });
2051
+ if (!this.snapshotLoaded) {
2052
+ this.snapshotLoaded = true;
2053
+ if (!this._diskDisabled) this.loadSnapshot();
2054
+ }
2055
+ this._shutdownHandler = () => {
2056
+ if (!this._diskDisabled) this.writeSnapshot();
2057
+ process.exit(0);
2058
+ };
2059
+ process.once("SIGTERM", this._shutdownHandler);
2060
+ process.once("SIGINT", this._shutdownHandler);
2061
+ if (this.opts.workerThreads && this.enc.isEnabled) {
2062
+ try {
2063
+ const encRef = this.enc;
2064
+ this._workerPool = new WorkerPool({
2065
+ keyBase64: encRef._key ? encRef._key.toString("base64") : "",
2066
+ mode: encRef._mode,
2067
+ prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
2068
+ prevMode: encRef._prevMode,
2069
+ size: this.opts.workerPoolSize || void 0
2070
+ });
2071
+ if (this._workerPool.isAvailable) {
2072
+ logger.info("tricache: worker-thread encryption pool active", {
2073
+ threshold: `${this.opts.workerThresholdBytes / 1024} KB`
2074
+ });
2075
+ } else {
2076
+ this._workerPool = null;
2077
+ logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
2078
+ }
2079
+ } catch {
2080
+ this._workerPool = null;
2081
+ logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
2082
+ }
2083
+ }
2084
+ this.cleanupInterval = setInterval(() => {
2085
+ const cleaned = this.l1.cleanup();
2086
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
2087
+ }, 5 * 60 * 1e3);
2088
+ if (this.cleanupInterval.unref) this.cleanupInterval.unref();
2089
+ if (!this._diskDisabled) {
2090
+ this.diskJanitorInterval = setInterval(() => {
2091
+ const purged = this.disk.purgeNextBucket();
2092
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
2093
+ }, 3e4);
2094
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
2095
+ }
2096
+ if (this.opts.oomProtection) {
2097
+ this.oomInterval = setInterval(() => {
2098
+ const heap = v8.getHeapStatistics();
2099
+ const used = heap.used_heap_size / heap.heap_size_limit;
2100
+ if (used >= this.opts.oomHeapThreshold) {
2101
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
2102
+ this.counters.oomEvictions++;
2103
+ this.counters.oomLastAt = Date.now();
2104
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
2105
+ heapUsedPct: Math.round(used * 100),
2106
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
2107
+ evicted
2108
+ });
2109
+ }
2110
+ }, this.opts.oomCheckIntervalMs);
2111
+ if (this.oomInterval.unref) this.oomInterval.unref();
2112
+ }
2113
+ if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
2114
+ this.metricsInterval = setInterval(() => {
2115
+ try {
2116
+ this.opts.onMetrics(this.metrics());
2117
+ } catch {
2118
+ }
2119
+ }, this.opts.metricsIntervalMs);
2120
+ if (this.metricsInterval.unref) this.metricsInterval.unref();
2121
+ }
2122
+ this.instanceId = crypto2.randomBytes(8).toString("hex");
2123
+ this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2124
+ this.initBackplane();
2125
+ if (this.opts.warmKeys) {
2126
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
2127
+ }
2128
+ }
2129
+ // ── Singleton factory ─────────────────────────────────────────────────────
2130
+ /**
2131
+ * Get (or create) the process-level singleton CacheService instance.
2132
+ *
2133
+ * Options are only applied on first call — subsequent calls return the
2134
+ * existing instance regardless of options passed.
2135
+ *
2136
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
2137
+ * with different namespaces return independent instances.
2138
+ */
2139
+ static create(options) {
2140
+ const g = globalThis;
2141
+ const key = _CacheService.globalKey(options);
2142
+ if (!g[key]) g[key] = new _CacheService(options);
2143
+ return g[key];
2144
+ }
2145
+ /**
2146
+ * Async factory — accepts a Promise that resolves to CacheOptions.
2147
+ * Useful when config is fetched from a secret store at startup.
2148
+ *
2149
+ * @example
2150
+ * const cache = await CacheService.createAsync(fetchSecrets());
2151
+ */
2152
+ static async createAsync(options) {
2153
+ const resolved = await options;
2154
+ return _CacheService.create(resolved);
2155
+ }
2156
+ /** Replace the singleton (useful in tests). */
2157
+ static reset(options) {
2158
+ const g = globalThis;
2159
+ const key = _CacheService.globalKey(options);
2160
+ const existing = g[key];
2161
+ if (existing) existing.destroy();
2162
+ g[key] = new _CacheService(options);
2163
+ return g[key];
2164
+ }
2165
+ /** Derive the globalThis key for a given set of options. */
2166
+ static globalKey(options) {
2167
+ const ns = options?.namespace?.trim() ?? "";
2168
+ return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
2169
+ }
2170
+ // ── Redis connection ──────────────────────────────────────────────────────
2171
+ /**
2172
+ * Prepend the configured namespace to a raw cache key.
2173
+ * Returns the key unchanged when namespace is empty.
2174
+ *
2175
+ * This is the only place the namespace prefix is applied — callers always
2176
+ * receive and provide un-prefixed keys in the public API.
2177
+ */
2178
+ nk(key) {
2179
+ return this._namespace ? `${this._namespace}:${key}` : key;
2180
+ }
2181
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
2182
+ _jitterTtl(ttlMs) {
2183
+ const j = this.opts.ttlJitterFactor;
2184
+ if (j === 0) return ttlMs;
2185
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
2186
+ }
2187
+ /** Shared no-op span for the common case where no tracer is configured.
2188
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
2189
+ static _nullSpan = {
2190
+ setAttribute() {
2191
+ return this;
2192
+ },
2193
+ setStatus() {
2194
+ return this;
2195
+ },
2196
+ end() {
2197
+ }
2198
+ };
2199
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
2200
+ _startSpan(name) {
2201
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
2202
+ return _CacheService._nullSpan;
2203
+ }
2204
+ initBackplane() {
2205
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2206
+ if (this.subClient) return;
2207
+ let sub;
2208
+ if (this.opts.redisClusterNodes?.length) {
2209
+ sub = new RedisCluster(this.opts.redisClusterNodes, {
2210
+ redisOptions: {
2211
+ tls: this.opts.redisTls ? {} : void 0,
2212
+ connectTimeout: 1e4,
2213
+ maxRetriesPerRequest: null
2214
+ }
2215
+ });
2216
+ } else if (this.opts.redisSentinel) {
2217
+ sub = new RedisClient({
2218
+ sentinels: this.opts.redisSentinel.sentinels,
2219
+ name: this.opts.redisSentinel.name,
2220
+ tls: this.opts.redisTls ? {} : void 0,
2221
+ connectTimeout: 1e4,
2222
+ lazyConnect: true,
2223
+ maxRetriesPerRequest: null,
2224
+ enableAutoPipelining: false,
2225
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2226
+ });
2227
+ } else {
2228
+ sub = new RedisClient({
2229
+ host: this.opts.redisHost,
2230
+ port: this.opts.redisPort,
2231
+ tls: this.opts.redisTls ? {} : void 0,
2232
+ connectTimeout: 1e4,
2233
+ lazyConnect: true,
2234
+ maxRetriesPerRequest: null,
2235
+ enableAutoPipelining: false,
2236
+ family: 4,
2237
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2238
+ });
2239
+ }
2240
+ sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
2241
+ sub.on("close", () => {
2242
+ if (this._subDisconnectedAt === null) {
2243
+ this._subDisconnectedAt = Date.now();
2244
+ this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
2245
+ }
2246
+ });
2247
+ sub.on("ready", () => {
2248
+ if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
2249
+ const gapMs = Date.now() - this._subDisconnectedAt;
2250
+ if (gapMs > this.opts.backplaneMaxStalenessMs) {
2251
+ const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
2252
+ this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
2253
+ gapMs,
2254
+ evicted,
2255
+ hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
2256
+ });
2257
+ }
2258
+ this._subDisconnectedAt = null;
2259
+ }
2260
+ });
2261
+ sub.on("message", (_channel, message) => {
2262
+ this._handleBackplaneMessage(message);
2263
+ });
2264
+ sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
2265
+ channel: this.backplaneChannel,
2266
+ instanceId: this.instanceId
2267
+ })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
2268
+ error: err.message
2269
+ }));
2270
+ this.subClient = sub;
2271
+ }
2272
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
2273
+ _handleBackplaneMessage(message) {
2274
+ try {
2275
+ const msg = JSON.parse(message);
2276
+ if (msg.src === this.instanceId) {
2277
+ this.counters.invSkipped++;
2278
+ return;
2279
+ }
2280
+ this.counters.invReceived++;
2281
+ if (msg.op === "del") {
2282
+ this.l1.delete(msg.key);
2283
+ setImmediate(() => {
2284
+ if (!this._diskDisabled) this.disk.delete(msg.key);
2285
+ });
2286
+ this._cascadeDependencies(msg.key);
2287
+ } else if (msg.op === "del-glob") {
2288
+ this.l1.deletePattern(msg.key);
2289
+ }
2290
+ this.logger.debug("Backplane: peer invalidation applied", {
2291
+ op: msg.op,
2292
+ key: msg.key.slice(0, 60)
2293
+ });
2294
+ } catch {
2295
+ }
2296
+ }
2297
+ async publishInvalidation(op, key) {
2298
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2299
+ try {
2300
+ const client = await this.getRedis();
2301
+ await client.publish(
2302
+ this.backplaneChannel,
2303
+ JSON.stringify({ op, key, src: this.instanceId })
2304
+ );
2305
+ this.counters.invSent++;
2306
+ } catch {
2307
+ }
2308
+ }
2309
+ /**
2310
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
2311
+ * For Cluster, iterates every master node independently (SCAN is node-local).
2312
+ */
2313
+ async _scanKeys(client, pattern) {
2314
+ const keys = [];
2315
+ if (client instanceof RedisCluster) {
2316
+ const masters = client.nodes("master");
2317
+ await Promise.all(masters.map(
2318
+ (node) => new Promise((resolve, reject) => {
2319
+ const stream = node.scanStream({ match: pattern, count: 100 });
2320
+ stream.on("data", (chunk) => keys.push(...chunk));
2321
+ stream.on("end", resolve);
2322
+ stream.on("error", reject);
2323
+ })
2324
+ ));
2325
+ } else {
2326
+ await new Promise((resolve, reject) => {
2327
+ const stream = client.scanStream({ match: pattern, count: 100 });
2328
+ stream.on("data", (chunk) => keys.push(...chunk));
2329
+ stream.on("end", resolve);
2330
+ stream.on("error", reject);
2331
+ });
2332
+ }
2333
+ return keys;
2334
+ }
2335
+ async getRedis() {
2336
+ if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
2337
+ if (this.redisConnecting) return this.redisConnecting;
2338
+ this.redisConnecting = (async () => {
2339
+ try {
2340
+ let client;
2341
+ if (this.opts.redisClusterNodes?.length) {
2342
+ client = new RedisCluster(this.opts.redisClusterNodes, {
2343
+ redisOptions: {
2344
+ tls: this.opts.redisTls ? {} : void 0,
2345
+ connectTimeout: 1e4,
2346
+ maxRetriesPerRequest: 3,
2347
+ keepAlive: 3e4
2348
+ },
2349
+ enableAutoPipelining: true,
2350
+ retryDelayOnClusterDown: 200,
2351
+ retryDelayOnFailover: 1e3
2352
+ });
2353
+ client.on("connect", () => this.logger.info("Redis Cluster connected"));
2354
+ client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
2355
+ client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
2356
+ } else if (this.opts.redisSentinel) {
2357
+ client = new RedisClient({
2358
+ sentinels: this.opts.redisSentinel.sentinels,
2359
+ name: this.opts.redisSentinel.name,
2360
+ tls: this.opts.redisTls ? {} : void 0,
2361
+ connectTimeout: 1e4,
2362
+ lazyConnect: false,
2363
+ maxRetriesPerRequest: 3,
2364
+ enableAutoPipelining: true,
2365
+ keepAlive: 3e4,
2366
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2367
+ });
2368
+ client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
2369
+ client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
2370
+ client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
2371
+ } else {
2372
+ client = new RedisClient({
2373
+ host: this.opts.redisHost,
2374
+ port: this.opts.redisPort,
2375
+ tls: this.opts.redisTls ? {} : void 0,
2376
+ connectTimeout: 1e4,
2377
+ lazyConnect: false,
2378
+ maxRetriesPerRequest: 3,
2379
+ enableAutoPipelining: true,
2380
+ keepAlive: 3e4,
2381
+ family: 4,
2382
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2383
+ });
2384
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2385
+ client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
2386
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2387
+ }
2388
+ await new Promise((resolve, reject) => {
2389
+ client.once("ready", resolve);
2390
+ client.once("error", reject);
2391
+ setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
2392
+ });
2393
+ this.cb.onSuccess();
2394
+ this.redis = client;
2395
+ this.redisConnecting = null;
2396
+ return client;
2397
+ } catch (err) {
2398
+ this.cb.onFailure();
2399
+ this.redisConnecting = null;
2400
+ throw err;
2401
+ }
2402
+ })();
2403
+ return this.redisConnecting;
2404
+ }
2405
+ // ── Snapshot (cold-start persistence) ────────────────────────────────────
2406
+ writeSnapshot(altPath) {
2407
+ try {
2408
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2409
+ if (entries.length === 0) return;
2410
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2411
+ const packed = pack3(payload);
2412
+ const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2413
+ const dest = altPath ?? this.opts.snapshotPath;
2414
+ fs2.writeFileSync(dest, final, { mode: 384 });
2415
+ this.logger.info("Cache snapshot written", {
2416
+ path: dest,
2417
+ entries: entries.length,
2418
+ sizeKB: Math.round(final.length / 1024),
2419
+ encrypted: this.enc.isEnabled
2420
+ });
2421
+ } catch (err) {
2422
+ this.logger.warn("Cache snapshot write failed", { error: err.message });
2423
+ }
2424
+ }
2425
+ loadSnapshot() {
2426
+ const snapshotPath = this.opts.snapshotPath;
2427
+ try {
2428
+ if (!fs2.existsSync(snapshotPath)) return;
2429
+ const stat = fs2.statSync(snapshotPath);
2430
+ if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
2431
+ this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
2432
+ fs2.unlinkSync(snapshotPath);
2433
+ return;
2434
+ }
2435
+ const raw = fs2.readFileSync(snapshotPath);
2436
+ fs2.unlinkSync(snapshotPath);
2437
+ let buf;
2438
+ try {
2439
+ buf = this.enc.decryptBuffer(raw);
2440
+ } catch (e) {
2441
+ this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
2442
+ return;
2443
+ }
2444
+ const snapshot = unpack3(buf);
2445
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
2446
+ this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
2447
+ return;
2448
+ }
2449
+ const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
2450
+ if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
2451
+ this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
2452
+ return;
2453
+ }
2454
+ if (!Array.isArray(snapshot.entries)) {
2455
+ this.logger.warn("Snapshot rejected: entries is not an array");
2456
+ return;
2457
+ }
2458
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2459
+ this.logger.info("Cache snapshot loaded (L1 is warm)", {
2460
+ loaded,
2461
+ total: snapshot.entries.length,
2462
+ sizeKB: this.l1.getStats().sizeKB
2463
+ });
2464
+ } catch (err) {
2465
+ this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
2466
+ try {
2467
+ fs2.unlinkSync(snapshotPath);
2468
+ } catch {
2469
+ }
2470
+ }
2471
+ }
2472
+ // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
2473
+ /**
2474
+ * Get a value from cache, or fetch and cache it.
2475
+ *
2476
+ * @param cacheKey - Unique key identifying this value
2477
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
2478
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
2479
+ * @param opts.priority - Override the auto-inferred eviction priority
2480
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
2481
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
2482
+ * is triggered proactively while the caller still receives the
2483
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
2484
+ * Requires `fetchFn` to be stable across calls.
2485
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
2486
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
2487
+ * Complementary to refreshAhead — uses recompute cost (delta) to
2488
+ * decide probabilistically rather than at a fixed threshold.
2489
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
2490
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
2491
+ */
2492
+ async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
2493
+ const span = this._startSpan("tricache.get");
2494
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2495
+ const k = this.nk(cacheKey);
2496
+ this.counters.gets++;
2497
+ const optSwr = opts.swr ?? 0;
2498
+ const optPriority = opts.priority;
2499
+ const optRefreshAhead = opts.refreshAhead;
2500
+ const optXfetchBeta = opts.xfetchBeta;
2501
+ const optNotFoundTtl = opts.notFoundTtl;
2502
+ const optTags = opts.tags;
2503
+ const l1Hit = this.l1.get(k);
2504
+ if (l1Hit !== null) {
2505
+ if (l1Hit.isStale) {
2506
+ const swrGraceMs2 = optSwr * 1e3;
2507
+ if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
2508
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2509
+ this.revalidating.add(k);
2510
+ void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
2511
+ this.counters.swrRevalidations++;
2512
+ this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
2513
+ } else {
2514
+ this.logger.debug("L1 hit");
2515
+ }
2516
+ } else {
2517
+ this.logger.debug("L1 hit");
2518
+ const ra = optRefreshAhead;
2519
+ const xb = optXfetchBeta;
2520
+ if (ra || xb) {
2521
+ const now = l1Hit.fetchedAt ?? Date.now();
2522
+ const remaining = l1Hit.expiresAt - now;
2523
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
2524
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
2525
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
2526
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2527
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2528
+ this.revalidating.add(k);
2529
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
2530
+ this.counters.swrRevalidations++;
2531
+ this.logger.debug(
2532
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
2533
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
2534
+ );
2535
+ }
2536
+ }
2537
+ }
2538
+ this.counters.l1Hits++;
2539
+ this.opts.onHit?.(cacheKey, "l1");
2540
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
2541
+ span.setAttribute("cache.hit", "l1").end();
2542
+ return l1Hit.value;
2543
+ }
2544
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2545
+ const swrGraceMs = optSwr * 1e3;
2546
+ const priority = optPriority ?? inferPriority(cacheKey);
2547
+ if (!this._redisDisabled) {
2548
+ try {
2549
+ const client = await this.getRedis();
2550
+ const raw = await client.get(k);
2551
+ this.cb.onSuccess();
2552
+ if (raw) {
2553
+ let decrypted;
2554
+ if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
2555
+ decrypted = await this._workerPool.decrypt(raw);
2556
+ } else {
2557
+ decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2558
+ }
2559
+ const parsed = JSON.parse(decrypted);
2560
+ this.l1.set(k, parsed, ttlMs, priority);
2561
+ this.counters.l2Hits++;
2562
+ this.opts.onHit?.(cacheKey, "l2");
2563
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
2564
+ span.setAttribute("cache.hit", "l2").end();
2565
+ return parsed;
2566
+ }
2567
+ } catch (err) {
2568
+ this.cb.onFailure();
2569
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
2570
+ }
2571
+ }
2572
+ if (!this._diskDisabled) {
2573
+ const diskHit = this.disk.load(k);
2574
+ if (diskHit !== null) {
2575
+ const promoted = this.l1.importEntries(
2576
+ [{ key: k, entry: diskHit }],
2577
+ this.opts.forbiddenSnapshotPrefixes
2578
+ );
2579
+ if (promoted > 0) {
2580
+ const l1Check = this.l1.get(k);
2581
+ if (l1Check !== null) {
2582
+ this.counters.diskHits++;
2583
+ this.opts.onHit?.(cacheKey, "disk");
2584
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
2585
+ span.setAttribute("cache.hit", "disk").end();
2586
+ return l1Check.value;
2587
+ }
2588
+ }
2589
+ }
2590
+ }
2591
+ span.setAttribute("cache.hit", "miss");
2592
+ this.opts.onMiss?.(cacheKey);
2593
+ const existing = this.inflight.get(k);
2594
+ if (existing) {
2595
+ this.counters.stampedes++;
2596
+ this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
2597
+ span.end();
2598
+ return existing;
2599
+ }
2600
+ const fetchPromise = (async () => {
2601
+ try {
2602
+ this.counters.fetches++;
2603
+ const fetchStart = Date.now();
2604
+ const data = await fetchFn();
2605
+ const delta = Date.now() - fetchStart;
2606
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
2607
+ let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
2608
+ if (this.latencyTracker && data != null) {
2609
+ this.latencyTracker.record(k, delta);
2610
+ const p95 = this.latencyTracker.p95(k);
2611
+ if (p95 !== null) {
2612
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
2613
+ effectiveTtl = Math.max(
2614
+ this.opts.adaptiveTtlMinMs,
2615
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
2616
+ );
2617
+ }
2618
+ }
2619
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
2620
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
2621
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2622
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
2623
+ if (!this._redisDisabled) {
2624
+ try {
2625
+ const client = await this.getRedis();
2626
+ const serialized = JSON.stringify(data);
2627
+ let toStore;
2628
+ if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
2629
+ toStore = await this._workerPool.encrypt(serialized);
2630
+ } else {
2631
+ toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2632
+ }
2633
+ await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
2634
+ this.cb.onSuccess();
2635
+ this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
2636
+ } catch {
2637
+ this.cb.onFailure();
2638
+ this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
2639
+ }
2640
+ } else {
2641
+ this.logger.debug("Cached L1", { cacheKey });
2642
+ }
2643
+ return data;
2644
+ } finally {
2645
+ this.inflight.delete(k);
2646
+ span.end();
2647
+ }
2648
+ })();
2649
+ this.inflight.set(k, fetchPromise);
2650
+ return fetchPromise;
2651
+ }
2652
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
2653
+ try {
2654
+ const fetchStart = Date.now();
2655
+ const data = await fetchFn();
2656
+ const delta = Date.now() - fetchStart;
2657
+ const staleAt = Date.now() + ttlMs;
2658
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2659
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
2660
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2661
+ try {
2662
+ const client = await this.getRedis();
2663
+ const s = JSON.stringify(data);
2664
+ let stored;
2665
+ if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
2666
+ stored = await this._workerPool.encrypt(s);
2667
+ } else {
2668
+ stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2669
+ }
2670
+ await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
2671
+ } catch {
2672
+ }
2673
+ }
2674
+ this.logger.debug("SWR: revalidation complete", { cacheKey });
2675
+ } catch (err) {
2676
+ if (this.opts.staleIfError > 0) {
2677
+ const additionalMs = this.opts.staleIfError * 1e3;
2678
+ this.l1.bumpExpiry(cacheKey, additionalMs);
2679
+ this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
2680
+ cacheKey,
2681
+ staleIfErrorSecs: this.opts.staleIfError
2682
+ });
2683
+ } else {
2684
+ this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
2685
+ }
2686
+ } finally {
2687
+ this.revalidating.delete(cacheKey);
2688
+ }
2689
+ }
2690
+ // ── Explicit set / delete ─────────────────────────────────────────────────
2691
+ /** Explicitly write a value into L1 (+ L2 in production). */
2692
+ async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
2693
+ const span = this._startSpan("tricache.set");
2694
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2695
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2696
+ const p = priority ?? inferPriority(cacheKey);
2697
+ const k = this.nk(cacheKey);
2698
+ this.counters.sets++;
2699
+ this.l1.set(k, data, ttlMs, p);
2700
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
2701
+ if (opts?.dependsOn?.length) {
2702
+ for (const pattern of opts.dependsOn) {
2703
+ const nsPattern = this.nk(pattern);
2704
+ let deps = this.dependencyIndex.get(nsPattern);
2705
+ if (!deps) {
2706
+ deps = /* @__PURE__ */ new Set();
2707
+ this.dependencyIndex.set(nsPattern, deps);
2708
+ }
2709
+ deps.add(k);
2710
+ }
2711
+ }
2712
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2713
+ try {
2714
+ const client = await this.getRedis();
2715
+ const s = JSON.stringify(data);
2716
+ let stored;
2717
+ if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
2718
+ stored = await this._workerPool.encrypt(s);
2719
+ } else {
2720
+ stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2721
+ }
2722
+ await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
2723
+ this.cb.onSuccess();
2724
+ } catch (err) {
2725
+ this.cb.onFailure();
2726
+ this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
2727
+ }
2728
+ }
2729
+ void this.publishInvalidation("del", k);
2730
+ span.end();
2731
+ }
2732
+ /**
2733
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
2734
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2735
+ */
2736
+ async _registerTags(k, tags, ttlSeconds) {
2737
+ for (const tag of tags) {
2738
+ const tagKey = this.nk(`_tag_:${tag}`);
2739
+ let members = this.tagIndex.get(tagKey);
2740
+ if (!members) {
2741
+ members = /* @__PURE__ */ new Set();
2742
+ this.tagIndex.set(tagKey, members);
2743
+ }
2744
+ members.add(k);
2745
+ }
2746
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2747
+ try {
2748
+ const client = await this.getRedis();
2749
+ const pl = client.pipeline();
2750
+ for (const tag of tags) {
2751
+ const tagKey = this.nk(`_tag_:${tag}`);
2752
+ pl.sadd(tagKey, k);
2753
+ pl.expire(tagKey, ttlSeconds + 3600);
2754
+ }
2755
+ await pl.exec();
2756
+ this.cb.onSuccess();
2757
+ } catch {
2758
+ this.cb.onFailure();
2759
+ }
2760
+ }
2761
+ }
2762
+ /**
2763
+ * Delete one key or a glob pattern (supports `*` wildcard).
2764
+ *
2765
+ * @example
2766
+ * await cache.delete('user:abc:profile'); // exact key
2767
+ * await cache.delete('user:abc:*'); // all keys for user abc
2768
+ */
2769
+ async delete(cacheKey) {
2770
+ const span = this._startSpan("tricache.delete");
2771
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2772
+ const isPattern = cacheKey.includes("*");
2773
+ const k = this.nk(cacheKey);
2774
+ this.counters.deletes++;
2775
+ if (isPattern) {
2776
+ this.l1.deletePattern(k);
2777
+ } else {
2778
+ this.l1.delete(k);
2779
+ setImmediate(() => {
2780
+ if (!this._diskDisabled) this.disk.delete(k);
2781
+ });
2782
+ this._cascadeDependencies(k);
2783
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2784
+ }
2785
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2786
+ try {
2787
+ const client = await this.getRedis();
2788
+ if (isPattern) {
2789
+ const keys = await this._scanKeys(client, k);
2790
+ if (keys.length > 0) await client.del(...keys);
2791
+ } else {
2792
+ await client.del(k);
2793
+ }
2794
+ this.cb.onSuccess();
2795
+ } catch (err) {
2796
+ this.cb.onFailure();
2797
+ this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
2798
+ }
2799
+ }
2800
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
2801
+ span.end();
2802
+ }
2803
+ // ── Counter (distributed rate limiting) ──────────────────────────────────
2804
+ /**
2805
+ * Atomically increment a counter in Redis. Returns the new value.
2806
+ * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
2807
+ */
2808
+ async increment(cacheKey, ttlSeconds) {
2809
+ const k = this.nk(cacheKey);
2810
+ if (this._redisDisabled) {
2811
+ const now = Date.now();
2812
+ const ttlMs = (ttlSeconds ?? 60) * 1e3;
2813
+ const entry = this._l1Counters.get(k);
2814
+ if (entry && entry.expiresAt > now) {
2815
+ entry.value++;
2816
+ return entry.value;
2817
+ }
2818
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
2819
+ return 1;
2820
+ }
2821
+ try {
2822
+ const client = await this.getRedis();
2823
+ const count = await client.incr(k);
2824
+ if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
2825
+ return count;
2826
+ } catch (err) {
2827
+ this.logger.error("increment: Redis error", { cacheKey }, err);
2828
+ return 0;
2829
+ }
2830
+ }
2831
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
2832
+ /**
2833
+ * Flush all cached entries, or only those whose key starts with `prefix`.
2834
+ *
2835
+ * @example
2836
+ * await cache.clear(); // flush everything
2837
+ * await cache.clear('user:abc'); // flush all keys for one user
2838
+ */
2839
+ async clear(prefix) {
2840
+ this.counters.deletes++;
2841
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
2842
+ if (k) {
2843
+ this.l1.deletePattern(k);
2844
+ } else {
2845
+ this.l1.clear();
2846
+ if (!this._diskDisabled) this.disk.clear();
2847
+ this._l1Counters.clear();
2848
+ this.tagIndex.clear();
2849
+ }
2850
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2851
+ try {
2852
+ const client = await this.getRedis();
2853
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
2854
+ const keys = await this._scanKeys(client, pattern);
2855
+ if (keys.length > 0) await client.del(...keys);
2856
+ } catch (err) {
2857
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
2858
+ }
2859
+ }
2860
+ void this.publishInvalidation(
2861
+ "del-glob",
2862
+ k ?? (this._namespace ? `${this._namespace}:*` : "*")
2863
+ );
2864
+ }
2865
+ /**
2866
+ * Evict L1 entries that violate the current category or global capacity limits.
2867
+ * Useful after a write burst or after adding stricter `categoryLimits`.
2868
+ * Returns the number of entries evicted.
2869
+ */
2870
+ rebalance() {
2871
+ return this.l1.rebalance();
2872
+ }
2873
+ /**
2874
+ * Return the remaining TTL in seconds for a key currently in L1.
2875
+ * Returns null if the key is absent from L1 or has already expired.
2876
+ * Only reflects L1 state — does not query Redis or disk.
2877
+ */
2878
+ ttl(cacheKey) {
2879
+ return this.l1.ttl(this.nk(cacheKey));
2880
+ }
2881
+ /**
2882
+ * Return true if the key exists in L1 and has not expired.
2883
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
2884
+ */
2885
+ has(cacheKey) {
2886
+ return this.l1.has(this.nk(cacheKey));
2887
+ }
2888
+ // ── Iteration ─────────────────────────────────────────────────────────────
2889
+ /**
2890
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
2891
+ *
2892
+ * @example
2893
+ * for (const key of cache.keys()) console.log(key);
2894
+ */
2895
+ *keys() {
2896
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2897
+ for (const key of this.l1.liveKeys()) {
2898
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
2899
+ }
2900
+ }
2901
+ /**
2902
+ * Lazily yield every non-expired L1 value.
2903
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
2904
+ *
2905
+ * @example
2906
+ * for (const val of cache.values<User>()) console.log(val.id);
2907
+ */
2908
+ *values() {
2909
+ yield* this.l1.liveValues();
2910
+ }
2911
+ /**
2912
+ * Lazily yield every non-expired L1 [key, value] pair.
2913
+ * Keys are stripped of their namespace prefix.
2914
+ *
2915
+ * @example
2916
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2917
+ */
2918
+ *entries() {
2919
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2920
+ for (const [key, entry] of this.l1.liveEntries()) {
2921
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
2922
+ yield [k, entry.value !== void 0 ? entry.value : entry.data];
2923
+ }
2924
+ }
2925
+ /**
2926
+ * High-throughput bulk scan over all live L1 entries.
2927
+ *
2928
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
2929
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
2930
+ * caller uses the `offset` parameter instead of pre-slicing.
2931
+ *
2932
+ * ```typescript
2933
+ * // Zero extra string allocations — use rawKey + offset directly:
2934
+ * cache.scan((rawKey, value, offset) => {
2935
+ * const key = rawKey.slice(offset); // allocate only if needed
2936
+ * sync(key, value as User);
2937
+ * });
2938
+ * ```
2939
+ *
2940
+ * @param fn Called once per live L1 entry.
2941
+ * `rawKey` — key with namespace prefix still attached.
2942
+ * `value` — deserialized cached value.
2943
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
2944
+ */
2945
+ scan(fn) {
2946
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2947
+ this.l1.scan((key, entry, pfx) => {
2948
+ const value = entry.value !== void 0 ? entry.value : entry.data;
2949
+ fn(key, value, pfx);
2950
+ }, prefixLen);
2951
+ }
2952
+ /**
2953
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
2954
+ * Returns `false` if the key is absent or already expired.
2955
+ *
2956
+ * @param newTtlSeconds - The new TTL from now, in seconds.
2957
+ */
2958
+ async touch(cacheKey, newTtlSeconds) {
2959
+ const k = this.nk(cacheKey);
2960
+ const hit = this.l1.touch(k, newTtlSeconds * 1e3);
2961
+ if (hit && !this._redisDisabled) {
2962
+ try {
2963
+ const client = await this.getRedis();
2964
+ void client.expire(k, newTtlSeconds);
2965
+ } catch {
2966
+ }
2967
+ }
2968
+ return hit;
2969
+ }
2970
+ /**
2971
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
2972
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
2973
+ *
2974
+ * @example
2975
+ * const fresh = cache.getIfFresh('user:123');
2976
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
2977
+ */
2978
+ getIfFresh(cacheKey) {
2979
+ const k = this.nk(cacheKey);
2980
+ const entry = this.l1.getEntry(k);
2981
+ if (!entry) return null;
2982
+ const now = Date.now();
2983
+ if (entry.expiresAt <= now) return null;
2984
+ if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
2985
+ return entry.value !== void 0 ? entry.value : unpack3(entry.data);
2986
+ }
2987
+ /**
2988
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
2989
+ * Preserves input ordering. Uses inflight coalescing per key.
2990
+ *
2991
+ * @param keys - Array of cache keys.
2992
+ * @param fetchFn - Called with only the keys that missed L1.
2993
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
2994
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
2995
+ */
2996
+ async mget(keys, fetchFn, ttl = 300, priority) {
2997
+ const result = new Array(keys.length);
2998
+ const missIndexes = [];
2999
+ const missKeys = [];
3000
+ for (let i = 0; i < keys.length; i++) {
3001
+ const entry = this.l1.getEntry(this.nk(keys[i]));
3002
+ if (entry && entry.expiresAt > Date.now()) {
3003
+ result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
3004
+ this.counters.l1Hits++;
3005
+ } else {
3006
+ missIndexes.push(i);
3007
+ missKeys.push(keys[i]);
3008
+ }
3009
+ }
3010
+ if (missKeys.length > 0) {
3011
+ const fetched = await fetchFn(missKeys);
3012
+ for (let j = 0; j < missKeys.length; j++) {
3013
+ const v = fetched[missKeys[j]];
3014
+ result[missIndexes[j]] = v;
3015
+ if (v !== void 0) {
3016
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
3017
+ await this.set(missKeys[j], v, resolvedTtl, priority);
3018
+ }
3019
+ }
3020
+ }
3021
+ return result;
3022
+ }
3023
+ /**
3024
+ * Returns a Promise that resolves once the cache is fully initialised and any
3025
+ * startup warming configured via `warmKeys` has completed.
3026
+ *
3027
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
3028
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
3029
+ *
3030
+ * @example
3031
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
3032
+ * await cache.ready(); // gate traffic until warm
3033
+ */
3034
+ ready() {
3035
+ return this._readyPromise;
3036
+ }
3037
+ /**
3038
+ * Batch write — set multiple entries in a single call.
3039
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
3040
+ *
3041
+ * @example
3042
+ * await cache.mset({
3043
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
3044
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
3045
+ * });
3046
+ */
3047
+ async mset(entries) {
3048
+ const keys = Object.keys(entries);
3049
+ await Promise.all(keys.map((key) => {
3050
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3051
+ const hasOpts = tags?.length || dependsOn?.length;
3052
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
3053
+ }));
3054
+ }
3055
+ /**
3056
+ * Batch delete — delete multiple exact keys in a single call.
3057
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
3058
+ *
3059
+ * @example
3060
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
3061
+ */
3062
+ async mdel(keys) {
3063
+ await Promise.all(keys.map((k) => this.delete(k)));
3064
+ }
3065
+ /**
3066
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
3067
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
3068
+ * the local snapshot is unavailable or too stale.
3069
+ *
3070
+ * Returns the number of keys loaded into L1.
3071
+ *
3072
+ * @example
3073
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
3074
+ * const loaded = await cache.warmFromL2('org:*');
3075
+ * console.log(`Warmed ${loaded} keys from Redis`);
3076
+ */
3077
+ async warmFromL2(pattern, opts) {
3078
+ if (this._redisDisabled) return 0;
3079
+ try {
3080
+ const client = await this.getRedis();
3081
+ const nsPattern = this.nk(pattern);
3082
+ const matchedKeys = await this._scanKeys(client, nsPattern);
3083
+ if (matchedKeys.length === 0) {
3084
+ this.cb.onSuccess();
3085
+ return 0;
3086
+ }
3087
+ const pl = client.pipeline();
3088
+ for (const k of matchedKeys) pl.get(k);
3089
+ const results = await pl.exec();
3090
+ this.cb.onSuccess();
3091
+ let loaded = 0;
3092
+ const now = Date.now();
3093
+ for (let i = 0; i < matchedKeys.length; i++) {
3094
+ const [err, raw] = results[i];
3095
+ if (err || raw == null) continue;
3096
+ try {
3097
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3098
+ const parsed = JSON.parse(decrypted);
3099
+ const remainingMs = 10 * 60 * 1e3;
3100
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
3101
+ loaded++;
3102
+ ;
3103
+ } catch {
3104
+ }
3105
+ }
3106
+ void now;
3107
+ this.logger.info("warmFromL2 complete", {
3108
+ pattern,
3109
+ matched: matchedKeys.length,
3110
+ loaded
3111
+ });
3112
+ return loaded;
3113
+ } catch (err) {
3114
+ this.cb.onFailure();
3115
+ this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
3116
+ return 0;
3117
+ }
3118
+ }
3119
+ /**
3120
+ * Invalidate all keys associated with a tag.
3121
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
3122
+ *
3123
+ * @example
3124
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
3125
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3126
+ */
3127
+ async invalidateTag(tag) {
3128
+ const tagKey = this.nk(`_tag_:${tag}`);
3129
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
3130
+ for (const k of members) {
3131
+ this.l1.delete(k);
3132
+ if (!this._diskDisabled) this.disk.delete(k);
3133
+ }
3134
+ this.tagIndex.delete(tagKey);
3135
+ if (!this._redisDisabled) {
3136
+ try {
3137
+ const client = await this.getRedis();
3138
+ const redisMembers = await client.smembers(tagKey);
3139
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
3140
+ if (toDelete.length > 0) {
3141
+ await client.del(...toDelete, tagKey);
3142
+ } else {
3143
+ await client.del(tagKey);
3144
+ }
3145
+ } catch (err) {
3146
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
3147
+ }
3148
+ }
3149
+ }
3150
+ /**
3151
+ * Invalidate all keys associated with any of the given tags in a single operation.
3152
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
3153
+ * reducing latency when invalidating several related tags together.
3154
+ *
3155
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
3156
+ * synchronously before the Redis round-trip.
3157
+ *
3158
+ * @example
3159
+ * // Instead of three serial round-trips:
3160
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
3161
+ */
3162
+ async invalidateTags(tags) {
3163
+ if (tags.length === 0) return;
3164
+ if (tags.length === 1) {
3165
+ await this.invalidateTag(tags[0]);
3166
+ return;
3167
+ }
3168
+ const tagKeys = [];
3169
+ const allMembers = /* @__PURE__ */ new Set();
3170
+ for (const tag of tags) {
3171
+ const tagKey = this.nk(`_tag_:${tag}`);
3172
+ tagKeys.push(tagKey);
3173
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
3174
+ for (const k of members) allMembers.add(k);
3175
+ this.tagIndex.delete(tagKey);
3176
+ }
3177
+ for (const k of allMembers) {
3178
+ this.l1.delete(k);
3179
+ this.disk.delete(k);
3180
+ }
3181
+ if (!this._redisDisabled) {
3182
+ try {
3183
+ const client = await this.getRedis();
3184
+ const pl = client.pipeline();
3185
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
3186
+ const smResults = await pl.exec();
3187
+ const toDelete = [...allMembers];
3188
+ for (const [err, redisMembers] of smResults) {
3189
+ if (!err && redisMembers) {
3190
+ for (const k of redisMembers) {
3191
+ if (!allMembers.has(k)) toDelete.push(k);
3192
+ }
3193
+ }
3194
+ }
3195
+ const keysToRemove = [...toDelete, ...tagKeys];
3196
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
3197
+ } catch (err) {
3198
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
3199
+ }
3200
+ }
3201
+ }
3202
+ /**
3203
+ * Measure L1 / disk / Redis latency.
3204
+ * Useful for health checks and dashboards.
3205
+ *
3206
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
3207
+ * `l2` is `null` when Redis is disabled.
3208
+ */
3209
+ async ping() {
3210
+ const t0 = Date.now();
3211
+ this.l1.has("__ping__");
3212
+ const l1 = Date.now() - t0;
3213
+ const t1 = Date.now();
3214
+ void this.disk.stats;
3215
+ const disk = Date.now() - t1;
3216
+ let l2 = null;
3217
+ if (!this._redisDisabled) {
3218
+ try {
3219
+ const client = await this.getRedis();
3220
+ const t2 = Date.now();
3221
+ await client.ping();
3222
+ l2 = Date.now() - t2;
3223
+ } catch {
3224
+ l2 = null;
3225
+ }
3226
+ }
3227
+ return { l1, disk, l2 };
3228
+ }
3229
+ /**
3230
+ * Export all live L1 entries to Redis via a single pipeline.
3231
+ * Useful for warming a new Redis instance or for zero-downtime failover.
3232
+ * Returns the number of keys written.
3233
+ */
3234
+ async drainToL2() {
3235
+ if (this._redisDisabled) return 0;
3236
+ try {
3237
+ const client = await this.getRedis();
3238
+ const entries = this.l1.exportEntries([]);
3239
+ const now = Date.now();
3240
+ if (entries.length === 0) return 0;
3241
+ const pl = client.pipeline();
3242
+ for (const { key, entry } of entries) {
3243
+ const remainingMs = entry.expiresAt - now;
3244
+ if (remainingMs <= 0) continue;
3245
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
3246
+ const s = JSON.stringify(entry.value);
3247
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
3248
+ pl.setex(key, ttlSecs, stored);
3249
+ }
3250
+ await pl.exec();
3251
+ return entries.length;
3252
+ } catch (err) {
3253
+ this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
3254
+ return 0;
3255
+ }
3256
+ }
3257
+ // ── Stats ─────────────────────────────────────────────────────────────
3258
+ stats() {
3259
+ return {
3260
+ l1: this.l1.getStats(),
3261
+ disk: this.disk.stats
3262
+ };
3263
+ }
3264
+ // ── Conditional write ─────────────────────────────────────────────────
3265
+ /**
3266
+ * Write `value` only if the key is not already cached.
3267
+ * Returns `true` if the write happened, `false` if the key already existed.
3268
+ *
3269
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
3270
+ * is safe to use for idempotency keys and "first writer wins" patterns across
3271
+ * multiple instances. L1 is populated on success.
3272
+ *
3273
+ * @example
3274
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
3275
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
3276
+ */
3277
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
3278
+ const k = this.nk(cacheKey);
3279
+ if (this.l1.has(k)) return false;
3280
+ if (!this._redisDisabled) {
3281
+ try {
3282
+ const client = await this.getRedis();
3283
+ const serialized = JSON.stringify(value);
3284
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3285
+ const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
3286
+ this.cb.onSuccess();
3287
+ if (result === null) return false;
3288
+ } catch (err) {
3289
+ this.cb.onFailure();
3290
+ this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
3291
+ if (this.l1.has(k)) return false;
3292
+ }
3293
+ }
3294
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3295
+ const p = priority ?? inferPriority(cacheKey);
3296
+ this.l1.set(k, value, ttlMs, p);
3297
+ this.counters.sets++;
3298
+ return true;
3299
+ }
3300
+ // ── Hot key introspection ─────────────────────────────────────────────
3301
+ /**
3302
+ * Return the top-N live L1 keys by historical access frequency.
3303
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
3304
+ * whose historical frequency exceeds their current in-memory hit count.
3305
+ *
3306
+ * Useful for diagnosing what is driving L1 pressure without any extra data
3307
+ * collection overhead.
3308
+ *
3309
+ * @param n - Maximum number of keys to return. Default: 10.
3310
+ *
3311
+ * @example
3312
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
3313
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
3314
+ */
3315
+ hotKeys(n = 10) {
3316
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3317
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
3318
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
3319
+ hits,
3320
+ sizeBytes
3321
+ }));
3322
+ }
3323
+ // ── Dependency cascade helpers ────────────────────────────────────────
3324
+ /**
3325
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
3326
+ * pattern that may contain `*` wildcards).
3327
+ */
3328
+ _matchesGlob(key, pattern) {
3329
+ if (!pattern.includes("*")) return key === pattern;
3330
+ const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
3331
+ return re.test(key);
3332
+ }
3333
+ /**
3334
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
3335
+ * that was registered via `dependsOn` and whose source pattern matches.
3336
+ */
3337
+ _cascadeDependencies(deletedKey) {
3338
+ for (const [pattern, dependents] of this.dependencyIndex) {
3339
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
3340
+ for (const dep of dependents) {
3341
+ if (dep === deletedKey) continue;
3342
+ this.l1.delete(dep);
3343
+ if (!this._diskDisabled) this.disk.delete(dep);
3344
+ void this.publishInvalidation("del", dep);
3345
+ this.logger.debug("Dependency cascade: invalidated dependent key", {
3346
+ trigger: deletedKey.slice(0, 60),
3347
+ dependent: dep.slice(0, 60)
3348
+ });
3349
+ }
3350
+ }
3351
+ }
3352
+ // ── Observability ──────────────────────────────────────────────────────────────────
3353
+ /** Return a full metrics snapshot. */
3354
+ metrics() {
3355
+ const c = this.counters;
3356
+ const l1s = this.l1.getStats();
3357
+ const div = (n, d) => d > 0 ? n / d : 0;
3358
+ return {
3359
+ namespace: this.opts.namespace,
3360
+ uptimeMs: Date.now() - c.startedAt,
3361
+ gets: {
3362
+ total: c.gets,
3363
+ l1Hits: c.l1Hits,
3364
+ l1HitRate: div(c.l1Hits, c.gets),
3365
+ diskHits: c.diskHits,
3366
+ diskHitRate: div(c.diskHits, c.gets),
3367
+ l2Hits: c.l2Hits,
3368
+ l2HitRate: div(c.l2Hits, c.gets),
3369
+ fetches: c.fetches,
3370
+ fetchRate: div(c.fetches, c.gets),
3371
+ stampedePrevented: c.stampedes
3372
+ },
3373
+ sets: { total: c.sets },
3374
+ deletes: { total: c.deletes },
3375
+ revalidations: { total: c.swrRevalidations },
3376
+ bloom: {
3377
+ checksTotal: l1s.bloom.checks,
3378
+ falsePositives: l1s.bloom.falsePositives,
3379
+ falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks)
3380
+ },
3381
+ compression: {
3382
+ entriesCompressed: l1s.compression.compressed,
3383
+ entriesUncompressed: l1s.compression.uncompressed,
3384
+ bytesSaved: l1s.compression.bytesSaved
3385
+ },
3386
+ backplane: {
3387
+ enabled: this.opts.invalidationBackplane && !this._redisDisabled,
3388
+ sent: c.invSent,
3389
+ received: c.invReceived,
3390
+ skipped: c.invSkipped
3391
+ },
3392
+ l2CircuitBreaker: {
3393
+ state: this.cb.currentState
3394
+ },
3395
+ oom: {
3396
+ enabled: this.opts.oomProtection,
3397
+ evictions: c.oomEvictions,
3398
+ lastTriggeredAt: c.oomLastAt
3399
+ },
3400
+ l1: {
3401
+ entries: l1s.entries,
3402
+ sizeBytes: this.l1.memoryUsage,
3403
+ maxBytes: this.opts.l1MaxBytes
3404
+ },
3405
+ disk: { ...this.disk.stats, disabled: this._diskDisabled },
3406
+ ...this.latencyTracker && {
3407
+ adaptiveTtl: {
3408
+ enabled: true,
3409
+ trackedKeys: this.latencyTracker.trackedKeys,
3410
+ slowestKeys: this.latencyTracker.snapshot(
3411
+ this._namespace ? this._namespace.length + 1 : 0,
3412
+ // strip "namespace:" prefix
3413
+ this.opts.adaptiveTtlMultiplier,
3414
+ this.opts.adaptiveTtlMinMs,
3415
+ this.opts.adaptiveTtlMaxMs
3416
+ )
3417
+ }
3418
+ }
3419
+ };
3420
+ }
3421
+ /**
3422
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
3423
+ * Paste the result into your `/metrics` endpoint.
3424
+ *
3425
+ * @param m - Snapshot returned by `cache.metrics()`
3426
+ * @param prefix - Metric name prefix. Default: `"tricache"`
3427
+ */
3428
+ static toPrometheusText(m, prefix = "tricache", instanceName) {
3429
+ const parts = [];
3430
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
3431
+ if (instanceName) parts.push(`instance="${instanceName}"`);
3432
+ const lbl = parts.length ? `{${parts.join(",")}}` : "";
3433
+ const lines = [];
3434
+ const counter = (name, val, help) => {
3435
+ lines.push(`# HELP ${prefix}_${name}_total ${help}`);
3436
+ lines.push(`# TYPE ${prefix}_${name}_total counter`);
3437
+ lines.push(`${prefix}_${name}_total${lbl} ${val}`);
3438
+ };
3439
+ const gauge = (name, val, help) => {
3440
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
3441
+ lines.push(`# TYPE ${prefix}_${name} gauge`);
3442
+ lines.push(`${prefix}_${name}${lbl} ${val}`);
3443
+ };
3444
+ counter("gets", m.gets.total, "Total get() calls");
3445
+ counter("l1_hits", m.gets.l1Hits, "L1 RAM cache hits");
3446
+ counter("disk_hits", m.gets.diskHits, "L1.5 disk tier hits");
3447
+ counter("l2_hits", m.gets.l2Hits, "L2 Redis hits");
3448
+ counter("fetches", m.gets.fetches, "fetchFn calls (cache misses)");
3449
+ counter("stampedes_prevented", m.gets.stampedePrevented, "Coalesced duplicate inflight requests");
3450
+ counter("sets", m.sets.total, "Total set() calls");
3451
+ counter("deletes", m.deletes.total, "Total delete() calls");
3452
+ counter("swr_revalidations", m.revalidations.total, "Stale-While-Revalidate background refreshes");
3453
+ gauge("l1_hit_rate", m.gets.l1HitRate, "Fraction of gets served from L1 RAM (0-1)");
3454
+ gauge("disk_hit_rate", m.gets.diskHitRate, "Fraction of gets served from disk (0-1)");
3455
+ gauge("l2_hit_rate", m.gets.l2HitRate, "Fraction of gets served from Redis (0-1)");
3456
+ gauge("fetch_rate", m.gets.fetchRate, "Fraction of gets calling fetchFn (0-1)");
3457
+ gauge("l1_entries", m.l1.entries, "Current L1 entry count");
3458
+ gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
3459
+ gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
3460
+ gauge(
3461
+ "bloom_false_positive_rate",
3462
+ m.bloom.falsePositiveRate,
3463
+ "Bloom filter false-positive rate; increase capacity if > 0.01"
3464
+ );
3465
+ gauge(
3466
+ "compression_bytes_saved",
3467
+ m.compression.bytesSaved,
3468
+ "Approximate bytes saved by msgpackr compression"
3469
+ );
3470
+ if (m.backplane.enabled) {
3471
+ counter("backplane_sent", m.backplane.sent, "Invalidation messages sent via Pub/Sub");
3472
+ counter("backplane_received", m.backplane.received, "Invalidation messages received from peers");
3473
+ }
3474
+ if (m.oom.enabled) {
3475
+ counter(
3476
+ "oom_evictions",
3477
+ m.oom.evictions,
3478
+ "Emergency L1 eviction rounds triggered by heap pressure"
3479
+ );
3480
+ }
3481
+ return lines.join("\n");
3482
+ }
3483
+ // ── Lifecycle ────────────────────────────────────────────────────────────
3484
+ /** Close Redis connections and stop all background timers. */
3485
+ async destroy() {
3486
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3487
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
3488
+ if (this.oomInterval) clearInterval(this.oomInterval);
3489
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
3490
+ if (this._shutdownHandler) {
3491
+ process.off("SIGTERM", this._shutdownHandler);
3492
+ process.off("SIGINT", this._shutdownHandler);
3493
+ this._shutdownHandler = null;
3494
+ }
3495
+ if (this._workerPool) {
3496
+ await this._workerPool.destroy();
3497
+ this._workerPool = null;
3498
+ }
3499
+ if (this.subClient) {
3500
+ try {
3501
+ await this.subClient.quit();
3502
+ } catch {
3503
+ }
3504
+ this.subClient = null;
3505
+ }
3506
+ if (this.redis) {
3507
+ try {
3508
+ await this.redis.disconnect();
3509
+ } catch {
3510
+ }
3511
+ this.redis = null;
3512
+ }
3513
+ if (!this._diskDisabled) this.disk.close();
3514
+ }
3515
+ };
3516
+ export {
3517
+ CacheEncryption,
3518
+ CachePriority,
3519
+ CacheService,
3520
+ DiskTier,
3521
+ SmartMemoryCache,
3522
+ WasmBloomFilter,
3523
+ consoleLogger
3524
+ };