tricache 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1784 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CacheEncryption: () => CacheEncryption,
34
+ CachePriority: () => CachePriority,
35
+ CacheService: () => CacheService,
36
+ DiskTier: () => DiskTier,
37
+ SmartMemoryCache: () => SmartMemoryCache,
38
+ WasmBloomFilter: () => WasmBloomFilter,
39
+ consoleLogger: () => consoleLogger
40
+ });
41
+ module.exports = __toCommonJS(index_exports);
42
+
43
+ // src/cache-service.ts
44
+ var import_ioredis = require("ioredis");
45
+ var import_crypto3 = __toESM(require("crypto"), 1);
46
+ var import_os = __toESM(require("os"), 1);
47
+ var import_fs2 = __toESM(require("fs"), 1);
48
+ var import_path2 = __toESM(require("path"), 1);
49
+ var import_msgpackr3 = require("msgpackr");
50
+
51
+ // src/types.ts
52
+ var consoleLogger = {
53
+ debug: (msg, meta) => {
54
+ },
55
+ info: (msg, meta) => console.info("[tricache]", msg, meta ?? ""),
56
+ warn: (msg, meta) => console.warn("[tricache]", msg, meta ?? ""),
57
+ error: (msg, meta, err) => console.error("[tricache]", msg, meta ?? "", err ?? "")
58
+ };
59
+ var CachePriority = /* @__PURE__ */ ((CachePriority2) => {
60
+ CachePriority2[CachePriority2["LOW"] = 1] = "LOW";
61
+ CachePriority2[CachePriority2["NORMAL"] = 2] = "NORMAL";
62
+ CachePriority2[CachePriority2["HIGH"] = 3] = "HIGH";
63
+ CachePriority2[CachePriority2["CRITICAL"] = 4] = "CRITICAL";
64
+ return CachePriority2;
65
+ })(CachePriority || {});
66
+
67
+ // src/encryption.ts
68
+ var import_crypto = require("crypto");
69
+ var IV_BYTES = 12;
70
+ var TAG_BYTES = 16;
71
+ var PREFIX_256 = "enc:v1:";
72
+ var PREFIX_128 = "a128:v1:";
73
+ var PREFIX_XOR = "xor:v1:";
74
+ var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
75
+ var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
76
+ var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
77
+ var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
78
+ var MAGIC_LEN = 8;
79
+ var CTR_IV_BYTES = 16;
80
+ var PREFIX_CTR = "ctr:v1:";
81
+ var IV_POOL_COUNT = 64;
82
+ var CacheEncryption = class {
83
+ _key = null;
84
+ _mode;
85
+ // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
86
+ _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
87
+ _ivOffset = IV_BYTES * IV_POOL_COUNT;
88
+ // start exhausted → fill on first use
89
+ /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
90
+ _nextIV() {
91
+ if (this._ivOffset >= this._ivPool.length) {
92
+ (0, import_crypto.randomFillSync)(this._ivPool);
93
+ this._ivOffset = 0;
94
+ }
95
+ const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES);
96
+ this._ivOffset += IV_BYTES;
97
+ return iv;
98
+ }
99
+ // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
100
+ _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
101
+ _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
102
+ /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
103
+ _nextCtrIV() {
104
+ if (this._ctrIvOffset >= this._ctrIvPool.length) {
105
+ (0, import_crypto.randomFillSync)(this._ctrIvPool);
106
+ this._ctrIvOffset = 0;
107
+ }
108
+ const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
109
+ this._ctrIvOffset += CTR_IV_BYTES;
110
+ return iv;
111
+ }
112
+ /**
113
+ * XOR `data` with the key, cycling through key bytes.
114
+ * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
115
+ *
116
+ * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
117
+ * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
118
+ * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
119
+ * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
120
+ *
121
+ * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
122
+ */
123
+ _xorBuffer(data) {
124
+ const key = this._key;
125
+ const klen = key.length;
126
+ const len = data.length;
127
+ const out = Buffer.allocUnsafe(len);
128
+ if (klen % 4 === 0 && len >= 4 && data.byteOffset % 4 === 0 && out.byteOffset % 4 === 0 && key.byteOffset % 4 === 0) {
129
+ const wordCount = len >>> 2;
130
+ const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
131
+ const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
132
+ const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
133
+ const kLen32 = key32.length;
134
+ for (let i = 0; i < wordCount; i++) {
135
+ out32[i] = data32[i] ^ key32[i % kLen32];
136
+ }
137
+ for (let i = wordCount << 2; i < len; i++) {
138
+ out[i] = data[i] ^ key[i % klen];
139
+ }
140
+ return out;
141
+ }
142
+ for (let i = 0; i < len; i++) {
143
+ out[i] = data[i] ^ key[i % klen];
144
+ }
145
+ return out;
146
+ }
147
+ constructor(keyBase64, logger, mode = "aes-256-gcm") {
148
+ this._mode = mode;
149
+ if (!keyBase64) {
150
+ if (process.env.NODE_ENV === "production") {
151
+ logger.warn(
152
+ "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
153
+ { hint: "Set encryptionKey option or CACHE_ENCRYPTION_KEY env var" }
154
+ );
155
+ }
156
+ return;
157
+ }
158
+ try {
159
+ const buf = Buffer.from(keyBase64, "base64");
160
+ const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
161
+ if (requiredLen > 0 && buf.length !== requiredLen) {
162
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
163
+ }
164
+ if (buf.length < 1) {
165
+ throw new Error("XOR key must be at least 1 byte");
166
+ }
167
+ this._key = buf;
168
+ if (mode === "xor") {
169
+ logger.warn(
170
+ "Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
171
+ );
172
+ } else {
173
+ logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
174
+ }
175
+ } catch (err) {
176
+ logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
177
+ }
178
+ }
179
+ get isEnabled() {
180
+ return this._key !== null;
181
+ }
182
+ // ── String (Redis) ────────────────────────────────────────────────────────
183
+ /**
184
+ * Encrypt a string for Redis storage.
185
+ * Returns a mode-prefixed base64 string when a key is configured;
186
+ * otherwise returns the original string unchanged (backward-compatible).
187
+ */
188
+ encrypt(plaintext) {
189
+ if (!this._key) return plaintext;
190
+ if (this._mode === "xor") {
191
+ const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
192
+ return PREFIX_XOR + masked.toString("base64");
193
+ }
194
+ if (this._mode === "aes-128-ctr") {
195
+ const iv2 = this._nextCtrIV();
196
+ const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
197
+ const enc2 = c2.update(plaintext, "utf8");
198
+ c2.final();
199
+ const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length);
200
+ iv2.copy(out2, 0);
201
+ enc2.copy(out2, CTR_IV_BYTES);
202
+ return PREFIX_CTR + out2.toString("base64");
203
+ }
204
+ const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
205
+ const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
206
+ const iv = this._nextIV();
207
+ const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
208
+ const enc = c.update(plaintext, "utf8");
209
+ c.final();
210
+ const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
211
+ iv.copy(out, 0);
212
+ c.getAuthTag().copy(out, IV_BYTES);
213
+ enc.copy(out, IV_BYTES + TAG_BYTES);
214
+ return prefix + out.toString("base64");
215
+ }
216
+ /**
217
+ * Decrypt a Redis value.
218
+ * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
219
+ */
220
+ decrypt(value) {
221
+ if (value.startsWith(PREFIX_XOR)) {
222
+ if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
223
+ const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
224
+ return this._xorBuffer(masked).toString("utf8");
225
+ }
226
+ if (value.startsWith(PREFIX_CTR)) {
227
+ if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
228
+ const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
229
+ const iv2 = combined2.subarray(0, CTR_IV_BYTES);
230
+ const ct2 = combined2.subarray(CTR_IV_BYTES);
231
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", this._key, iv2);
232
+ const plain2 = d2.update(ct2);
233
+ d2.final();
234
+ return plain2.toString("utf8");
235
+ }
236
+ const is256 = value.startsWith(PREFIX_256);
237
+ const is128 = value.startsWith(PREFIX_128);
238
+ if (!is256 && !is128) return value;
239
+ if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
240
+ const prefix = is128 ? PREFIX_128 : PREFIX_256;
241
+ const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
242
+ const combined = Buffer.from(value.slice(prefix.length), "base64");
243
+ const iv = combined.subarray(0, IV_BYTES);
244
+ const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
245
+ const ct = combined.subarray(IV_BYTES + TAG_BYTES);
246
+ const d = (0, import_crypto.createDecipheriv)(algo, this._key, iv);
247
+ d.setAuthTag(tag);
248
+ const plain = d.update(ct);
249
+ d.final();
250
+ return plain.toString("utf8");
251
+ }
252
+ // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
253
+ /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
254
+ encryptBuffer(data) {
255
+ if (!this._key) return data;
256
+ if (this._mode === "xor") {
257
+ const masked = this._xorBuffer(data);
258
+ const out2 = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
259
+ MAGIC_XOR.copy(out2, 0);
260
+ masked.copy(out2, MAGIC_LEN);
261
+ return out2;
262
+ }
263
+ if (this._mode === "aes-128-ctr") {
264
+ const iv2 = this._nextCtrIV();
265
+ const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
266
+ const enc2 = c2.update(data);
267
+ c2.final();
268
+ const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length);
269
+ MAGIC_CTR.copy(out2, 0);
270
+ iv2.copy(out2, MAGIC_LEN);
271
+ enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
272
+ return out2;
273
+ }
274
+ const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
275
+ const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
276
+ const iv = this._nextIV();
277
+ const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
278
+ const enc = c.update(data);
279
+ c.final();
280
+ const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
281
+ magic.copy(out, 0);
282
+ iv.copy(out, MAGIC_LEN);
283
+ c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
284
+ enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
285
+ return out;
286
+ }
287
+ /**
288
+ * Decrypt a raw Buffer from disk/snapshot.
289
+ * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
290
+ */
291
+ decryptBuffer(data) {
292
+ if (data.length < MAGIC_LEN) return data;
293
+ const magic = data.subarray(0, MAGIC_LEN);
294
+ if (magic.equals(MAGIC_XOR)) {
295
+ if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
296
+ return this._xorBuffer(data.subarray(MAGIC_LEN));
297
+ }
298
+ if (magic.equals(MAGIC_CTR)) {
299
+ if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
300
+ const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
301
+ const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
302
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", this._key, iv2);
303
+ const plain2 = d2.update(ct2);
304
+ d2.final();
305
+ return plain2;
306
+ }
307
+ const is256 = magic.equals(MAGIC_256);
308
+ const is128 = magic.equals(MAGIC_128);
309
+ if (!is256 && !is128) return data;
310
+ if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
311
+ const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
312
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
313
+ const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
314
+ const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
315
+ const d = (0, import_crypto.createDecipheriv)(algo, this._key, iv);
316
+ d.setAuthTag(tag);
317
+ const plain = d.update(ct);
318
+ d.final();
319
+ return plain;
320
+ }
321
+ };
322
+
323
+ // src/smart-memory-cache.ts
324
+ var import_msgpackr = require("msgpackr");
325
+
326
+ // src/wasm/bloom-filter-wasm.ts
327
+ var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
328
+ var KEY_STAGING_OFFSET = 2e4;
329
+ var MAX_KEY_BYTES = 512;
330
+ function instantiateSync() {
331
+ const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, "base64");
332
+ const compiled = new WebAssembly.Module(wasmBytes);
333
+ return new WebAssembly.Instance(compiled, {});
334
+ }
335
+ var WasmBloomFilter = class {
336
+ exports;
337
+ mem;
338
+ encoder = new TextEncoder();
339
+ numBits = 1e5;
340
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
341
+ _maxCapacity;
342
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
343
+ _insertionCount = 0;
344
+ constructor() {
345
+ const instance = instantiateSync();
346
+ this.exports = instance.exports;
347
+ this.mem = new Uint8Array(this.exports.memory.buffer);
348
+ const k = 7, p = 0.01;
349
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
350
+ }
351
+ writeKey(key) {
352
+ const max = Math.min(key.length, MAX_KEY_BYTES);
353
+ if (max === 0) return 0;
354
+ for (let i = 0; i < max; i++) {
355
+ const c = key.charCodeAt(i);
356
+ if (c > 127) {
357
+ const encoded = this.encoder.encode(key);
358
+ const len = Math.min(encoded.length, MAX_KEY_BYTES);
359
+ this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
360
+ return len;
361
+ }
362
+ this.mem[KEY_STAGING_OFFSET + i] = c;
363
+ }
364
+ return max;
365
+ }
366
+ add(key) {
367
+ const len = this.writeKey(key);
368
+ if (len === 0) return;
369
+ this.exports.add(KEY_STAGING_OFFSET, len);
370
+ this._insertionCount++;
371
+ }
372
+ mightContain(key) {
373
+ const len = this.writeKey(key);
374
+ if (len === 0) return true;
375
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
376
+ }
377
+ reset() {
378
+ this.exports.reset();
379
+ this._insertionCount = 0;
380
+ }
381
+ rebuild(keys) {
382
+ this.reset();
383
+ for (const key of keys) this.add(key);
384
+ }
385
+ get stats() {
386
+ const bitsSet = this.exports.countBits();
387
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
388
+ }
389
+ /** Number of add() calls since last reset/rebuild. */
390
+ get insertions() {
391
+ return this._insertionCount;
392
+ }
393
+ /**
394
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
395
+ * Exact formula for k=7 hash rounds, m=100 000 bits:
396
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
397
+ */
398
+ get maxCapacity() {
399
+ return this._maxCapacity;
400
+ }
401
+ };
402
+
403
+ // src/smart-memory-cache.ts
404
+ var EVICTION_BATCH_PERCENT = 0.2;
405
+ var JsBloomFilter = class {
406
+ bits;
407
+ numBits;
408
+ k;
409
+ /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
410
+ _maxCapacity;
411
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
412
+ _insertionCount = 0;
413
+ constructor(numBits = 1e5, k = 7) {
414
+ this.numBits = numBits;
415
+ this.k = k;
416
+ this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
417
+ const p = 0.01;
418
+ this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
419
+ }
420
+ fnv1a32(s) {
421
+ let h = 2166136261;
422
+ for (let i = 0; i < s.length; i++) {
423
+ h ^= s.charCodeAt(i);
424
+ h = Math.imul(h, 16777619) >>> 0;
425
+ }
426
+ return h >>> 0;
427
+ }
428
+ djb2(s) {
429
+ let h = 5381;
430
+ for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) >>> 0;
431
+ return h >>> 0;
432
+ }
433
+ setBit(i) {
434
+ this.bits[i >>> 3] |= 1 << (i & 7);
435
+ }
436
+ getBit(i) {
437
+ return (this.bits[i >>> 3] & 1 << (i & 7)) !== 0;
438
+ }
439
+ add(key) {
440
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
441
+ for (let i = 0; i < this.k; i++) this.setBit((h1 + i * h2 >>> 0) % this.numBits);
442
+ this._insertionCount++;
443
+ }
444
+ mightContain(key) {
445
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
446
+ for (let i = 0; i < this.k; i++) if (!this.getBit((h1 + i * h2 >>> 0) % this.numBits)) return false;
447
+ return true;
448
+ }
449
+ reset() {
450
+ this.bits.fill(0);
451
+ this._insertionCount = 0;
452
+ }
453
+ rebuild(keys) {
454
+ this.bits.fill(0);
455
+ this._insertionCount = 0;
456
+ for (const k of keys) this.add(k);
457
+ }
458
+ /** Number of add() calls since last reset/rebuild. */
459
+ get insertions() {
460
+ return this._insertionCount;
461
+ }
462
+ /**
463
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
464
+ * Exact formula for the configured k and target p=1 %:
465
+ * n_max = -m * ln(1 - p^(1/k)) / k
466
+ */
467
+ get maxCapacity() {
468
+ return this._maxCapacity;
469
+ }
470
+ get stats() {
471
+ let bitsSet = 0;
472
+ for (const byte of this.bits) {
473
+ let b = byte;
474
+ while (b) {
475
+ bitsSet++;
476
+ b &= b - 1;
477
+ }
478
+ }
479
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
480
+ }
481
+ };
482
+ function createBloomFilter(logger) {
483
+ try {
484
+ const wasm = new WasmBloomFilter();
485
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
486
+ return wasm;
487
+ } catch (err) {
488
+ logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
489
+ return new JsBloomFilter();
490
+ }
491
+ }
492
+ var SmartMemoryCache = class {
493
+ cache = /* @__PURE__ */ new Map();
494
+ opts;
495
+ bloom;
496
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
497
+ categoryPrefixes;
498
+ totalSize = 0;
499
+ categoryCount = /* @__PURE__ */ new Map();
500
+ categorySize = /* @__PURE__ */ new Map();
501
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
502
+ categoryKeys = /* @__PURE__ */ new Map();
503
+ // ── Observability counters ──────────────────────────────────────────────────────
504
+ bloomChecks = 0;
505
+ bloomFalsePos = 0;
506
+ compressions = 0;
507
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
508
+ _bloomDirtyCount = 0;
509
+ constructor(opts, existing) {
510
+ this.opts = opts;
511
+ this.bloom = createBloomFilter(opts.logger);
512
+ this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
513
+ if (existing) {
514
+ for (const [k, v] of existing) this.cache.set(k, v);
515
+ this.recalculateStats();
516
+ for (const key of this.cache.keys()) this.bloom.add(key);
517
+ }
518
+ }
519
+ // ── Internal helpers ──────────────────────────────────────────────────────
520
+ recalculateStats() {
521
+ this.totalSize = 0;
522
+ this.categoryCount.clear();
523
+ this.categorySize.clear();
524
+ this.categoryKeys.clear();
525
+ for (const [key, entry] of this.cache) {
526
+ this.totalSize += entry.size;
527
+ const cat = this.getCategory(key);
528
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
529
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
530
+ let ks = this.categoryKeys.get(cat);
531
+ if (!ks) {
532
+ ks = /* @__PURE__ */ new Set();
533
+ this.categoryKeys.set(cat, ks);
534
+ }
535
+ ks.add(key);
536
+ }
537
+ }
538
+ getCategory(key) {
539
+ for (const prefix of this.categoryPrefixes) {
540
+ if (key.startsWith(prefix)) return prefix;
541
+ }
542
+ return "default";
543
+ }
544
+ getCategoryLimit(cat) {
545
+ return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
546
+ }
547
+ _delete(key) {
548
+ const entry = this.cache.get(key);
549
+ if (!entry) return false;
550
+ const cat = this.getCategory(key);
551
+ this.totalSize -= entry.size;
552
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
553
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
554
+ this.categoryKeys.get(cat)?.delete(key);
555
+ this._bloomDirtyCount++;
556
+ return this.cache.delete(key);
557
+ }
558
+ ensureCapacity(category, neededSize) {
559
+ const lim = this.getCategoryLimit(category);
560
+ const catCnt = this.categoryCount.get(category) ?? 0;
561
+ const catSz = this.categorySize.get(category) ?? 0;
562
+ const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
563
+ const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
564
+ if (!catOvf && !glbOvf) return;
565
+ this.smartEvict(category, catOvf);
566
+ }
567
+ score(entry, catBonus, now) {
568
+ const age = now - entry.lastAccess;
569
+ const ttl = Math.max(0, entry.expiresAt - now);
570
+ const freq = Math.min(entry.hits, 100);
571
+ return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
572
+ }
573
+ /**
574
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
575
+ * saturated the filter past its ~1 % FP capacity.
576
+ *
577
+ * Trigger: (insertions − live entries) > maxCapacity
578
+ *
579
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
580
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
581
+ * cache holds more entries than the filter's rated capacity — which would
582
+ * stall the write path entirely.
583
+ *
584
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
585
+ */
586
+ maybeRebuildBloom() {
587
+ if (this._bloomDirtyCount > this.bloom.maxCapacity >>> 2 || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
588
+ this.bloom.rebuild(this.cache.keys());
589
+ this._bloomDirtyCount = 0;
590
+ }
591
+ }
592
+ smartEvict(targetCat, catOvf) {
593
+ const now = Date.now();
594
+ const SAMPLE = 16;
595
+ const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT));
596
+ const pool = [];
597
+ if (catOvf) {
598
+ const catKeySet = this.categoryKeys.get(targetCat);
599
+ if (catKeySet) {
600
+ let catSeen = 0;
601
+ for (const key of catKeySet) {
602
+ const entry = this.cache.get(key);
603
+ if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
604
+ catSeen++;
605
+ const s = this.score(entry, 100, now);
606
+ if (pool.length < EVICT) {
607
+ pool.push({ key, score: s });
608
+ } else {
609
+ const j = Math.floor(Math.random() * catSeen);
610
+ if (j < EVICT) pool[j] = { key, score: s };
611
+ }
612
+ }
613
+ }
614
+ }
615
+ if (pool.length < EVICT) {
616
+ const remaining = SAMPLE - pool.length;
617
+ let globalSeen = 0;
618
+ const globalPool = [];
619
+ for (const [key, entry] of this.cache) {
620
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
621
+ if (catOvf && this.getCategory(key) === targetCat) continue;
622
+ globalSeen++;
623
+ const s = this.score(entry, 0, now);
624
+ if (globalPool.length < remaining) {
625
+ globalPool.push({ key, score: s });
626
+ } else {
627
+ const j = Math.floor(Math.random() * globalSeen);
628
+ if (j < remaining) globalPool[j] = { key, score: s };
629
+ }
630
+ }
631
+ pool.push(...globalPool);
632
+ }
633
+ if (pool.length === 0) return;
634
+ pool.sort((a, b) => a.score - b.score);
635
+ for (const { key } of pool.slice(0, EVICT)) {
636
+ const entry = this.cache.get(key);
637
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
638
+ this._delete(key);
639
+ }
640
+ }
641
+ // ── Public API ────────────────────────────────────────────────────────────
642
+ get(key) {
643
+ this.bloomChecks++;
644
+ if (!this.bloom.mightContain(key)) return null;
645
+ const entry = this.cache.get(key);
646
+ if (!entry) {
647
+ this.bloomFalsePos++;
648
+ return null;
649
+ }
650
+ const now = Date.now();
651
+ if (entry.expiresAt < now) {
652
+ this._delete(key);
653
+ return null;
654
+ }
655
+ entry.hits++;
656
+ entry.lastAccess = now;
657
+ const value = (0, import_msgpackr.unpack)(entry.data);
658
+ const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
659
+ return { value, isStale };
660
+ }
661
+ set(key, data, ttlMs, priority = 2, staleAt) {
662
+ const packed = (0, import_msgpackr.pack)(data);
663
+ const size = packed.byteLength;
664
+ this.compressions++;
665
+ const cat = this.getCategory(key);
666
+ const lim = this.getCategoryLimit(cat);
667
+ if (size > lim.maxSizeBytes * 0.5) {
668
+ this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
669
+ return;
670
+ }
671
+ const existingEntry = this.cache.get(key);
672
+ if (existingEntry) {
673
+ this.totalSize -= existingEntry.size;
674
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
675
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
676
+ this.cache.delete(key);
677
+ }
678
+ this.ensureCapacity(cat, size);
679
+ const now = Date.now();
680
+ this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
681
+ this.bloom.add(key);
682
+ this.maybeRebuildBloom();
683
+ this.totalSize += size;
684
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
685
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
686
+ let ks = this.categoryKeys.get(cat);
687
+ if (!ks) {
688
+ ks = /* @__PURE__ */ new Set();
689
+ this.categoryKeys.set(cat, ks);
690
+ }
691
+ ks.add(key);
692
+ }
693
+ delete(key) {
694
+ const deleted = this._delete(key);
695
+ if (deleted) this.maybeRebuildBloom();
696
+ return deleted;
697
+ }
698
+ keysMatchingPattern(pattern) {
699
+ if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
700
+ const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
701
+ const out = [];
702
+ for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
703
+ return out;
704
+ }
705
+ deletePattern(pattern) {
706
+ let n = 0;
707
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
708
+ if (n > 0) this.maybeRebuildBloom();
709
+ return n;
710
+ }
711
+ /**
712
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
713
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
714
+ * exceeds the configured threshold.
715
+ *
716
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
717
+ * @returns Number of entries evicted
718
+ */
719
+ evictPercentage(pct) {
720
+ if (pct <= 0 || this.cache.size === 0) return 0;
721
+ const now = Date.now();
722
+ const candidates = [];
723
+ for (const [key, entry] of this.cache) {
724
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
725
+ candidates.push({ key, score: this.score(entry, 0, now) });
726
+ }
727
+ candidates.sort((a, b) => a.score - b.score);
728
+ const count = Math.max(1, Math.ceil(candidates.length * pct));
729
+ let evicted = 0;
730
+ for (const { key } of candidates.slice(0, count)) {
731
+ const entry = this.cache.get(key);
732
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
733
+ this._delete(key);
734
+ evicted++;
735
+ }
736
+ return evicted;
737
+ }
738
+ cleanup() {
739
+ const now = Date.now();
740
+ let cleaned = 0;
741
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
742
+ this._delete(key);
743
+ cleaned++;
744
+ }
745
+ if (cleaned > 0) {
746
+ this.bloom.rebuild(this.cache.keys());
747
+ this._bloomDirtyCount = 0;
748
+ }
749
+ return cleaned;
750
+ }
751
+ // ── Snapshot import/export ────────────────────────────────────────────────
752
+ exportEntries(forbiddenPrefixes) {
753
+ const now = Date.now();
754
+ const out = [];
755
+ for (const [key, entry] of this.cache) {
756
+ if (entry.expiresAt <= now) continue;
757
+ if (entry.priority === 4) continue;
758
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
759
+ out.push({ key, entry: { ...entry } });
760
+ }
761
+ return out;
762
+ }
763
+ importEntries(entries, forbiddenPrefixes) {
764
+ const now = Date.now();
765
+ let loaded = 0;
766
+ for (const { key, entry } of entries) {
767
+ if (entry.expiresAt <= now) continue;
768
+ if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
769
+ if (this.cache.has(key)) continue;
770
+ const rawData = entry.data;
771
+ const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
772
+ this.cache.set(key, { ...entry, data, isCompressed: true });
773
+ this.bloom.add(key);
774
+ loaded++;
775
+ }
776
+ this.recalculateStats();
777
+ return loaded;
778
+ }
779
+ // ── Stats ─────────────────────────────────────────────────────────────────
780
+ get size() {
781
+ return this.cache.size;
782
+ }
783
+ get memoryUsage() {
784
+ return this.totalSize;
785
+ }
786
+ getStats() {
787
+ const categories = {};
788
+ for (const [cat, cnt] of this.categoryCount) categories[cat] = cnt;
789
+ return {
790
+ entries: this.cache.size,
791
+ sizeKB: Math.round(this.totalSize / 1024),
792
+ categories,
793
+ bloom: {
794
+ checks: this.bloomChecks,
795
+ falsePositives: this.bloomFalsePos
796
+ },
797
+ compression: {
798
+ compressed: this.compressions,
799
+ uncompressed: 0,
800
+ // all entries are now msgpackr-packed
801
+ bytesSaved: 0
802
+ // no longer tracked (unified format removes the split path)
803
+ }
804
+ };
805
+ }
806
+ bloomMightContain(key) {
807
+ return this.bloom.mightContain(key);
808
+ }
809
+ bloomStats() {
810
+ return this.bloom.stats;
811
+ }
812
+ };
813
+
814
+ // src/disk-tier.ts
815
+ var import_fs = __toESM(require("fs"), 1);
816
+ var import_path = __toESM(require("path"), 1);
817
+ var import_crypto2 = __toESM(require("crypto"), 1);
818
+ var import_msgpackr2 = require("msgpackr");
819
+ var AES_ALGO = "aes-256-gcm";
820
+ var IV_BYTES2 = 12;
821
+ var TAG_BYTES2 = 16;
822
+ var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
823
+ var DISK_TIER_VERSION = 1;
824
+ var DiskTier = class {
825
+ opts;
826
+ dirReady = false;
827
+ diskUsageBytes = 0;
828
+ usageCounted = false;
829
+ fileCount = 0;
830
+ // maintained in-memory; avoids walkCacheFiles() in stats
831
+ constructor(opts) {
832
+ this.opts = opts;
833
+ }
834
+ // ── Helpers ───────────────────────────────────────────────────────────────
835
+ ensureDir() {
836
+ if (this.dirReady) return;
837
+ try {
838
+ import_fs.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
839
+ this.dirReady = true;
840
+ } catch (err) {
841
+ this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
842
+ }
843
+ }
844
+ ensureUsageCounted() {
845
+ if (this.usageCounted) return;
846
+ this.usageCounted = true;
847
+ try {
848
+ this.ensureDir();
849
+ let total = 0;
850
+ const files = this.walkCacheFiles();
851
+ this.fileCount = files.length;
852
+ for (const filePath of files) {
853
+ try {
854
+ total += import_fs.default.statSync(filePath).size;
855
+ } catch {
856
+ }
857
+ }
858
+ this.diskUsageBytes = total;
859
+ } catch {
860
+ this.diskUsageBytes = 0;
861
+ this.fileCount = 0;
862
+ }
863
+ }
864
+ /**
865
+ * Map a cache key to its on-disk path.
866
+ *
867
+ * Files are sharded into two-character hex prefix subdirectories to avoid
868
+ * putting thousands of flat files into a single directory node — which
869
+ * degrades EXT4/NTFS performance at scale.
870
+ *
871
+ * key → SHA-256 hex e3b0c442...
872
+ * path → {dir}/e3/e3b0c442...
873
+ */
874
+ keyToPath(key) {
875
+ const hash = import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
876
+ return import_path.default.join(this.opts.dir, hash.slice(0, 2), hash);
877
+ }
878
+ /**
879
+ * Recursively list all cache file paths across the 2-level sharded subdirs.
880
+ * Top-level entries that are not directories are skipped (e.g. stale flat
881
+ * files written by older versions).
882
+ */
883
+ walkCacheFiles() {
884
+ const results = [];
885
+ let topEntries;
886
+ try {
887
+ topEntries = import_fs.default.readdirSync(this.opts.dir);
888
+ } catch {
889
+ return results;
890
+ }
891
+ for (const top of topEntries) {
892
+ const topPath = import_path.default.join(this.opts.dir, top);
893
+ try {
894
+ if (!import_fs.default.statSync(topPath).isDirectory()) continue;
895
+ for (const file of import_fs.default.readdirSync(topPath)) {
896
+ results.push(import_path.default.join(topPath, file));
897
+ }
898
+ } catch {
899
+ }
900
+ }
901
+ return results;
902
+ }
903
+ isForbidden(key) {
904
+ return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
905
+ }
906
+ encrypt(data) {
907
+ const key = this.opts.encryptionKey;
908
+ if (!key) return data;
909
+ const iv = import_crypto2.default.randomBytes(IV_BYTES2);
910
+ const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
911
+ const enc = Buffer.concat([c.update(data), c.final()]);
912
+ const tag = c.getAuthTag();
913
+ return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
914
+ }
915
+ decrypt(data) {
916
+ const mLen = DISK_MAGIC.length;
917
+ if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
918
+ const key = this.opts.encryptionKey;
919
+ if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
920
+ const iv = data.subarray(mLen, mLen + IV_BYTES2);
921
+ const tag = data.subarray(mLen + IV_BYTES2, mLen + IV_BYTES2 + TAG_BYTES2);
922
+ const ct = data.subarray(mLen + IV_BYTES2 + TAG_BYTES2);
923
+ const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
924
+ d.setAuthTag(tag);
925
+ return Buffer.concat([d.update(ct), d.final()]);
926
+ }
927
+ // ── Public API ────────────────────────────────────────────────────────────
928
+ /**
929
+ * Spill an evicted L1 entry to disk.
930
+ *
931
+ * Returns a Promise that resolves when the file is durably written. Callers
932
+ * that treat the spill as fire-and-forget should do:
933
+ * `void disk.save(key, entry)`
934
+ *
935
+ * Implementation notes:
936
+ * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
937
+ * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
938
+ * on any external resource.
939
+ * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
940
+ * so the Node.js event loop is never stalled waiting for disk I/O.
941
+ */
942
+ async save(key, entry) {
943
+ if (this.isForbidden(key)) return;
944
+ if (entry.expiresAt <= Date.now()) return;
945
+ this.ensureDir();
946
+ if (!this.dirReady) return;
947
+ this.ensureUsageCounted();
948
+ if (this.diskUsageBytes >= this.opts.maxBytes) return;
949
+ let final;
950
+ try {
951
+ const payload = {
952
+ version: DISK_TIER_VERSION,
953
+ key,
954
+ entry: {
955
+ ...entry,
956
+ data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
957
+ },
958
+ writtenAt: Date.now()
959
+ };
960
+ const packed = (0, import_msgpackr2.pack)(payload);
961
+ if (packed.length > this.opts.entryMaxBytes) return;
962
+ final = this.encrypt(packed);
963
+ } catch (err) {
964
+ this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
965
+ return;
966
+ }
967
+ const filePath = this.keyToPath(key);
968
+ this.diskUsageBytes += final.length;
969
+ this.fileCount++;
970
+ try {
971
+ await import_fs.default.promises.mkdir(import_path.default.dirname(filePath), { recursive: true });
972
+ await import_fs.default.promises.writeFile(filePath, final, { mode: 384 });
973
+ this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
974
+ } catch (err) {
975
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
976
+ this.fileCount = Math.max(0, this.fileCount - 1);
977
+ this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
978
+ }
979
+ }
980
+ /** Load a key from disk, or return null on miss/expiry/corruption. */
981
+ load(key) {
982
+ if (this.isForbidden(key)) return null;
983
+ this.ensureDir();
984
+ if (!this.dirReady) return null;
985
+ const filePath = this.keyToPath(key);
986
+ try {
987
+ if (!import_fs.default.existsSync(filePath)) return null;
988
+ const stat = import_fs.default.statSync(filePath);
989
+ if (stat.size > this.opts.entryMaxBytes) {
990
+ import_fs.default.unlinkSync(filePath);
991
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
992
+ return null;
993
+ }
994
+ const raw = import_fs.default.readFileSync(filePath);
995
+ try {
996
+ import_fs.default.unlinkSync(filePath);
997
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
998
+ this.fileCount = Math.max(0, this.fileCount - 1);
999
+ } catch {
1000
+ }
1001
+ let decrypted;
1002
+ try {
1003
+ decrypted = this.decrypt(raw);
1004
+ } catch {
1005
+ return null;
1006
+ }
1007
+ const payload = (0, import_msgpackr2.unpack)(decrypted);
1008
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1009
+ if (payload.entry.expiresAt <= Date.now()) return null;
1010
+ const entry = payload.entry;
1011
+ if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
1012
+ this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1013
+ return entry;
1014
+ } catch (err) {
1015
+ this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1016
+ return null;
1017
+ }
1018
+ }
1019
+ /** Explicitly delete a key from disk (cache invalidation). */
1020
+ delete(key) {
1021
+ const filePath = this.keyToPath(key);
1022
+ try {
1023
+ if (import_fs.default.existsSync(filePath)) {
1024
+ const stat = import_fs.default.statSync(filePath);
1025
+ import_fs.default.unlinkSync(filePath);
1026
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1027
+ this.fileCount = Math.max(0, this.fileCount - 1);
1028
+ }
1029
+ } catch {
1030
+ }
1031
+ }
1032
+ /** Purge all expired entries. Returns number deleted. */
1033
+ purgeExpired() {
1034
+ this.ensureDir();
1035
+ if (!this.dirReady) return 0;
1036
+ let purged = 0;
1037
+ for (const filePath of this.walkCacheFiles()) {
1038
+ try {
1039
+ const stat = import_fs.default.statSync(filePath);
1040
+ if (stat.size > this.opts.entryMaxBytes) {
1041
+ import_fs.default.unlinkSync(filePath);
1042
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1043
+ this.fileCount = Math.max(0, this.fileCount - 1);
1044
+ purged++;
1045
+ continue;
1046
+ }
1047
+ const raw = import_fs.default.readFileSync(filePath);
1048
+ let dec;
1049
+ try {
1050
+ dec = this.decrypt(raw);
1051
+ } catch {
1052
+ import_fs.default.unlinkSync(filePath);
1053
+ this.fileCount = Math.max(0, this.fileCount - 1);
1054
+ purged++;
1055
+ continue;
1056
+ }
1057
+ const payload = (0, import_msgpackr2.unpack)(dec);
1058
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
1059
+ import_fs.default.unlinkSync(filePath);
1060
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1061
+ this.fileCount = Math.max(0, this.fileCount - 1);
1062
+ purged++;
1063
+ }
1064
+ } catch {
1065
+ }
1066
+ }
1067
+ return purged;
1068
+ }
1069
+ get stats() {
1070
+ return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1071
+ }
1072
+ };
1073
+
1074
+ // src/cache-service.ts
1075
+ var SNAPSHOT_VERSION = 1;
1076
+ var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
1077
+ var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
1078
+ var DEFAULT_CATEGORY_LIMITS = {
1079
+ "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1080
+ };
1081
+ var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1082
+ function inferPriority(cacheKey) {
1083
+ if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1084
+ if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
1085
+ if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
1086
+ return 2 /* NORMAL */;
1087
+ }
1088
+ var GLOBAL_KEY = "__tricache_instance__";
1089
+ var CacheService = class _CacheService {
1090
+ logger;
1091
+ enc;
1092
+ l1;
1093
+ disk;
1094
+ opts;
1095
+ /** Pre-computed once — opts.namespace never changes after construction. */
1096
+ _namespace;
1097
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
1098
+ _redisDisabled;
1099
+ inflight = /* @__PURE__ */ new Map();
1100
+ revalidating = /* @__PURE__ */ new Set();
1101
+ redis = null;
1102
+ redisConnecting = null;
1103
+ snapshotLoaded = false;
1104
+ cleanupInterval = null;
1105
+ oomInterval = null;
1106
+ metricsInterval = null;
1107
+ _shutdownHandler = null;
1108
+ instanceId;
1109
+ backplaneChannel;
1110
+ subClient = null;
1111
+ counters = {
1112
+ gets: 0,
1113
+ l1Hits: 0,
1114
+ diskHits: 0,
1115
+ l2Hits: 0,
1116
+ fetches: 0,
1117
+ stampedes: 0,
1118
+ sets: 0,
1119
+ deletes: 0,
1120
+ swrRevalidations: 0,
1121
+ invSent: 0,
1122
+ invReceived: 0,
1123
+ invSkipped: 0,
1124
+ oomEvictions: 0,
1125
+ oomLastAt: null,
1126
+ startedAt: Date.now()
1127
+ };
1128
+ // ── Constructor (use CacheService.create() for the recommended singleton) ──
1129
+ constructor(options = {}) {
1130
+ const logger = options.logger ?? consoleLogger;
1131
+ this.logger = logger;
1132
+ const ns = options.namespace?.trim() ?? "";
1133
+ const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
1134
+ this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode);
1135
+ const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
1136
+ const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
1137
+ this.opts = {
1138
+ namespace: ns,
1139
+ logger,
1140
+ l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
1141
+ l1MaxEntries: options.l1MaxEntries ?? 2e3,
1142
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits ?? {} },
1143
+ forbiddenSnapshotPrefixes: forbiddenPrefixes,
1144
+ // Namespace-isolated defaults: separate dir / snapshot per namespace so
1145
+ // two instances with different namespaces never share cache files.
1146
+ diskCacheDir: options.diskCacheDir ?? import_path2.default.join(
1147
+ import_os.default.tmpdir(),
1148
+ ns ? `tricache-disk-${ns}` : "tricache-disk"
1149
+ ),
1150
+ diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
1151
+ diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
1152
+ redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
1153
+ redisPort: options.redisPort ?? 6379,
1154
+ redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
1155
+ disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
1156
+ encryptionKey: encKeyRaw,
1157
+ snapshotPath: options.snapshotPath ?? import_path2.default.join(
1158
+ import_os.default.tmpdir(),
1159
+ ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
1160
+ ),
1161
+ snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
1162
+ invalidationBackplane: options.invalidationBackplane ?? true,
1163
+ oomProtection: options.oomProtection ?? true,
1164
+ oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
1165
+ oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
1166
+ oomEvictPercent: options.oomEvictPercent ?? 0.2,
1167
+ onMetrics: options.onMetrics,
1168
+ metricsIntervalMs: options.metricsIntervalMs ?? 6e4
1169
+ };
1170
+ this.disk = new DiskTier({
1171
+ dir: this.opts.diskCacheDir,
1172
+ maxBytes: this.opts.diskMaxBytes,
1173
+ entryMaxBytes: this.opts.diskEntryMaxBytes,
1174
+ forbiddenPrefixes,
1175
+ encryptionKey: this.enc.isEnabled ? this.enc["_key"] : null,
1176
+ logger
1177
+ });
1178
+ this._namespace = ns;
1179
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost;
1180
+ this.l1 = new SmartMemoryCache({
1181
+ maxBytes: this.opts.l1MaxBytes,
1182
+ maxEntries: this.opts.l1MaxEntries,
1183
+ categories: this.opts.categoryLimits,
1184
+ diskSpill: (key, entry) => {
1185
+ void this.disk.save(key, entry);
1186
+ },
1187
+ logger
1188
+ });
1189
+ if (!this.snapshotLoaded) {
1190
+ this.snapshotLoaded = true;
1191
+ this.loadSnapshot();
1192
+ }
1193
+ this._shutdownHandler = () => {
1194
+ this.writeSnapshot();
1195
+ process.exit(0);
1196
+ };
1197
+ process.once("SIGTERM", this._shutdownHandler);
1198
+ process.once("SIGINT", this._shutdownHandler);
1199
+ this.cleanupInterval = setInterval(() => {
1200
+ const cleaned = this.l1.cleanup();
1201
+ const diskPurged = this.disk.purgeExpired();
1202
+ if (cleaned > 0 || diskPurged > 0) {
1203
+ this.logger.debug("Periodic cache cleanup", { cleaned, diskPurged });
1204
+ }
1205
+ }, 5 * 60 * 1e3);
1206
+ if (this.cleanupInterval.unref) this.cleanupInterval.unref();
1207
+ if (this.opts.oomProtection) {
1208
+ this.oomInterval = setInterval(() => {
1209
+ const mem = process.memoryUsage();
1210
+ const used = mem.heapUsed / mem.heapTotal;
1211
+ if (used >= this.opts.oomHeapThreshold) {
1212
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
1213
+ this.counters.oomEvictions++;
1214
+ this.counters.oomLastAt = Date.now();
1215
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
1216
+ heapUsedPct: Math.round(used * 100),
1217
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
1218
+ evicted
1219
+ });
1220
+ }
1221
+ }, this.opts.oomCheckIntervalMs);
1222
+ if (this.oomInterval.unref) this.oomInterval.unref();
1223
+ }
1224
+ if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
1225
+ this.metricsInterval = setInterval(() => {
1226
+ try {
1227
+ this.opts.onMetrics(this.metrics());
1228
+ } catch {
1229
+ }
1230
+ }, this.opts.metricsIntervalMs);
1231
+ if (this.metricsInterval.unref) this.metricsInterval.unref();
1232
+ }
1233
+ this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
1234
+ this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
1235
+ this.initBackplane();
1236
+ }
1237
+ // ── Singleton factory ─────────────────────────────────────────────────────
1238
+ /**
1239
+ * Get (or create) the process-level singleton CacheService instance.
1240
+ *
1241
+ * Options are only applied on first call — subsequent calls return the
1242
+ * existing instance regardless of options passed.
1243
+ *
1244
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
1245
+ * with different namespaces return independent instances.
1246
+ */
1247
+ static create(options) {
1248
+ const g = globalThis;
1249
+ const key = _CacheService.globalKey(options);
1250
+ if (!g[key]) g[key] = new _CacheService(options);
1251
+ return g[key];
1252
+ }
1253
+ /** Replace the singleton (useful in tests). */
1254
+ static reset(options) {
1255
+ const g = globalThis;
1256
+ const key = _CacheService.globalKey(options);
1257
+ const existing = g[key];
1258
+ if (existing) existing.destroy();
1259
+ g[key] = new _CacheService(options);
1260
+ return g[key];
1261
+ }
1262
+ /** Derive the globalThis key for a given set of options. */
1263
+ static globalKey(options) {
1264
+ const ns = options?.namespace?.trim() ?? "";
1265
+ return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
1266
+ }
1267
+ // ── Redis connection ──────────────────────────────────────────────────────
1268
+ /**
1269
+ * Prepend the configured namespace to a raw cache key.
1270
+ * Returns the key unchanged when namespace is empty.
1271
+ *
1272
+ * This is the only place the namespace prefix is applied — callers always
1273
+ * receive and provide un-prefixed keys in the public API.
1274
+ */
1275
+ nk(key) {
1276
+ return this._namespace ? `${this._namespace}:${key}` : key;
1277
+ }
1278
+ initBackplane() {
1279
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1280
+ if (this.subClient) return;
1281
+ const sub = new import_ioredis.Redis({
1282
+ host: this.opts.redisHost,
1283
+ port: this.opts.redisPort,
1284
+ tls: this.opts.redisTls ? {} : void 0,
1285
+ connectTimeout: 1e4,
1286
+ lazyConnect: true,
1287
+ maxRetriesPerRequest: null,
1288
+ enableAutoPipelining: false,
1289
+ family: 4,
1290
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
1291
+ });
1292
+ sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
1293
+ sub.on("message", (_channel, message) => {
1294
+ try {
1295
+ const msg = JSON.parse(message);
1296
+ if (msg.src === this.instanceId) {
1297
+ this.counters.invSkipped++;
1298
+ return;
1299
+ }
1300
+ this.counters.invReceived++;
1301
+ if (msg.op === "del") {
1302
+ this.l1.delete(msg.key);
1303
+ this.disk.delete(msg.key);
1304
+ } else if (msg.op === "del-glob") {
1305
+ this.l1.deletePattern(msg.key);
1306
+ }
1307
+ this.logger.debug("Backplane: peer invalidation applied", {
1308
+ op: msg.op,
1309
+ key: msg.key.slice(0, 60)
1310
+ });
1311
+ } catch {
1312
+ }
1313
+ });
1314
+ sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
1315
+ channel: this.backplaneChannel,
1316
+ instanceId: this.instanceId
1317
+ })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
1318
+ error: err.message
1319
+ }));
1320
+ this.subClient = sub;
1321
+ }
1322
+ async publishInvalidation(op, key) {
1323
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1324
+ try {
1325
+ const client = await this.getRedis();
1326
+ await client.publish(
1327
+ this.backplaneChannel,
1328
+ JSON.stringify({ op, key, src: this.instanceId })
1329
+ );
1330
+ this.counters.invSent++;
1331
+ } catch {
1332
+ }
1333
+ }
1334
+ async getRedis() {
1335
+ if (this.redis?.status === "ready") return this.redis;
1336
+ if (this.redisConnecting) return this.redisConnecting;
1337
+ this.redisConnecting = (async () => {
1338
+ const client = new import_ioredis.Redis({
1339
+ host: this.opts.redisHost,
1340
+ port: this.opts.redisPort,
1341
+ tls: this.opts.redisTls ? {} : void 0,
1342
+ connectTimeout: 1e4,
1343
+ lazyConnect: false,
1344
+ maxRetriesPerRequest: 3,
1345
+ enableAutoPipelining: true,
1346
+ keepAlive: 3e4,
1347
+ family: 4,
1348
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
1349
+ });
1350
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
1351
+ client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
1352
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
1353
+ await new Promise((resolve, reject) => {
1354
+ client.once("ready", resolve);
1355
+ client.once("error", reject);
1356
+ setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1357
+ });
1358
+ this.redis = client;
1359
+ this.redisConnecting = null;
1360
+ return client;
1361
+ })();
1362
+ return this.redisConnecting;
1363
+ }
1364
+ // ── Snapshot (cold-start persistence) ────────────────────────────────────
1365
+ writeSnapshot() {
1366
+ try {
1367
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
1368
+ if (entries.length === 0) return;
1369
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
1370
+ const packed = (0, import_msgpackr3.pack)(payload);
1371
+ const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1372
+ import_fs2.default.writeFileSync(this.opts.snapshotPath, final, { mode: 384 });
1373
+ this.logger.info("Cache snapshot written", {
1374
+ path: this.opts.snapshotPath,
1375
+ entries: entries.length,
1376
+ sizeKB: Math.round(final.length / 1024),
1377
+ encrypted: this.enc.isEnabled
1378
+ });
1379
+ } catch (err) {
1380
+ this.logger.warn("Cache snapshot write failed", { error: err.message });
1381
+ }
1382
+ }
1383
+ loadSnapshot() {
1384
+ const snapshotPath = this.opts.snapshotPath;
1385
+ try {
1386
+ if (!import_fs2.default.existsSync(snapshotPath)) return;
1387
+ const stat = import_fs2.default.statSync(snapshotPath);
1388
+ if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
1389
+ this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
1390
+ import_fs2.default.unlinkSync(snapshotPath);
1391
+ return;
1392
+ }
1393
+ const raw = import_fs2.default.readFileSync(snapshotPath);
1394
+ import_fs2.default.unlinkSync(snapshotPath);
1395
+ let buf;
1396
+ try {
1397
+ buf = this.enc.decryptBuffer(raw);
1398
+ } catch (e) {
1399
+ this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
1400
+ return;
1401
+ }
1402
+ const snapshot = (0, import_msgpackr3.unpack)(buf);
1403
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
1404
+ this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
1405
+ return;
1406
+ }
1407
+ const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
1408
+ if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
1409
+ this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
1410
+ return;
1411
+ }
1412
+ if (!Array.isArray(snapshot.entries)) {
1413
+ this.logger.warn("Snapshot rejected: entries is not an array");
1414
+ return;
1415
+ }
1416
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
1417
+ this.logger.info("Cache snapshot loaded (L1 is warm)", {
1418
+ loaded,
1419
+ total: snapshot.entries.length,
1420
+ sizeKB: this.l1.getStats().sizeKB
1421
+ });
1422
+ } catch (err) {
1423
+ this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
1424
+ try {
1425
+ import_fs2.default.unlinkSync(snapshotPath);
1426
+ } catch {
1427
+ }
1428
+ }
1429
+ }
1430
+ // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
1431
+ /**
1432
+ * Get a value from cache, or fetch and cache it.
1433
+ *
1434
+ * @param cacheKey - Unique key identifying this value
1435
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
1436
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1437
+ * @param opts.priority - Override the auto-inferred eviction priority
1438
+ * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
1439
+ * alive for this many extra seconds after TTL; callers get stale data
1440
+ * instantly while a background refresh runs. Default: 0 (disabled).
1441
+ */
1442
+ async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1443
+ const k = this.nk(cacheKey);
1444
+ this.counters.gets++;
1445
+ const l1Hit = this.l1.get(k);
1446
+ if (l1Hit !== null) {
1447
+ if (l1Hit.isStale) {
1448
+ const swrGraceMs2 = (opts.swr ?? 0) * 1e3;
1449
+ if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
1450
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1451
+ this.revalidating.add(k);
1452
+ void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
1453
+ this.counters.swrRevalidations++;
1454
+ this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
1455
+ } else {
1456
+ this.logger.debug("L1 hit");
1457
+ }
1458
+ } else {
1459
+ this.logger.debug("L1 hit");
1460
+ }
1461
+ this.counters.l1Hits++;
1462
+ return l1Hit.value;
1463
+ }
1464
+ const ttlMs = ttlSeconds * 1e3;
1465
+ const swrGraceMs = (opts.swr ?? 0) * 1e3;
1466
+ const priority = opts.priority ?? inferPriority(cacheKey);
1467
+ if (!this._redisDisabled) {
1468
+ try {
1469
+ const client = await this.getRedis();
1470
+ const raw = await client.get(k);
1471
+ if (raw) {
1472
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1473
+ const parsed = JSON.parse(decrypted);
1474
+ this.l1.set(k, parsed, ttlMs, priority);
1475
+ this.counters.l2Hits++;
1476
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
1477
+ return parsed;
1478
+ }
1479
+ } catch (err) {
1480
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
1481
+ }
1482
+ }
1483
+ const diskHit = this.disk.load(k);
1484
+ if (diskHit !== null) {
1485
+ const promoted = this.l1.importEntries(
1486
+ [{ key: k, entry: diskHit }],
1487
+ this.opts.forbiddenSnapshotPrefixes
1488
+ );
1489
+ if (promoted > 0) {
1490
+ const l1Check = this.l1.get(k);
1491
+ if (l1Check !== null) {
1492
+ this.counters.diskHits++;
1493
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1494
+ return l1Check.value;
1495
+ }
1496
+ }
1497
+ }
1498
+ const existing = this.inflight.get(k);
1499
+ if (existing) {
1500
+ this.counters.stampedes++;
1501
+ this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
1502
+ return existing;
1503
+ }
1504
+ const fetchPromise = (async () => {
1505
+ try {
1506
+ this.counters.fetches++;
1507
+ const data = await fetchFn();
1508
+ const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : void 0;
1509
+ const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
1510
+ this.l1.set(k, data, storeTtl, priority, staleAt);
1511
+ if (!this._redisDisabled) {
1512
+ try {
1513
+ const client = await this.getRedis();
1514
+ const serialized = JSON.stringify(data);
1515
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1516
+ await client.setex(k, ttlSeconds, toStore);
1517
+ this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1518
+ } catch {
1519
+ this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
1520
+ }
1521
+ } else {
1522
+ this.logger.debug("Cached L1", { cacheKey });
1523
+ }
1524
+ return data;
1525
+ } finally {
1526
+ this.inflight.delete(k);
1527
+ }
1528
+ })();
1529
+ this.inflight.set(k, fetchPromise);
1530
+ return fetchPromise;
1531
+ }
1532
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
1533
+ try {
1534
+ const data = await fetchFn();
1535
+ const staleAt = Date.now() + ttlMs;
1536
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1537
+ if (!this._redisDisabled) {
1538
+ try {
1539
+ const client = await this.getRedis();
1540
+ const s = JSON.stringify(data);
1541
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1542
+ await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
1543
+ } catch {
1544
+ }
1545
+ }
1546
+ this.logger.debug("SWR: revalidation complete", { cacheKey });
1547
+ } catch (err) {
1548
+ this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
1549
+ } finally {
1550
+ this.revalidating.delete(cacheKey);
1551
+ }
1552
+ }
1553
+ // ── Explicit set / delete ─────────────────────────────────────────────────
1554
+ /** Explicitly write a value into L1 (+ L2 in production). */
1555
+ async set(cacheKey, data, ttlSeconds = 300, priority) {
1556
+ const ttlMs = ttlSeconds * 1e3;
1557
+ const p = priority ?? inferPriority(cacheKey);
1558
+ const k = this.nk(cacheKey);
1559
+ this.counters.sets++;
1560
+ this.l1.set(k, data, ttlMs, p);
1561
+ if (!this._redisDisabled) {
1562
+ try {
1563
+ const client = await this.getRedis();
1564
+ const s = JSON.stringify(data);
1565
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1566
+ await client.setex(k, ttlSeconds, stored);
1567
+ } catch (err) {
1568
+ this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
1569
+ }
1570
+ }
1571
+ void this.publishInvalidation("del", k);
1572
+ }
1573
+ /**
1574
+ * Delete one key or a glob pattern (supports `*` wildcard).
1575
+ *
1576
+ * @example
1577
+ * await cache.delete('user:abc:profile'); // exact key
1578
+ * await cache.delete('user:abc:*'); // all keys for user abc
1579
+ */
1580
+ async delete(cacheKey) {
1581
+ const isPattern = cacheKey.includes("*");
1582
+ const k = this.nk(cacheKey);
1583
+ this.counters.deletes++;
1584
+ if (isPattern) {
1585
+ this.l1.deletePattern(k);
1586
+ } else {
1587
+ this.l1.delete(k);
1588
+ this.disk.delete(k);
1589
+ }
1590
+ if (!this._redisDisabled) {
1591
+ try {
1592
+ const client = await this.getRedis();
1593
+ if (isPattern) {
1594
+ const stream = client.scanStream({ match: k, count: 100 });
1595
+ const keys = [];
1596
+ await new Promise((resolve, reject) => {
1597
+ stream.on("data", (chunk) => keys.push(...chunk));
1598
+ stream.on("end", resolve);
1599
+ stream.on("error", reject);
1600
+ });
1601
+ if (keys.length > 0) await client.del(...keys);
1602
+ } else {
1603
+ await client.del(k);
1604
+ }
1605
+ } catch (err) {
1606
+ this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
1607
+ }
1608
+ }
1609
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
1610
+ }
1611
+ // ── Counter (distributed rate limiting) ──────────────────────────────────
1612
+ /**
1613
+ * Atomically increment a counter in Redis. Returns the new value.
1614
+ * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
1615
+ */
1616
+ async increment(cacheKey, ttlSeconds) {
1617
+ if (this._redisDisabled) return 0;
1618
+ const k = this.nk(cacheKey);
1619
+ try {
1620
+ const client = await this.getRedis();
1621
+ const count = await client.incr(k);
1622
+ if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
1623
+ return count;
1624
+ } catch (err) {
1625
+ this.logger.error("increment: Redis error", { cacheKey }, err);
1626
+ return 0;
1627
+ }
1628
+ }
1629
+ // ── Stats ─────────────────────────────────────────────────────────────────
1630
+ stats() {
1631
+ return {
1632
+ l1: this.l1.getStats(),
1633
+ disk: this.disk.stats
1634
+ };
1635
+ }
1636
+ // ── Observability ──────────────────────────────────────────────────────────────────
1637
+ /** Return a full metrics snapshot. */
1638
+ metrics() {
1639
+ const c = this.counters;
1640
+ const l1s = this.l1.getStats();
1641
+ const div = (n, d) => d > 0 ? n / d : 0;
1642
+ return {
1643
+ namespace: this.opts.namespace,
1644
+ uptimeMs: Date.now() - c.startedAt,
1645
+ gets: {
1646
+ total: c.gets,
1647
+ l1Hits: c.l1Hits,
1648
+ l1HitRate: div(c.l1Hits, c.gets),
1649
+ diskHits: c.diskHits,
1650
+ diskHitRate: div(c.diskHits, c.gets),
1651
+ l2Hits: c.l2Hits,
1652
+ l2HitRate: div(c.l2Hits, c.gets),
1653
+ fetches: c.fetches,
1654
+ fetchRate: div(c.fetches, c.gets),
1655
+ stampedePrevented: c.stampedes
1656
+ },
1657
+ sets: { total: c.sets },
1658
+ deletes: { total: c.deletes },
1659
+ revalidations: { total: c.swrRevalidations },
1660
+ bloom: {
1661
+ checksTotal: l1s.bloom.checks,
1662
+ falsePositives: l1s.bloom.falsePositives,
1663
+ falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks)
1664
+ },
1665
+ compression: {
1666
+ entriesCompressed: l1s.compression.compressed,
1667
+ entriesUncompressed: l1s.compression.uncompressed,
1668
+ bytesSaved: l1s.compression.bytesSaved
1669
+ },
1670
+ backplane: {
1671
+ enabled: this.opts.invalidationBackplane && !this._redisDisabled,
1672
+ sent: c.invSent,
1673
+ received: c.invReceived,
1674
+ skipped: c.invSkipped
1675
+ },
1676
+ oom: {
1677
+ enabled: this.opts.oomProtection,
1678
+ evictions: c.oomEvictions,
1679
+ lastTriggeredAt: c.oomLastAt
1680
+ },
1681
+ l1: {
1682
+ entries: l1s.entries,
1683
+ sizeBytes: this.l1.memoryUsage,
1684
+ maxBytes: this.opts.l1MaxBytes
1685
+ },
1686
+ disk: this.disk.stats
1687
+ };
1688
+ }
1689
+ /**
1690
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
1691
+ * Paste the result into your `/metrics` endpoint.
1692
+ *
1693
+ * @param m - Snapshot returned by `cache.metrics()`
1694
+ * @param prefix - Metric name prefix. Default: `"tricache"`
1695
+ */
1696
+ static toPrometheusText(m, prefix = "tricache") {
1697
+ const lbl = m.namespace ? `{namespace="${m.namespace}"}` : "";
1698
+ const lines = [];
1699
+ const counter = (name, val, help) => {
1700
+ lines.push(`# HELP ${prefix}_${name}_total ${help}`);
1701
+ lines.push(`# TYPE ${prefix}_${name}_total counter`);
1702
+ lines.push(`${prefix}_${name}_total${lbl} ${val}`);
1703
+ };
1704
+ const gauge = (name, val, help) => {
1705
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
1706
+ lines.push(`# TYPE ${prefix}_${name} gauge`);
1707
+ lines.push(`${prefix}_${name}${lbl} ${val}`);
1708
+ };
1709
+ counter("gets", m.gets.total, "Total get() calls");
1710
+ counter("l1_hits", m.gets.l1Hits, "L1 RAM cache hits");
1711
+ counter("disk_hits", m.gets.diskHits, "L1.5 disk tier hits");
1712
+ counter("l2_hits", m.gets.l2Hits, "L2 Redis hits");
1713
+ counter("fetches", m.gets.fetches, "fetchFn calls (cache misses)");
1714
+ counter("stampedes_prevented", m.gets.stampedePrevented, "Coalesced duplicate inflight requests");
1715
+ counter("sets", m.sets.total, "Total set() calls");
1716
+ counter("deletes", m.deletes.total, "Total delete() calls");
1717
+ counter("swr_revalidations", m.revalidations.total, "Stale-While-Revalidate background refreshes");
1718
+ gauge("l1_hit_rate", m.gets.l1HitRate, "Fraction of gets served from L1 RAM (0-1)");
1719
+ gauge("disk_hit_rate", m.gets.diskHitRate, "Fraction of gets served from disk (0-1)");
1720
+ gauge("l2_hit_rate", m.gets.l2HitRate, "Fraction of gets served from Redis (0-1)");
1721
+ gauge("fetch_rate", m.gets.fetchRate, "Fraction of gets calling fetchFn (0-1)");
1722
+ gauge("l1_entries", m.l1.entries, "Current L1 entry count");
1723
+ gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
1724
+ gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
1725
+ gauge(
1726
+ "bloom_false_positive_rate",
1727
+ m.bloom.falsePositiveRate,
1728
+ "Bloom filter false-positive rate; increase capacity if > 0.01"
1729
+ );
1730
+ gauge(
1731
+ "compression_bytes_saved",
1732
+ m.compression.bytesSaved,
1733
+ "Approximate bytes saved by msgpackr compression"
1734
+ );
1735
+ if (m.backplane.enabled) {
1736
+ counter("backplane_sent", m.backplane.sent, "Invalidation messages sent via Pub/Sub");
1737
+ counter("backplane_received", m.backplane.received, "Invalidation messages received from peers");
1738
+ }
1739
+ if (m.oom.enabled) {
1740
+ counter(
1741
+ "oom_evictions",
1742
+ m.oom.evictions,
1743
+ "Emergency L1 eviction rounds triggered by heap pressure"
1744
+ );
1745
+ }
1746
+ return lines.join("\n");
1747
+ }
1748
+ // ── Lifecycle ────────────────────────────────────────────────────────────
1749
+ /** Close Redis connections and stop all background timers. */
1750
+ async destroy() {
1751
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
1752
+ if (this.oomInterval) clearInterval(this.oomInterval);
1753
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
1754
+ if (this._shutdownHandler) {
1755
+ process.off("SIGTERM", this._shutdownHandler);
1756
+ process.off("SIGINT", this._shutdownHandler);
1757
+ this._shutdownHandler = null;
1758
+ }
1759
+ if (this.subClient) {
1760
+ try {
1761
+ await this.subClient.quit();
1762
+ } catch {
1763
+ }
1764
+ this.subClient = null;
1765
+ }
1766
+ if (this.redis) {
1767
+ try {
1768
+ await this.redis.disconnect();
1769
+ } catch {
1770
+ }
1771
+ this.redis = null;
1772
+ }
1773
+ }
1774
+ };
1775
+ // Annotate the CommonJS export names for ESM import in node:
1776
+ 0 && (module.exports = {
1777
+ CacheEncryption,
1778
+ CachePriority,
1779
+ CacheService,
1780
+ DiskTier,
1781
+ SmartMemoryCache,
1782
+ WasmBloomFilter,
1783
+ consoleLogger
1784
+ });