tricache 0.1.0 → 0.3.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/README.md +248 -57
- package/dist/index.cjs +709 -87
- package/dist/index.d.cts +253 -8
- package/dist/index.d.ts +253 -8
- package/dist/index.js +709 -87
- package/package.json +15 -14
- package/src/cache-service.ts +436 -54
- package/src/disk-tier.ts +18 -2
- package/src/encryption.ts +69 -13
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +283 -23
- package/src/types.ts +75 -1
package/dist/index.cjs
CHANGED
|
@@ -42,11 +42,11 @@ module.exports = __toCommonJS(index_exports);
|
|
|
42
42
|
|
|
43
43
|
// src/cache-service.ts
|
|
44
44
|
var import_ioredis = require("ioredis");
|
|
45
|
+
var import_msgpackr3 = require("msgpackr");
|
|
45
46
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
46
47
|
var import_os = __toESM(require("os"), 1);
|
|
47
48
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
48
49
|
var import_path2 = __toESM(require("path"), 1);
|
|
49
|
-
var import_msgpackr3 = require("msgpackr");
|
|
50
50
|
|
|
51
51
|
// src/types.ts
|
|
52
52
|
var consoleLogger = {
|
|
@@ -82,6 +82,8 @@ var IV_POOL_COUNT = 64;
|
|
|
82
82
|
var CacheEncryption = class {
|
|
83
83
|
_key = null;
|
|
84
84
|
_mode;
|
|
85
|
+
_prevKey = null;
|
|
86
|
+
_prevMode = "aes-256-gcm";
|
|
85
87
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
86
88
|
_ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
87
89
|
_ivOffset = IV_BYTES * IV_POOL_COUNT;
|
|
@@ -144,7 +146,7 @@ var CacheEncryption = class {
|
|
|
144
146
|
}
|
|
145
147
|
return out;
|
|
146
148
|
}
|
|
147
|
-
constructor(keyBase64, logger, mode = "aes-256-gcm") {
|
|
149
|
+
constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
148
150
|
this._mode = mode;
|
|
149
151
|
if (!keyBase64) {
|
|
150
152
|
if (process.env.NODE_ENV === "production") {
|
|
@@ -175,6 +177,15 @@ var CacheEncryption = class {
|
|
|
175
177
|
} catch (err) {
|
|
176
178
|
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
177
179
|
}
|
|
180
|
+
if (previousKeyBase64) {
|
|
181
|
+
try {
|
|
182
|
+
this._prevMode = previousMode ?? mode;
|
|
183
|
+
this._prevKey = Buffer.from(previousKeyBase64, "base64");
|
|
184
|
+
logger.debug("Previous encryption key loaded for key rotation fallback");
|
|
185
|
+
} catch (err) {
|
|
186
|
+
logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
178
189
|
}
|
|
179
190
|
get isEnabled() {
|
|
180
191
|
return this._key !== null;
|
|
@@ -216,19 +227,37 @@ var CacheEncryption = class {
|
|
|
216
227
|
/**
|
|
217
228
|
* Decrypt a Redis value.
|
|
218
229
|
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
230
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
219
231
|
*/
|
|
220
232
|
decrypt(value) {
|
|
233
|
+
try {
|
|
234
|
+
return this._decryptWithKey(value, this._key, this._mode);
|
|
235
|
+
} catch (primaryErr) {
|
|
236
|
+
if (this._prevKey) {
|
|
237
|
+
try {
|
|
238
|
+
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
239
|
+
} catch {
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
throw primaryErr;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
_decryptWithKey(value, key, mode) {
|
|
221
246
|
if (value.startsWith(PREFIX_XOR)) {
|
|
222
|
-
if (!
|
|
247
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
223
248
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
224
|
-
|
|
249
|
+
const klen = key.length;
|
|
250
|
+
const len = masked.length;
|
|
251
|
+
const out = Buffer.allocUnsafe(len);
|
|
252
|
+
for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
|
|
253
|
+
return out.toString("utf8");
|
|
225
254
|
}
|
|
226
255
|
if (value.startsWith(PREFIX_CTR)) {
|
|
227
|
-
if (!
|
|
256
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
228
257
|
const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
|
|
229
258
|
const iv2 = combined2.subarray(0, CTR_IV_BYTES);
|
|
230
259
|
const ct2 = combined2.subarray(CTR_IV_BYTES);
|
|
231
|
-
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr",
|
|
260
|
+
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
|
|
232
261
|
const plain2 = d2.update(ct2);
|
|
233
262
|
d2.final();
|
|
234
263
|
return plain2.toString("utf8");
|
|
@@ -236,18 +265,19 @@ var CacheEncryption = class {
|
|
|
236
265
|
const is256 = value.startsWith(PREFIX_256);
|
|
237
266
|
const is128 = value.startsWith(PREFIX_128);
|
|
238
267
|
if (!is256 && !is128) return value;
|
|
239
|
-
if (!
|
|
268
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
240
269
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
241
270
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
242
271
|
const combined = Buffer.from(value.slice(prefix.length), "base64");
|
|
243
272
|
const iv = combined.subarray(0, IV_BYTES);
|
|
244
273
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
245
274
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
246
|
-
const d = (0, import_crypto.createDecipheriv)(algo,
|
|
275
|
+
const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
|
|
247
276
|
d.setAuthTag(tag);
|
|
248
277
|
const plain = d.update(ct);
|
|
249
278
|
d.final();
|
|
250
279
|
return plain.toString("utf8");
|
|
280
|
+
void mode;
|
|
251
281
|
}
|
|
252
282
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
253
283
|
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
@@ -287,19 +317,37 @@ var CacheEncryption = class {
|
|
|
287
317
|
/**
|
|
288
318
|
* Decrypt a raw Buffer from disk/snapshot.
|
|
289
319
|
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
320
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
290
321
|
*/
|
|
291
322
|
decryptBuffer(data) {
|
|
323
|
+
try {
|
|
324
|
+
return this._decryptBufferWithKey(data, this._key);
|
|
325
|
+
} catch (primaryErr) {
|
|
326
|
+
if (this._prevKey) {
|
|
327
|
+
try {
|
|
328
|
+
return this._decryptBufferWithKey(data, this._prevKey);
|
|
329
|
+
} catch {
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
throw primaryErr;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
_decryptBufferWithKey(data, key) {
|
|
292
336
|
if (data.length < MAGIC_LEN) return data;
|
|
293
337
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
294
338
|
if (magic.equals(MAGIC_XOR)) {
|
|
295
|
-
if (!
|
|
296
|
-
|
|
339
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
340
|
+
const raw = data.subarray(MAGIC_LEN);
|
|
341
|
+
const klen = key.length;
|
|
342
|
+
const out = Buffer.allocUnsafe(raw.length);
|
|
343
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
|
|
344
|
+
return out;
|
|
297
345
|
}
|
|
298
346
|
if (magic.equals(MAGIC_CTR)) {
|
|
299
|
-
if (!
|
|
347
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
300
348
|
const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
301
349
|
const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
302
|
-
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr",
|
|
350
|
+
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
|
|
303
351
|
const plain2 = d2.update(ct2);
|
|
304
352
|
d2.final();
|
|
305
353
|
return plain2;
|
|
@@ -307,12 +355,12 @@ var CacheEncryption = class {
|
|
|
307
355
|
const is256 = magic.equals(MAGIC_256);
|
|
308
356
|
const is128 = magic.equals(MAGIC_128);
|
|
309
357
|
if (!is256 && !is128) return data;
|
|
310
|
-
if (!
|
|
358
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
311
359
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
312
360
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
313
361
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
314
362
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
315
|
-
const d = (0, import_crypto.createDecipheriv)(algo,
|
|
363
|
+
const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
|
|
316
364
|
d.setAuthTag(tag);
|
|
317
365
|
const plain = d.update(ct);
|
|
318
366
|
d.final();
|
|
@@ -489,12 +537,66 @@ function createBloomFilter(logger) {
|
|
|
489
537
|
return new JsBloomFilter();
|
|
490
538
|
}
|
|
491
539
|
}
|
|
540
|
+
var SKETCH_ROWS = 4;
|
|
541
|
+
var SKETCH_WIDTH = 512;
|
|
542
|
+
var SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
543
|
+
var SKETCH_DECAY_THRESHOLD = 1e5;
|
|
544
|
+
var CountMinSketch = class {
|
|
545
|
+
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
546
|
+
inserts = 0;
|
|
547
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
548
|
+
fnv32(key) {
|
|
549
|
+
let h = 2166136261;
|
|
550
|
+
for (let i = 0; i < key.length; i++) {
|
|
551
|
+
h ^= key.charCodeAt(i);
|
|
552
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
553
|
+
}
|
|
554
|
+
return h;
|
|
555
|
+
}
|
|
556
|
+
/** Four independent bit-mixes from one FNV-1a seed. */
|
|
557
|
+
hashes(key) {
|
|
558
|
+
const h = this.fnv32(key);
|
|
559
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
560
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
561
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
562
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
563
|
+
return [h1, h2, h3, h4];
|
|
564
|
+
}
|
|
565
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
566
|
+
increment(key) {
|
|
567
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
568
|
+
const t = this.table;
|
|
569
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
|
|
570
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
|
|
571
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
|
|
572
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
|
|
573
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
574
|
+
}
|
|
575
|
+
/** Minimum-across-rows frequency estimate. */
|
|
576
|
+
estimate(key) {
|
|
577
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
578
|
+
const t = this.table;
|
|
579
|
+
return Math.min(
|
|
580
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
|
|
581
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
|
|
582
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
|
|
583
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
587
|
+
decay() {
|
|
588
|
+
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
589
|
+
this.inserts = 0;
|
|
590
|
+
}
|
|
591
|
+
};
|
|
492
592
|
var SmartMemoryCache = class {
|
|
493
593
|
cache = /* @__PURE__ */ new Map();
|
|
494
594
|
opts;
|
|
495
595
|
bloom;
|
|
496
596
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
497
597
|
categoryPrefixes;
|
|
598
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
599
|
+
sketch = new CountMinSketch();
|
|
498
600
|
totalSize = 0;
|
|
499
601
|
categoryCount = /* @__PURE__ */ new Map();
|
|
500
602
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -504,6 +606,7 @@ var SmartMemoryCache = class {
|
|
|
504
606
|
bloomChecks = 0;
|
|
505
607
|
bloomFalsePos = 0;
|
|
506
608
|
compressions = 0;
|
|
609
|
+
categoryHits = /* @__PURE__ */ new Map();
|
|
507
610
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
508
611
|
_bloomDirtyCount = 0;
|
|
509
612
|
constructor(opts, existing) {
|
|
@@ -544,7 +647,7 @@ var SmartMemoryCache = class {
|
|
|
544
647
|
getCategoryLimit(cat) {
|
|
545
648
|
return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
546
649
|
}
|
|
547
|
-
_delete(key) {
|
|
650
|
+
_delete(key, reason = "manual") {
|
|
548
651
|
const entry = this.cache.get(key);
|
|
549
652
|
if (!entry) return false;
|
|
550
653
|
const cat = this.getCategory(key);
|
|
@@ -553,7 +656,14 @@ var SmartMemoryCache = class {
|
|
|
553
656
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
554
657
|
this.categoryKeys.get(cat)?.delete(key);
|
|
555
658
|
this._bloomDirtyCount++;
|
|
556
|
-
|
|
659
|
+
const deleted = this.cache.delete(key);
|
|
660
|
+
if (deleted && this.opts.onEviction) {
|
|
661
|
+
try {
|
|
662
|
+
this.opts.onEviction(key, reason);
|
|
663
|
+
} catch {
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return deleted;
|
|
557
667
|
}
|
|
558
668
|
ensureCapacity(category, neededSize) {
|
|
559
669
|
const lim = this.getCategoryLimit(category);
|
|
@@ -564,10 +674,10 @@ var SmartMemoryCache = class {
|
|
|
564
674
|
if (!catOvf && !glbOvf) return;
|
|
565
675
|
this.smartEvict(category, catOvf);
|
|
566
676
|
}
|
|
567
|
-
score(entry, catBonus, now) {
|
|
677
|
+
score(entry, catBonus, now, key) {
|
|
568
678
|
const age = now - entry.lastAccess;
|
|
569
679
|
const ttl = Math.max(0, entry.expiresAt - now);
|
|
570
|
-
const freq = Math.min(entry.hits, 100);
|
|
680
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
571
681
|
return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
|
|
572
682
|
}
|
|
573
683
|
/**
|
|
@@ -602,7 +712,7 @@ var SmartMemoryCache = class {
|
|
|
602
712
|
const entry = this.cache.get(key);
|
|
603
713
|
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
604
714
|
catSeen++;
|
|
605
|
-
const s = this.score(entry, 100, now);
|
|
715
|
+
const s = this.score(entry, 100, now, key);
|
|
606
716
|
if (pool.length < EVICT) {
|
|
607
717
|
pool.push({ key, score: s });
|
|
608
718
|
} else {
|
|
@@ -620,7 +730,7 @@ var SmartMemoryCache = class {
|
|
|
620
730
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
621
731
|
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
622
732
|
globalSeen++;
|
|
623
|
-
const s = this.score(entry, 0, now);
|
|
733
|
+
const s = this.score(entry, 0, now, key);
|
|
624
734
|
if (globalPool.length < remaining) {
|
|
625
735
|
globalPool.push({ key, score: s });
|
|
626
736
|
} else {
|
|
@@ -635,7 +745,7 @@ var SmartMemoryCache = class {
|
|
|
635
745
|
for (const { key } of pool.slice(0, EVICT)) {
|
|
636
746
|
const entry = this.cache.get(key);
|
|
637
747
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
638
|
-
this._delete(key);
|
|
748
|
+
this._delete(key, "capacity");
|
|
639
749
|
}
|
|
640
750
|
}
|
|
641
751
|
// ── Public API ────────────────────────────────────────────────────────────
|
|
@@ -649,12 +759,15 @@ var SmartMemoryCache = class {
|
|
|
649
759
|
}
|
|
650
760
|
const now = Date.now();
|
|
651
761
|
if (entry.expiresAt < now) {
|
|
652
|
-
this._delete(key);
|
|
762
|
+
this._delete(key, "ttl");
|
|
653
763
|
return null;
|
|
654
764
|
}
|
|
655
765
|
entry.hits++;
|
|
656
766
|
entry.lastAccess = now;
|
|
657
|
-
|
|
767
|
+
this.sketch.increment(key);
|
|
768
|
+
const cat = this.getCategory(key);
|
|
769
|
+
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
770
|
+
const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
658
771
|
const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
|
|
659
772
|
return { value, isStale };
|
|
660
773
|
}
|
|
@@ -662,6 +775,7 @@ var SmartMemoryCache = class {
|
|
|
662
775
|
const packed = (0, import_msgpackr.pack)(data);
|
|
663
776
|
const size = packed.byteLength;
|
|
664
777
|
this.compressions++;
|
|
778
|
+
this.sketch.increment(key);
|
|
665
779
|
const cat = this.getCategory(key);
|
|
666
780
|
const lim = this.getCategoryLimit(cat);
|
|
667
781
|
if (size > lim.maxSizeBytes * 0.5) {
|
|
@@ -677,7 +791,7 @@ var SmartMemoryCache = class {
|
|
|
677
791
|
}
|
|
678
792
|
this.ensureCapacity(cat, size);
|
|
679
793
|
const now = Date.now();
|
|
680
|
-
this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
794
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
681
795
|
this.bloom.add(key);
|
|
682
796
|
this.maybeRebuildBloom();
|
|
683
797
|
this.totalSize += size;
|
|
@@ -691,7 +805,7 @@ var SmartMemoryCache = class {
|
|
|
691
805
|
ks.add(key);
|
|
692
806
|
}
|
|
693
807
|
delete(key) {
|
|
694
|
-
const deleted = this._delete(key);
|
|
808
|
+
const deleted = this._delete(key, "manual");
|
|
695
809
|
if (deleted) this.maybeRebuildBloom();
|
|
696
810
|
return deleted;
|
|
697
811
|
}
|
|
@@ -704,10 +818,77 @@ var SmartMemoryCache = class {
|
|
|
704
818
|
}
|
|
705
819
|
deletePattern(pattern) {
|
|
706
820
|
let n = 0;
|
|
707
|
-
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
|
|
821
|
+
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
|
|
708
822
|
if (n > 0) this.maybeRebuildBloom();
|
|
709
823
|
return n;
|
|
710
824
|
}
|
|
825
|
+
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
826
|
+
clear(prefix) {
|
|
827
|
+
if (prefix) {
|
|
828
|
+
const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
|
|
829
|
+
return this.deletePattern(pattern);
|
|
830
|
+
}
|
|
831
|
+
const count = this.cache.size;
|
|
832
|
+
this.cache.clear();
|
|
833
|
+
this.totalSize = 0;
|
|
834
|
+
this.categoryCount.clear();
|
|
835
|
+
this.categorySize.clear();
|
|
836
|
+
this.categoryKeys.clear();
|
|
837
|
+
this.categoryHits.clear();
|
|
838
|
+
this.bloom.reset();
|
|
839
|
+
this._bloomDirtyCount = 0;
|
|
840
|
+
return count;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Evict entries that violate current category or global limits.
|
|
844
|
+
* Returns the number of entries evicted.
|
|
845
|
+
*/
|
|
846
|
+
rebalance() {
|
|
847
|
+
const now = Date.now();
|
|
848
|
+
let evicted = 0;
|
|
849
|
+
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
850
|
+
const catKeys = this.categoryKeys.get(cat);
|
|
851
|
+
if (!catKeys || catKeys.size === 0) continue;
|
|
852
|
+
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
853
|
+
let catSz = this.categorySize.get(cat) ?? 0;
|
|
854
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
|
|
855
|
+
const candidates = [];
|
|
856
|
+
for (const key of catKeys) {
|
|
857
|
+
const entry = this.cache.get(key);
|
|
858
|
+
if (!entry) continue;
|
|
859
|
+
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
860
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
861
|
+
}
|
|
862
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
863
|
+
for (const { key } of candidates) {
|
|
864
|
+
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
865
|
+
catSz = this.categorySize.get(cat) ?? 0;
|
|
866
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
|
|
867
|
+
const entry = this.cache.get(key);
|
|
868
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
869
|
+
this._delete(key, "rebalance");
|
|
870
|
+
evicted++;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
874
|
+
const before = this.cache.size;
|
|
875
|
+
this.smartEvict("default", false);
|
|
876
|
+
if (this.cache.size >= before) break;
|
|
877
|
+
evicted += before - this.cache.size;
|
|
878
|
+
}
|
|
879
|
+
if (evicted > 0) this.maybeRebuildBloom();
|
|
880
|
+
return evicted;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
884
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
885
|
+
*/
|
|
886
|
+
ttl(key) {
|
|
887
|
+
const entry = this.cache.get(key);
|
|
888
|
+
if (!entry) return null;
|
|
889
|
+
const remaining = entry.expiresAt - Date.now();
|
|
890
|
+
return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
|
|
891
|
+
}
|
|
711
892
|
/**
|
|
712
893
|
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
713
894
|
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
@@ -722,7 +903,7 @@ var SmartMemoryCache = class {
|
|
|
722
903
|
const candidates = [];
|
|
723
904
|
for (const [key, entry] of this.cache) {
|
|
724
905
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
725
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
906
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
726
907
|
}
|
|
727
908
|
candidates.sort((a, b) => a.score - b.score);
|
|
728
909
|
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
@@ -730,7 +911,7 @@ var SmartMemoryCache = class {
|
|
|
730
911
|
for (const { key } of candidates.slice(0, count)) {
|
|
731
912
|
const entry = this.cache.get(key);
|
|
732
913
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
733
|
-
this._delete(key);
|
|
914
|
+
this._delete(key, "oom");
|
|
734
915
|
evicted++;
|
|
735
916
|
}
|
|
736
917
|
return evicted;
|
|
@@ -739,7 +920,7 @@ var SmartMemoryCache = class {
|
|
|
739
920
|
const now = Date.now();
|
|
740
921
|
let cleaned = 0;
|
|
741
922
|
for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
|
|
742
|
-
this._delete(key);
|
|
923
|
+
this._delete(key, "ttl");
|
|
743
924
|
cleaned++;
|
|
744
925
|
}
|
|
745
926
|
if (cleaned > 0) {
|
|
@@ -769,13 +950,49 @@ var SmartMemoryCache = class {
|
|
|
769
950
|
if (this.cache.has(key)) continue;
|
|
770
951
|
const rawData = entry.data;
|
|
771
952
|
const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
772
|
-
|
|
953
|
+
const value = (0, import_msgpackr.unpack)(data);
|
|
954
|
+
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
773
955
|
this.bloom.add(key);
|
|
774
956
|
loaded++;
|
|
775
957
|
}
|
|
776
958
|
this.recalculateStats();
|
|
777
959
|
return loaded;
|
|
778
960
|
}
|
|
961
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
962
|
+
/**
|
|
963
|
+
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
964
|
+
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
965
|
+
* are silently skipped.
|
|
966
|
+
*/
|
|
967
|
+
*liveEntries() {
|
|
968
|
+
const now = Date.now();
|
|
969
|
+
for (const [key, entry] of this.cache) {
|
|
970
|
+
if (entry.expiresAt > now) yield [key, entry];
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
975
|
+
* Use this instead of liveEntries() when you only need keys.
|
|
976
|
+
*/
|
|
977
|
+
*liveKeys() {
|
|
978
|
+
const now = Date.now();
|
|
979
|
+
for (const [key, entry] of this.cache) {
|
|
980
|
+
if (entry.expiresAt > now) yield key;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Yields only the resolved values of live entries.
|
|
985
|
+
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
986
|
+
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
987
|
+
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
988
|
+
*/
|
|
989
|
+
*liveValues() {
|
|
990
|
+
const now = Date.now();
|
|
991
|
+
for (const entry of this.cache.values()) {
|
|
992
|
+
if (entry.expiresAt > now)
|
|
993
|
+
yield entry.value !== void 0 ? entry.value : entry.data;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
779
996
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
780
997
|
get size() {
|
|
781
998
|
return this.cache.size;
|
|
@@ -785,9 +1002,12 @@ var SmartMemoryCache = class {
|
|
|
785
1002
|
}
|
|
786
1003
|
getStats() {
|
|
787
1004
|
const categories = {};
|
|
788
|
-
for (const [cat, cnt] of this.categoryCount)
|
|
1005
|
+
for (const [cat, cnt] of this.categoryCount) {
|
|
1006
|
+
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
1007
|
+
}
|
|
789
1008
|
return {
|
|
790
1009
|
entries: this.cache.size,
|
|
1010
|
+
sizeBytes: this.totalSize,
|
|
791
1011
|
sizeKB: Math.round(this.totalSize / 1024),
|
|
792
1012
|
categories,
|
|
793
1013
|
bloom: {
|
|
@@ -803,6 +1023,56 @@ var SmartMemoryCache = class {
|
|
|
803
1023
|
}
|
|
804
1024
|
};
|
|
805
1025
|
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
1028
|
+
* Does NOT count as a hit or perform SWR logic.
|
|
1029
|
+
*/
|
|
1030
|
+
getEntry(key) {
|
|
1031
|
+
const entry = this.cache.get(key);
|
|
1032
|
+
if (!entry) return void 0;
|
|
1033
|
+
if (entry.expiresAt <= Date.now()) return void 0;
|
|
1034
|
+
return entry;
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Return true if the key exists in L1 and has not expired.
|
|
1038
|
+
* Uses the bloom filter as a fast negative check.
|
|
1039
|
+
*/
|
|
1040
|
+
has(key) {
|
|
1041
|
+
if (!this.bloom.mightContain(key)) return false;
|
|
1042
|
+
const entry = this.cache.get(key);
|
|
1043
|
+
if (!entry) return false;
|
|
1044
|
+
if (entry.expiresAt <= Date.now()) {
|
|
1045
|
+
this._delete(key, "ttl");
|
|
1046
|
+
return false;
|
|
1047
|
+
}
|
|
1048
|
+
return true;
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1052
|
+
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1053
|
+
*/
|
|
1054
|
+
touch(key, newTtlMs) {
|
|
1055
|
+
const entry = this.cache.get(key);
|
|
1056
|
+
if (!entry) return false;
|
|
1057
|
+
const now = Date.now();
|
|
1058
|
+
if (entry.expiresAt <= now) {
|
|
1059
|
+
this._delete(key, "ttl");
|
|
1060
|
+
return false;
|
|
1061
|
+
}
|
|
1062
|
+
entry.expiresAt = now + newTtlMs;
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1067
|
+
* Returns `false` if the key is absent or already expired.
|
|
1068
|
+
*/
|
|
1069
|
+
bumpExpiry(key, additionalMs) {
|
|
1070
|
+
const entry = this.cache.get(key);
|
|
1071
|
+
if (!entry) return false;
|
|
1072
|
+
if (entry.expiresAt <= Date.now()) return false;
|
|
1073
|
+
entry.expiresAt += additionalMs;
|
|
1074
|
+
return true;
|
|
1075
|
+
}
|
|
806
1076
|
bloomMightContain(key) {
|
|
807
1077
|
return this.bloom.mightContain(key);
|
|
808
1078
|
}
|
|
@@ -1066,6 +1336,23 @@ var DiskTier = class {
|
|
|
1066
1336
|
}
|
|
1067
1337
|
return purged;
|
|
1068
1338
|
}
|
|
1339
|
+
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1340
|
+
clear() {
|
|
1341
|
+
this.ensureDir();
|
|
1342
|
+
if (!this.dirReady) return 0;
|
|
1343
|
+
let cleared = 0;
|
|
1344
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
1345
|
+
try {
|
|
1346
|
+
const stat = import_fs.default.statSync(filePath);
|
|
1347
|
+
import_fs.default.unlinkSync(filePath);
|
|
1348
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1349
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1350
|
+
cleared++;
|
|
1351
|
+
} catch {
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
return cleared;
|
|
1355
|
+
}
|
|
1069
1356
|
get stats() {
|
|
1070
1357
|
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
1071
1358
|
}
|
|
@@ -1098,6 +1385,9 @@ var CacheService = class _CacheService {
|
|
|
1098
1385
|
_redisDisabled;
|
|
1099
1386
|
inflight = /* @__PURE__ */ new Map();
|
|
1100
1387
|
revalidating = /* @__PURE__ */ new Set();
|
|
1388
|
+
_l1Counters = /* @__PURE__ */ new Map();
|
|
1389
|
+
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
1390
|
+
tagIndex = /* @__PURE__ */ new Map();
|
|
1101
1391
|
redis = null;
|
|
1102
1392
|
redisConnecting = null;
|
|
1103
1393
|
snapshotLoaded = false;
|
|
@@ -1131,7 +1421,13 @@ var CacheService = class _CacheService {
|
|
|
1131
1421
|
this.logger = logger;
|
|
1132
1422
|
const ns = options.namespace?.trim() ?? "";
|
|
1133
1423
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
1134
|
-
this.enc = new CacheEncryption(
|
|
1424
|
+
this.enc = new CacheEncryption(
|
|
1425
|
+
encKeyRaw,
|
|
1426
|
+
logger,
|
|
1427
|
+
options.encryptionMode,
|
|
1428
|
+
options.previousEncryptionKey,
|
|
1429
|
+
options.previousEncryptionMode
|
|
1430
|
+
);
|
|
1135
1431
|
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
1136
1432
|
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
1137
1433
|
this.opts = {
|
|
@@ -1165,7 +1461,10 @@ var CacheService = class _CacheService {
|
|
|
1165
1461
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
1166
1462
|
oomEvictPercent: options.oomEvictPercent ?? 0.2,
|
|
1167
1463
|
onMetrics: options.onMetrics,
|
|
1168
|
-
metricsIntervalMs: options.metricsIntervalMs ?? 6e4
|
|
1464
|
+
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1465
|
+
staleIfError: options.staleIfError ?? 0,
|
|
1466
|
+
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1467
|
+
instanceName: options.instanceName ?? ""
|
|
1169
1468
|
};
|
|
1170
1469
|
this.disk = new DiskTier({
|
|
1171
1470
|
dir: this.opts.diskCacheDir,
|
|
@@ -1184,6 +1483,7 @@ var CacheService = class _CacheService {
|
|
|
1184
1483
|
diskSpill: (key, entry) => {
|
|
1185
1484
|
void this.disk.save(key, entry);
|
|
1186
1485
|
},
|
|
1486
|
+
onEviction: options.onEviction,
|
|
1187
1487
|
logger
|
|
1188
1488
|
});
|
|
1189
1489
|
if (!this.snapshotLoaded) {
|
|
@@ -1250,6 +1550,17 @@ var CacheService = class _CacheService {
|
|
|
1250
1550
|
if (!g[key]) g[key] = new _CacheService(options);
|
|
1251
1551
|
return g[key];
|
|
1252
1552
|
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
1555
|
+
* Useful when config is fetched from a secret store at startup.
|
|
1556
|
+
*
|
|
1557
|
+
* @example
|
|
1558
|
+
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
1559
|
+
*/
|
|
1560
|
+
static async createAsync(options) {
|
|
1561
|
+
const resolved = await options;
|
|
1562
|
+
return _CacheService.create(resolved);
|
|
1563
|
+
}
|
|
1253
1564
|
/** Replace the singleton (useful in tests). */
|
|
1254
1565
|
static reset(options) {
|
|
1255
1566
|
const g = globalThis;
|
|
@@ -1291,25 +1602,7 @@ var CacheService = class _CacheService {
|
|
|
1291
1602
|
});
|
|
1292
1603
|
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
1293
1604
|
sub.on("message", (_channel, message) => {
|
|
1294
|
-
|
|
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
|
-
}
|
|
1605
|
+
this._handleBackplaneMessage(message);
|
|
1313
1606
|
});
|
|
1314
1607
|
sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
1315
1608
|
channel: this.backplaneChannel,
|
|
@@ -1319,6 +1612,28 @@ var CacheService = class _CacheService {
|
|
|
1319
1612
|
}));
|
|
1320
1613
|
this.subClient = sub;
|
|
1321
1614
|
}
|
|
1615
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
1616
|
+
_handleBackplaneMessage(message) {
|
|
1617
|
+
try {
|
|
1618
|
+
const msg = JSON.parse(message);
|
|
1619
|
+
if (msg.src === this.instanceId) {
|
|
1620
|
+
this.counters.invSkipped++;
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
this.counters.invReceived++;
|
|
1624
|
+
if (msg.op === "del") {
|
|
1625
|
+
this.l1.delete(msg.key);
|
|
1626
|
+
setImmediate(() => this.disk.delete(msg.key));
|
|
1627
|
+
} else if (msg.op === "del-glob") {
|
|
1628
|
+
this.l1.deletePattern(msg.key);
|
|
1629
|
+
}
|
|
1630
|
+
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1631
|
+
op: msg.op,
|
|
1632
|
+
key: msg.key.slice(0, 60)
|
|
1633
|
+
});
|
|
1634
|
+
} catch {
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1322
1637
|
async publishInvalidation(op, key) {
|
|
1323
1638
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1324
1639
|
try {
|
|
@@ -1335,43 +1650,49 @@ var CacheService = class _CacheService {
|
|
|
1335
1650
|
if (this.redis?.status === "ready") return this.redis;
|
|
1336
1651
|
if (this.redisConnecting) return this.redisConnecting;
|
|
1337
1652
|
this.redisConnecting = (async () => {
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1653
|
+
try {
|
|
1654
|
+
const client = new import_ioredis.Redis({
|
|
1655
|
+
host: this.opts.redisHost,
|
|
1656
|
+
port: this.opts.redisPort,
|
|
1657
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
1658
|
+
connectTimeout: 1e4,
|
|
1659
|
+
lazyConnect: false,
|
|
1660
|
+
maxRetriesPerRequest: 3,
|
|
1661
|
+
enableAutoPipelining: true,
|
|
1662
|
+
keepAlive: 3e4,
|
|
1663
|
+
family: 4,
|
|
1664
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
1665
|
+
});
|
|
1666
|
+
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
1667
|
+
client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
|
|
1668
|
+
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
1669
|
+
await new Promise((resolve, reject) => {
|
|
1670
|
+
client.once("ready", resolve);
|
|
1671
|
+
client.once("error", reject);
|
|
1672
|
+
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1673
|
+
});
|
|
1674
|
+
this.redis = client;
|
|
1675
|
+
this.redisConnecting = null;
|
|
1676
|
+
return client;
|
|
1677
|
+
} catch (err) {
|
|
1678
|
+
this.redisConnecting = null;
|
|
1679
|
+
throw err;
|
|
1680
|
+
}
|
|
1361
1681
|
})();
|
|
1362
1682
|
return this.redisConnecting;
|
|
1363
1683
|
}
|
|
1364
1684
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
1365
|
-
writeSnapshot() {
|
|
1685
|
+
writeSnapshot(altPath) {
|
|
1366
1686
|
try {
|
|
1367
1687
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
1368
1688
|
if (entries.length === 0) return;
|
|
1369
1689
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
1370
1690
|
const packed = (0, import_msgpackr3.pack)(payload);
|
|
1371
1691
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
1372
|
-
|
|
1692
|
+
const dest = altPath ?? this.opts.snapshotPath;
|
|
1693
|
+
import_fs2.default.writeFileSync(dest, final, { mode: 384 });
|
|
1373
1694
|
this.logger.info("Cache snapshot written", {
|
|
1374
|
-
path:
|
|
1695
|
+
path: dest,
|
|
1375
1696
|
entries: entries.length,
|
|
1376
1697
|
sizeKB: Math.round(final.length / 1024),
|
|
1377
1698
|
encrypted: this.enc.isEnabled
|
|
@@ -1534,7 +1855,7 @@ var CacheService = class _CacheService {
|
|
|
1534
1855
|
const data = await fetchFn();
|
|
1535
1856
|
const staleAt = Date.now() + ttlMs;
|
|
1536
1857
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
|
|
1537
|
-
if (!this._redisDisabled) {
|
|
1858
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1538
1859
|
try {
|
|
1539
1860
|
const client = await this.getRedis();
|
|
1540
1861
|
const s = JSON.stringify(data);
|
|
@@ -1545,20 +1866,53 @@ var CacheService = class _CacheService {
|
|
|
1545
1866
|
}
|
|
1546
1867
|
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
1547
1868
|
} catch (err) {
|
|
1548
|
-
this.
|
|
1869
|
+
if (this.opts.staleIfError > 0) {
|
|
1870
|
+
const additionalMs = this.opts.staleIfError * 1e3;
|
|
1871
|
+
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
1872
|
+
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
1873
|
+
cacheKey,
|
|
1874
|
+
staleIfErrorSecs: this.opts.staleIfError
|
|
1875
|
+
});
|
|
1876
|
+
} else {
|
|
1877
|
+
this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
|
|
1878
|
+
}
|
|
1549
1879
|
} finally {
|
|
1550
1880
|
this.revalidating.delete(cacheKey);
|
|
1551
1881
|
}
|
|
1552
1882
|
}
|
|
1553
1883
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1554
1884
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1555
|
-
async set(cacheKey, data, ttlSeconds = 300, priority) {
|
|
1885
|
+
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1556
1886
|
const ttlMs = ttlSeconds * 1e3;
|
|
1557
1887
|
const p = priority ?? inferPriority(cacheKey);
|
|
1558
1888
|
const k = this.nk(cacheKey);
|
|
1559
1889
|
this.counters.sets++;
|
|
1560
1890
|
this.l1.set(k, data, ttlMs, p);
|
|
1561
|
-
if (
|
|
1891
|
+
if (opts?.tags?.length) {
|
|
1892
|
+
for (const tag of opts.tags) {
|
|
1893
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1894
|
+
let members = this.tagIndex.get(tagKey);
|
|
1895
|
+
if (!members) {
|
|
1896
|
+
members = /* @__PURE__ */ new Set();
|
|
1897
|
+
this.tagIndex.set(tagKey, members);
|
|
1898
|
+
}
|
|
1899
|
+
members.add(k);
|
|
1900
|
+
}
|
|
1901
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1902
|
+
try {
|
|
1903
|
+
const client = await this.getRedis();
|
|
1904
|
+
const pl = client.pipeline();
|
|
1905
|
+
for (const tag of opts.tags) {
|
|
1906
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1907
|
+
pl.sadd(tagKey, k);
|
|
1908
|
+
pl.expire(tagKey, ttlSeconds + 3600);
|
|
1909
|
+
}
|
|
1910
|
+
await pl.exec();
|
|
1911
|
+
} catch {
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1562
1916
|
try {
|
|
1563
1917
|
const client = await this.getRedis();
|
|
1564
1918
|
const s = JSON.stringify(data);
|
|
@@ -1587,7 +1941,7 @@ var CacheService = class _CacheService {
|
|
|
1587
1941
|
this.l1.delete(k);
|
|
1588
1942
|
this.disk.delete(k);
|
|
1589
1943
|
}
|
|
1590
|
-
if (!this._redisDisabled) {
|
|
1944
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1591
1945
|
try {
|
|
1592
1946
|
const client = await this.getRedis();
|
|
1593
1947
|
if (isPattern) {
|
|
@@ -1614,8 +1968,18 @@ var CacheService = class _CacheService {
|
|
|
1614
1968
|
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
1615
1969
|
*/
|
|
1616
1970
|
async increment(cacheKey, ttlSeconds) {
|
|
1617
|
-
if (this._redisDisabled) return 0;
|
|
1618
1971
|
const k = this.nk(cacheKey);
|
|
1972
|
+
if (this._redisDisabled) {
|
|
1973
|
+
const now = Date.now();
|
|
1974
|
+
const ttlMs = (ttlSeconds ?? 60) * 1e3;
|
|
1975
|
+
const entry = this._l1Counters.get(k);
|
|
1976
|
+
if (entry && entry.expiresAt > now) {
|
|
1977
|
+
entry.value++;
|
|
1978
|
+
return entry.value;
|
|
1979
|
+
}
|
|
1980
|
+
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
1981
|
+
return 1;
|
|
1982
|
+
}
|
|
1619
1983
|
try {
|
|
1620
1984
|
const client = await this.getRedis();
|
|
1621
1985
|
const count = await client.incr(k);
|
|
@@ -1626,7 +1990,262 @@ var CacheService = class _CacheService {
|
|
|
1626
1990
|
return 0;
|
|
1627
1991
|
}
|
|
1628
1992
|
}
|
|
1629
|
-
// ──
|
|
1993
|
+
// ── Clear / Rebalance / TTL ────────────────────────────────────────────────
|
|
1994
|
+
/**
|
|
1995
|
+
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
1996
|
+
*
|
|
1997
|
+
* @example
|
|
1998
|
+
* await cache.clear(); // flush everything
|
|
1999
|
+
* await cache.clear('user:abc'); // flush all keys for one user
|
|
2000
|
+
*/
|
|
2001
|
+
async clear(prefix) {
|
|
2002
|
+
this.counters.deletes++;
|
|
2003
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
2004
|
+
if (k) {
|
|
2005
|
+
this.l1.deletePattern(k);
|
|
2006
|
+
} else {
|
|
2007
|
+
this.l1.clear();
|
|
2008
|
+
this.disk.clear();
|
|
2009
|
+
this._l1Counters.clear();
|
|
2010
|
+
this.tagIndex.clear();
|
|
2011
|
+
}
|
|
2012
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2013
|
+
try {
|
|
2014
|
+
const client = await this.getRedis();
|
|
2015
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
2016
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2017
|
+
const keys = [];
|
|
2018
|
+
await new Promise((resolve, reject) => {
|
|
2019
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2020
|
+
stream.on("end", resolve);
|
|
2021
|
+
stream.on("error", reject);
|
|
2022
|
+
});
|
|
2023
|
+
if (keys.length > 0) await client.del(...keys);
|
|
2024
|
+
} catch (err) {
|
|
2025
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
void this.publishInvalidation(
|
|
2029
|
+
"del-glob",
|
|
2030
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
2034
|
+
* Evict L1 entries that violate the current category or global capacity limits.
|
|
2035
|
+
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
2036
|
+
* Returns the number of entries evicted.
|
|
2037
|
+
*/
|
|
2038
|
+
rebalance() {
|
|
2039
|
+
return this.l1.rebalance();
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* Return the remaining TTL in seconds for a key currently in L1.
|
|
2043
|
+
* Returns null if the key is absent from L1 or has already expired.
|
|
2044
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
2045
|
+
*/
|
|
2046
|
+
ttl(cacheKey) {
|
|
2047
|
+
return this.l1.ttl(this.nk(cacheKey));
|
|
2048
|
+
}
|
|
2049
|
+
/**
|
|
2050
|
+
* Return true if the key exists in L1 and has not expired.
|
|
2051
|
+
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
2052
|
+
*/
|
|
2053
|
+
has(cacheKey) {
|
|
2054
|
+
return this.l1.has(this.nk(cacheKey));
|
|
2055
|
+
}
|
|
2056
|
+
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
2057
|
+
/**
|
|
2058
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
2059
|
+
*
|
|
2060
|
+
* @example
|
|
2061
|
+
* for (const key of cache.keys()) console.log(key);
|
|
2062
|
+
*/
|
|
2063
|
+
*keys() {
|
|
2064
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2065
|
+
for (const key of this.l1.liveKeys()) {
|
|
2066
|
+
yield prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
/**
|
|
2070
|
+
* Lazily yield every non-expired L1 value.
|
|
2071
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
2072
|
+
*
|
|
2073
|
+
* @example
|
|
2074
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
2075
|
+
*/
|
|
2076
|
+
*values() {
|
|
2077
|
+
yield* this.l1.liveValues();
|
|
2078
|
+
}
|
|
2079
|
+
/**
|
|
2080
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
2081
|
+
* Keys are stripped of their namespace prefix.
|
|
2082
|
+
*
|
|
2083
|
+
* @example
|
|
2084
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
2085
|
+
*/
|
|
2086
|
+
*entries() {
|
|
2087
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2088
|
+
for (const [key, entry] of this.l1.liveEntries()) {
|
|
2089
|
+
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2090
|
+
yield [k, entry.value !== void 0 ? entry.value : entry.data];
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
2095
|
+
* Returns `false` if the key is absent or already expired.
|
|
2096
|
+
*
|
|
2097
|
+
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
2098
|
+
*/
|
|
2099
|
+
async touch(cacheKey, newTtlSeconds) {
|
|
2100
|
+
const k = this.nk(cacheKey);
|
|
2101
|
+
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
2102
|
+
if (hit && !this._redisDisabled) {
|
|
2103
|
+
try {
|
|
2104
|
+
const client = await this.getRedis();
|
|
2105
|
+
void client.expire(k, newTtlSeconds);
|
|
2106
|
+
} catch {
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
return hit;
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
2113
|
+
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
2114
|
+
*
|
|
2115
|
+
* @example
|
|
2116
|
+
* const fresh = cache.getIfFresh('user:123');
|
|
2117
|
+
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
2118
|
+
*/
|
|
2119
|
+
getIfFresh(cacheKey) {
|
|
2120
|
+
const k = this.nk(cacheKey);
|
|
2121
|
+
const entry = this.l1.getEntry(k);
|
|
2122
|
+
if (!entry) return null;
|
|
2123
|
+
const now = Date.now();
|
|
2124
|
+
if (entry.expiresAt <= now) return null;
|
|
2125
|
+
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
2126
|
+
return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
2127
|
+
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
2130
|
+
* Preserves input ordering. Uses inflight coalescing per key.
|
|
2131
|
+
*
|
|
2132
|
+
* @param keys - Array of cache keys.
|
|
2133
|
+
* @param fetchFn - Called with only the keys that missed L1.
|
|
2134
|
+
* @param ttl - TTL in seconds for newly fetched values.
|
|
2135
|
+
*/
|
|
2136
|
+
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
2137
|
+
const result = new Array(keys.length);
|
|
2138
|
+
const missIndexes = [];
|
|
2139
|
+
const missKeys = [];
|
|
2140
|
+
for (let i = 0; i < keys.length; i++) {
|
|
2141
|
+
const entry = this.l1.getEntry(this.nk(keys[i]));
|
|
2142
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
2143
|
+
result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
2144
|
+
this.counters.l1Hits++;
|
|
2145
|
+
} else {
|
|
2146
|
+
missIndexes.push(i);
|
|
2147
|
+
missKeys.push(keys[i]);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
if (missKeys.length > 0) {
|
|
2151
|
+
const fetched = await fetchFn(missKeys);
|
|
2152
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
2153
|
+
const v = fetched[missKeys[j]];
|
|
2154
|
+
result[missIndexes[j]] = v;
|
|
2155
|
+
if (v !== void 0) {
|
|
2156
|
+
await this.set(missKeys[j], v, ttl, priority);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
return result;
|
|
2161
|
+
}
|
|
2162
|
+
/**
|
|
2163
|
+
* Invalidate all keys associated with a tag.
|
|
2164
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
2165
|
+
*
|
|
2166
|
+
* @example
|
|
2167
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
2168
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
2169
|
+
*/
|
|
2170
|
+
async invalidateTag(tag) {
|
|
2171
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
2172
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
2173
|
+
for (const k of members) {
|
|
2174
|
+
this.l1.delete(k);
|
|
2175
|
+
this.disk.delete(k);
|
|
2176
|
+
}
|
|
2177
|
+
this.tagIndex.delete(tagKey);
|
|
2178
|
+
if (!this._redisDisabled) {
|
|
2179
|
+
try {
|
|
2180
|
+
const client = await this.getRedis();
|
|
2181
|
+
const redisMembers = await client.smembers(tagKey);
|
|
2182
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
2183
|
+
if (toDelete.length > 0) {
|
|
2184
|
+
await client.del(...toDelete, tagKey);
|
|
2185
|
+
} else {
|
|
2186
|
+
await client.del(tagKey);
|
|
2187
|
+
}
|
|
2188
|
+
} catch (err) {
|
|
2189
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
/**
|
|
2194
|
+
* Measure L1 / disk / Redis latency.
|
|
2195
|
+
* Useful for health checks and dashboards.
|
|
2196
|
+
*
|
|
2197
|
+
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
2198
|
+
* `l2` is `null` when Redis is disabled.
|
|
2199
|
+
*/
|
|
2200
|
+
async ping() {
|
|
2201
|
+
const t0 = Date.now();
|
|
2202
|
+
this.l1.has("__ping__");
|
|
2203
|
+
const l1 = Date.now() - t0;
|
|
2204
|
+
const t1 = Date.now();
|
|
2205
|
+
void this.disk.stats;
|
|
2206
|
+
const disk = Date.now() - t1;
|
|
2207
|
+
let l2 = null;
|
|
2208
|
+
if (!this._redisDisabled) {
|
|
2209
|
+
try {
|
|
2210
|
+
const client = await this.getRedis();
|
|
2211
|
+
const t2 = Date.now();
|
|
2212
|
+
await client.ping();
|
|
2213
|
+
l2 = Date.now() - t2;
|
|
2214
|
+
} catch {
|
|
2215
|
+
l2 = null;
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
return { l1, disk, l2 };
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* Export all live L1 entries to Redis via a single pipeline.
|
|
2222
|
+
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
2223
|
+
* Returns the number of keys written.
|
|
2224
|
+
*/
|
|
2225
|
+
async drainToL2() {
|
|
2226
|
+
if (this._redisDisabled) return 0;
|
|
2227
|
+
try {
|
|
2228
|
+
const client = await this.getRedis();
|
|
2229
|
+
const entries = this.l1.exportEntries([]);
|
|
2230
|
+
const now = Date.now();
|
|
2231
|
+
if (entries.length === 0) return 0;
|
|
2232
|
+
const pl = client.pipeline();
|
|
2233
|
+
for (const { key, entry } of entries) {
|
|
2234
|
+
const remainingMs = entry.expiresAt - now;
|
|
2235
|
+
if (remainingMs <= 0) continue;
|
|
2236
|
+
const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
|
|
2237
|
+
const s = JSON.stringify(entry.value);
|
|
2238
|
+
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
2239
|
+
pl.setex(key, ttlSecs, stored);
|
|
2240
|
+
}
|
|
2241
|
+
await pl.exec();
|
|
2242
|
+
return entries.length;
|
|
2243
|
+
} catch (err) {
|
|
2244
|
+
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
2245
|
+
return 0;
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
// ── Stats ─────────────────────────────────────────────────────────────
|
|
1630
2249
|
stats() {
|
|
1631
2250
|
return {
|
|
1632
2251
|
l1: this.l1.getStats(),
|
|
@@ -1693,8 +2312,11 @@ var CacheService = class _CacheService {
|
|
|
1693
2312
|
* @param m - Snapshot returned by `cache.metrics()`
|
|
1694
2313
|
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
1695
2314
|
*/
|
|
1696
|
-
static toPrometheusText(m, prefix = "tricache") {
|
|
1697
|
-
const
|
|
2315
|
+
static toPrometheusText(m, prefix = "tricache", instanceName) {
|
|
2316
|
+
const parts = [];
|
|
2317
|
+
if (m.namespace) parts.push(`namespace="${m.namespace}"`);
|
|
2318
|
+
if (instanceName) parts.push(`instance="${instanceName}"`);
|
|
2319
|
+
const lbl = parts.length ? `{${parts.join(",")}}` : "";
|
|
1698
2320
|
const lines = [];
|
|
1699
2321
|
const counter = (name, val, help) => {
|
|
1700
2322
|
lines.push(`# HELP ${prefix}_${name}_total ${help}`);
|