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.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// src/cache-service.ts
|
|
2
2
|
import { Redis as RedisClient } from "ioredis";
|
|
3
|
+
import { pack as pack3, unpack as unpack3 } from "msgpackr";
|
|
3
4
|
import crypto2 from "crypto";
|
|
4
5
|
import os from "os";
|
|
5
6
|
import fs2 from "fs";
|
|
6
7
|
import path2 from "path";
|
|
7
|
-
import { pack as pack3, unpack as unpack3 } from "msgpackr";
|
|
8
8
|
|
|
9
9
|
// src/types.ts
|
|
10
10
|
var consoleLogger = {
|
|
@@ -40,6 +40,8 @@ var IV_POOL_COUNT = 64;
|
|
|
40
40
|
var CacheEncryption = class {
|
|
41
41
|
_key = null;
|
|
42
42
|
_mode;
|
|
43
|
+
_prevKey = null;
|
|
44
|
+
_prevMode = "aes-256-gcm";
|
|
43
45
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
44
46
|
_ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
45
47
|
_ivOffset = IV_BYTES * IV_POOL_COUNT;
|
|
@@ -102,7 +104,7 @@ var CacheEncryption = class {
|
|
|
102
104
|
}
|
|
103
105
|
return out;
|
|
104
106
|
}
|
|
105
|
-
constructor(keyBase64, logger, mode = "aes-256-gcm") {
|
|
107
|
+
constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
106
108
|
this._mode = mode;
|
|
107
109
|
if (!keyBase64) {
|
|
108
110
|
if (process.env.NODE_ENV === "production") {
|
|
@@ -133,6 +135,15 @@ var CacheEncryption = class {
|
|
|
133
135
|
} catch (err) {
|
|
134
136
|
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
135
137
|
}
|
|
138
|
+
if (previousKeyBase64) {
|
|
139
|
+
try {
|
|
140
|
+
this._prevMode = previousMode ?? mode;
|
|
141
|
+
this._prevKey = Buffer.from(previousKeyBase64, "base64");
|
|
142
|
+
logger.debug("Previous encryption key loaded for key rotation fallback");
|
|
143
|
+
} catch (err) {
|
|
144
|
+
logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
136
147
|
}
|
|
137
148
|
get isEnabled() {
|
|
138
149
|
return this._key !== null;
|
|
@@ -174,19 +185,37 @@ var CacheEncryption = class {
|
|
|
174
185
|
/**
|
|
175
186
|
* Decrypt a Redis value.
|
|
176
187
|
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
188
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
177
189
|
*/
|
|
178
190
|
decrypt(value) {
|
|
191
|
+
try {
|
|
192
|
+
return this._decryptWithKey(value, this._key, this._mode);
|
|
193
|
+
} catch (primaryErr) {
|
|
194
|
+
if (this._prevKey) {
|
|
195
|
+
try {
|
|
196
|
+
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
197
|
+
} catch {
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
throw primaryErr;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
_decryptWithKey(value, key, mode) {
|
|
179
204
|
if (value.startsWith(PREFIX_XOR)) {
|
|
180
|
-
if (!
|
|
205
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
181
206
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
182
|
-
|
|
207
|
+
const klen = key.length;
|
|
208
|
+
const len = masked.length;
|
|
209
|
+
const out = Buffer.allocUnsafe(len);
|
|
210
|
+
for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
|
|
211
|
+
return out.toString("utf8");
|
|
183
212
|
}
|
|
184
213
|
if (value.startsWith(PREFIX_CTR)) {
|
|
185
|
-
if (!
|
|
214
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
186
215
|
const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
|
|
187
216
|
const iv2 = combined2.subarray(0, CTR_IV_BYTES);
|
|
188
217
|
const ct2 = combined2.subarray(CTR_IV_BYTES);
|
|
189
|
-
const d2 = createDecipheriv("aes-128-ctr",
|
|
218
|
+
const d2 = createDecipheriv("aes-128-ctr", key, iv2);
|
|
190
219
|
const plain2 = d2.update(ct2);
|
|
191
220
|
d2.final();
|
|
192
221
|
return plain2.toString("utf8");
|
|
@@ -194,18 +223,19 @@ var CacheEncryption = class {
|
|
|
194
223
|
const is256 = value.startsWith(PREFIX_256);
|
|
195
224
|
const is128 = value.startsWith(PREFIX_128);
|
|
196
225
|
if (!is256 && !is128) return value;
|
|
197
|
-
if (!
|
|
226
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
198
227
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
199
228
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
200
229
|
const combined = Buffer.from(value.slice(prefix.length), "base64");
|
|
201
230
|
const iv = combined.subarray(0, IV_BYTES);
|
|
202
231
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
203
232
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
204
|
-
const d = createDecipheriv(algo,
|
|
233
|
+
const d = createDecipheriv(algo, key, iv);
|
|
205
234
|
d.setAuthTag(tag);
|
|
206
235
|
const plain = d.update(ct);
|
|
207
236
|
d.final();
|
|
208
237
|
return plain.toString("utf8");
|
|
238
|
+
void mode;
|
|
209
239
|
}
|
|
210
240
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
211
241
|
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
@@ -245,19 +275,37 @@ var CacheEncryption = class {
|
|
|
245
275
|
/**
|
|
246
276
|
* Decrypt a raw Buffer from disk/snapshot.
|
|
247
277
|
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
278
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
248
279
|
*/
|
|
249
280
|
decryptBuffer(data) {
|
|
281
|
+
try {
|
|
282
|
+
return this._decryptBufferWithKey(data, this._key);
|
|
283
|
+
} catch (primaryErr) {
|
|
284
|
+
if (this._prevKey) {
|
|
285
|
+
try {
|
|
286
|
+
return this._decryptBufferWithKey(data, this._prevKey);
|
|
287
|
+
} catch {
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
throw primaryErr;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
_decryptBufferWithKey(data, key) {
|
|
250
294
|
if (data.length < MAGIC_LEN) return data;
|
|
251
295
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
252
296
|
if (magic.equals(MAGIC_XOR)) {
|
|
253
|
-
if (!
|
|
254
|
-
|
|
297
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
298
|
+
const raw = data.subarray(MAGIC_LEN);
|
|
299
|
+
const klen = key.length;
|
|
300
|
+
const out = Buffer.allocUnsafe(raw.length);
|
|
301
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
|
|
302
|
+
return out;
|
|
255
303
|
}
|
|
256
304
|
if (magic.equals(MAGIC_CTR)) {
|
|
257
|
-
if (!
|
|
305
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
258
306
|
const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
259
307
|
const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
260
|
-
const d2 = createDecipheriv("aes-128-ctr",
|
|
308
|
+
const d2 = createDecipheriv("aes-128-ctr", key, iv2);
|
|
261
309
|
const plain2 = d2.update(ct2);
|
|
262
310
|
d2.final();
|
|
263
311
|
return plain2;
|
|
@@ -265,12 +313,12 @@ var CacheEncryption = class {
|
|
|
265
313
|
const is256 = magic.equals(MAGIC_256);
|
|
266
314
|
const is128 = magic.equals(MAGIC_128);
|
|
267
315
|
if (!is256 && !is128) return data;
|
|
268
|
-
if (!
|
|
316
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
269
317
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
270
318
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
271
319
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
272
320
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
273
|
-
const d = createDecipheriv(algo,
|
|
321
|
+
const d = createDecipheriv(algo, key, iv);
|
|
274
322
|
d.setAuthTag(tag);
|
|
275
323
|
const plain = d.update(ct);
|
|
276
324
|
d.final();
|
|
@@ -447,12 +495,66 @@ function createBloomFilter(logger) {
|
|
|
447
495
|
return new JsBloomFilter();
|
|
448
496
|
}
|
|
449
497
|
}
|
|
498
|
+
var SKETCH_ROWS = 4;
|
|
499
|
+
var SKETCH_WIDTH = 512;
|
|
500
|
+
var SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
501
|
+
var SKETCH_DECAY_THRESHOLD = 1e5;
|
|
502
|
+
var CountMinSketch = class {
|
|
503
|
+
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
504
|
+
inserts = 0;
|
|
505
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
506
|
+
fnv32(key) {
|
|
507
|
+
let h = 2166136261;
|
|
508
|
+
for (let i = 0; i < key.length; i++) {
|
|
509
|
+
h ^= key.charCodeAt(i);
|
|
510
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
511
|
+
}
|
|
512
|
+
return h;
|
|
513
|
+
}
|
|
514
|
+
/** Four independent bit-mixes from one FNV-1a seed. */
|
|
515
|
+
hashes(key) {
|
|
516
|
+
const h = this.fnv32(key);
|
|
517
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
518
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
519
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
520
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
521
|
+
return [h1, h2, h3, h4];
|
|
522
|
+
}
|
|
523
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
524
|
+
increment(key) {
|
|
525
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
526
|
+
const t = this.table;
|
|
527
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
|
|
528
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
|
|
529
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
|
|
530
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
|
|
531
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
532
|
+
}
|
|
533
|
+
/** Minimum-across-rows frequency estimate. */
|
|
534
|
+
estimate(key) {
|
|
535
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
536
|
+
const t = this.table;
|
|
537
|
+
return Math.min(
|
|
538
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
|
|
539
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
|
|
540
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
|
|
541
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
545
|
+
decay() {
|
|
546
|
+
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
547
|
+
this.inserts = 0;
|
|
548
|
+
}
|
|
549
|
+
};
|
|
450
550
|
var SmartMemoryCache = class {
|
|
451
551
|
cache = /* @__PURE__ */ new Map();
|
|
452
552
|
opts;
|
|
453
553
|
bloom;
|
|
454
554
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
455
555
|
categoryPrefixes;
|
|
556
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
557
|
+
sketch = new CountMinSketch();
|
|
456
558
|
totalSize = 0;
|
|
457
559
|
categoryCount = /* @__PURE__ */ new Map();
|
|
458
560
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -462,6 +564,7 @@ var SmartMemoryCache = class {
|
|
|
462
564
|
bloomChecks = 0;
|
|
463
565
|
bloomFalsePos = 0;
|
|
464
566
|
compressions = 0;
|
|
567
|
+
categoryHits = /* @__PURE__ */ new Map();
|
|
465
568
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
466
569
|
_bloomDirtyCount = 0;
|
|
467
570
|
constructor(opts, existing) {
|
|
@@ -502,7 +605,7 @@ var SmartMemoryCache = class {
|
|
|
502
605
|
getCategoryLimit(cat) {
|
|
503
606
|
return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
504
607
|
}
|
|
505
|
-
_delete(key) {
|
|
608
|
+
_delete(key, reason = "manual") {
|
|
506
609
|
const entry = this.cache.get(key);
|
|
507
610
|
if (!entry) return false;
|
|
508
611
|
const cat = this.getCategory(key);
|
|
@@ -511,7 +614,14 @@ var SmartMemoryCache = class {
|
|
|
511
614
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
512
615
|
this.categoryKeys.get(cat)?.delete(key);
|
|
513
616
|
this._bloomDirtyCount++;
|
|
514
|
-
|
|
617
|
+
const deleted = this.cache.delete(key);
|
|
618
|
+
if (deleted && this.opts.onEviction) {
|
|
619
|
+
try {
|
|
620
|
+
this.opts.onEviction(key, reason);
|
|
621
|
+
} catch {
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return deleted;
|
|
515
625
|
}
|
|
516
626
|
ensureCapacity(category, neededSize) {
|
|
517
627
|
const lim = this.getCategoryLimit(category);
|
|
@@ -522,10 +632,10 @@ var SmartMemoryCache = class {
|
|
|
522
632
|
if (!catOvf && !glbOvf) return;
|
|
523
633
|
this.smartEvict(category, catOvf);
|
|
524
634
|
}
|
|
525
|
-
score(entry, catBonus, now) {
|
|
635
|
+
score(entry, catBonus, now, key) {
|
|
526
636
|
const age = now - entry.lastAccess;
|
|
527
637
|
const ttl = Math.max(0, entry.expiresAt - now);
|
|
528
|
-
const freq = Math.min(entry.hits, 100);
|
|
638
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
529
639
|
return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
|
|
530
640
|
}
|
|
531
641
|
/**
|
|
@@ -560,7 +670,7 @@ var SmartMemoryCache = class {
|
|
|
560
670
|
const entry = this.cache.get(key);
|
|
561
671
|
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
562
672
|
catSeen++;
|
|
563
|
-
const s = this.score(entry, 100, now);
|
|
673
|
+
const s = this.score(entry, 100, now, key);
|
|
564
674
|
if (pool.length < EVICT) {
|
|
565
675
|
pool.push({ key, score: s });
|
|
566
676
|
} else {
|
|
@@ -578,7 +688,7 @@ var SmartMemoryCache = class {
|
|
|
578
688
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
579
689
|
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
580
690
|
globalSeen++;
|
|
581
|
-
const s = this.score(entry, 0, now);
|
|
691
|
+
const s = this.score(entry, 0, now, key);
|
|
582
692
|
if (globalPool.length < remaining) {
|
|
583
693
|
globalPool.push({ key, score: s });
|
|
584
694
|
} else {
|
|
@@ -593,7 +703,7 @@ var SmartMemoryCache = class {
|
|
|
593
703
|
for (const { key } of pool.slice(0, EVICT)) {
|
|
594
704
|
const entry = this.cache.get(key);
|
|
595
705
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
596
|
-
this._delete(key);
|
|
706
|
+
this._delete(key, "capacity");
|
|
597
707
|
}
|
|
598
708
|
}
|
|
599
709
|
// ── Public API ────────────────────────────────────────────────────────────
|
|
@@ -607,12 +717,15 @@ var SmartMemoryCache = class {
|
|
|
607
717
|
}
|
|
608
718
|
const now = Date.now();
|
|
609
719
|
if (entry.expiresAt < now) {
|
|
610
|
-
this._delete(key);
|
|
720
|
+
this._delete(key, "ttl");
|
|
611
721
|
return null;
|
|
612
722
|
}
|
|
613
723
|
entry.hits++;
|
|
614
724
|
entry.lastAccess = now;
|
|
615
|
-
|
|
725
|
+
this.sketch.increment(key);
|
|
726
|
+
const cat = this.getCategory(key);
|
|
727
|
+
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
728
|
+
const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
|
|
616
729
|
const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
|
|
617
730
|
return { value, isStale };
|
|
618
731
|
}
|
|
@@ -620,6 +733,7 @@ var SmartMemoryCache = class {
|
|
|
620
733
|
const packed = pack(data);
|
|
621
734
|
const size = packed.byteLength;
|
|
622
735
|
this.compressions++;
|
|
736
|
+
this.sketch.increment(key);
|
|
623
737
|
const cat = this.getCategory(key);
|
|
624
738
|
const lim = this.getCategoryLimit(cat);
|
|
625
739
|
if (size > lim.maxSizeBytes * 0.5) {
|
|
@@ -635,7 +749,7 @@ var SmartMemoryCache = class {
|
|
|
635
749
|
}
|
|
636
750
|
this.ensureCapacity(cat, size);
|
|
637
751
|
const now = Date.now();
|
|
638
|
-
this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
752
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
639
753
|
this.bloom.add(key);
|
|
640
754
|
this.maybeRebuildBloom();
|
|
641
755
|
this.totalSize += size;
|
|
@@ -649,7 +763,7 @@ var SmartMemoryCache = class {
|
|
|
649
763
|
ks.add(key);
|
|
650
764
|
}
|
|
651
765
|
delete(key) {
|
|
652
|
-
const deleted = this._delete(key);
|
|
766
|
+
const deleted = this._delete(key, "manual");
|
|
653
767
|
if (deleted) this.maybeRebuildBloom();
|
|
654
768
|
return deleted;
|
|
655
769
|
}
|
|
@@ -662,10 +776,77 @@ var SmartMemoryCache = class {
|
|
|
662
776
|
}
|
|
663
777
|
deletePattern(pattern) {
|
|
664
778
|
let n = 0;
|
|
665
|
-
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
|
|
779
|
+
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
|
|
666
780
|
if (n > 0) this.maybeRebuildBloom();
|
|
667
781
|
return n;
|
|
668
782
|
}
|
|
783
|
+
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
784
|
+
clear(prefix) {
|
|
785
|
+
if (prefix) {
|
|
786
|
+
const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
|
|
787
|
+
return this.deletePattern(pattern);
|
|
788
|
+
}
|
|
789
|
+
const count = this.cache.size;
|
|
790
|
+
this.cache.clear();
|
|
791
|
+
this.totalSize = 0;
|
|
792
|
+
this.categoryCount.clear();
|
|
793
|
+
this.categorySize.clear();
|
|
794
|
+
this.categoryKeys.clear();
|
|
795
|
+
this.categoryHits.clear();
|
|
796
|
+
this.bloom.reset();
|
|
797
|
+
this._bloomDirtyCount = 0;
|
|
798
|
+
return count;
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Evict entries that violate current category or global limits.
|
|
802
|
+
* Returns the number of entries evicted.
|
|
803
|
+
*/
|
|
804
|
+
rebalance() {
|
|
805
|
+
const now = Date.now();
|
|
806
|
+
let evicted = 0;
|
|
807
|
+
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
808
|
+
const catKeys = this.categoryKeys.get(cat);
|
|
809
|
+
if (!catKeys || catKeys.size === 0) continue;
|
|
810
|
+
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
811
|
+
let catSz = this.categorySize.get(cat) ?? 0;
|
|
812
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
|
|
813
|
+
const candidates = [];
|
|
814
|
+
for (const key of catKeys) {
|
|
815
|
+
const entry = this.cache.get(key);
|
|
816
|
+
if (!entry) continue;
|
|
817
|
+
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
818
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
819
|
+
}
|
|
820
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
821
|
+
for (const { key } of candidates) {
|
|
822
|
+
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
823
|
+
catSz = this.categorySize.get(cat) ?? 0;
|
|
824
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
|
|
825
|
+
const entry = this.cache.get(key);
|
|
826
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
827
|
+
this._delete(key, "rebalance");
|
|
828
|
+
evicted++;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
832
|
+
const before = this.cache.size;
|
|
833
|
+
this.smartEvict("default", false);
|
|
834
|
+
if (this.cache.size >= before) break;
|
|
835
|
+
evicted += before - this.cache.size;
|
|
836
|
+
}
|
|
837
|
+
if (evicted > 0) this.maybeRebuildBloom();
|
|
838
|
+
return evicted;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
842
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
843
|
+
*/
|
|
844
|
+
ttl(key) {
|
|
845
|
+
const entry = this.cache.get(key);
|
|
846
|
+
if (!entry) return null;
|
|
847
|
+
const remaining = entry.expiresAt - Date.now();
|
|
848
|
+
return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
|
|
849
|
+
}
|
|
669
850
|
/**
|
|
670
851
|
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
671
852
|
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
@@ -680,7 +861,7 @@ var SmartMemoryCache = class {
|
|
|
680
861
|
const candidates = [];
|
|
681
862
|
for (const [key, entry] of this.cache) {
|
|
682
863
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
683
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
864
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
684
865
|
}
|
|
685
866
|
candidates.sort((a, b) => a.score - b.score);
|
|
686
867
|
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
@@ -688,7 +869,7 @@ var SmartMemoryCache = class {
|
|
|
688
869
|
for (const { key } of candidates.slice(0, count)) {
|
|
689
870
|
const entry = this.cache.get(key);
|
|
690
871
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
691
|
-
this._delete(key);
|
|
872
|
+
this._delete(key, "oom");
|
|
692
873
|
evicted++;
|
|
693
874
|
}
|
|
694
875
|
return evicted;
|
|
@@ -697,7 +878,7 @@ var SmartMemoryCache = class {
|
|
|
697
878
|
const now = Date.now();
|
|
698
879
|
let cleaned = 0;
|
|
699
880
|
for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
|
|
700
|
-
this._delete(key);
|
|
881
|
+
this._delete(key, "ttl");
|
|
701
882
|
cleaned++;
|
|
702
883
|
}
|
|
703
884
|
if (cleaned > 0) {
|
|
@@ -727,13 +908,49 @@ var SmartMemoryCache = class {
|
|
|
727
908
|
if (this.cache.has(key)) continue;
|
|
728
909
|
const rawData = entry.data;
|
|
729
910
|
const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
730
|
-
|
|
911
|
+
const value = unpack(data);
|
|
912
|
+
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
731
913
|
this.bloom.add(key);
|
|
732
914
|
loaded++;
|
|
733
915
|
}
|
|
734
916
|
this.recalculateStats();
|
|
735
917
|
return loaded;
|
|
736
918
|
}
|
|
919
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
920
|
+
/**
|
|
921
|
+
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
922
|
+
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
923
|
+
* are silently skipped.
|
|
924
|
+
*/
|
|
925
|
+
*liveEntries() {
|
|
926
|
+
const now = Date.now();
|
|
927
|
+
for (const [key, entry] of this.cache) {
|
|
928
|
+
if (entry.expiresAt > now) yield [key, entry];
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
933
|
+
* Use this instead of liveEntries() when you only need keys.
|
|
934
|
+
*/
|
|
935
|
+
*liveKeys() {
|
|
936
|
+
const now = Date.now();
|
|
937
|
+
for (const [key, entry] of this.cache) {
|
|
938
|
+
if (entry.expiresAt > now) yield key;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Yields only the resolved values of live entries.
|
|
943
|
+
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
944
|
+
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
945
|
+
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
946
|
+
*/
|
|
947
|
+
*liveValues() {
|
|
948
|
+
const now = Date.now();
|
|
949
|
+
for (const entry of this.cache.values()) {
|
|
950
|
+
if (entry.expiresAt > now)
|
|
951
|
+
yield entry.value !== void 0 ? entry.value : entry.data;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
737
954
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
738
955
|
get size() {
|
|
739
956
|
return this.cache.size;
|
|
@@ -743,9 +960,12 @@ var SmartMemoryCache = class {
|
|
|
743
960
|
}
|
|
744
961
|
getStats() {
|
|
745
962
|
const categories = {};
|
|
746
|
-
for (const [cat, cnt] of this.categoryCount)
|
|
963
|
+
for (const [cat, cnt] of this.categoryCount) {
|
|
964
|
+
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
965
|
+
}
|
|
747
966
|
return {
|
|
748
967
|
entries: this.cache.size,
|
|
968
|
+
sizeBytes: this.totalSize,
|
|
749
969
|
sizeKB: Math.round(this.totalSize / 1024),
|
|
750
970
|
categories,
|
|
751
971
|
bloom: {
|
|
@@ -761,6 +981,56 @@ var SmartMemoryCache = class {
|
|
|
761
981
|
}
|
|
762
982
|
};
|
|
763
983
|
}
|
|
984
|
+
/**
|
|
985
|
+
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
986
|
+
* Does NOT count as a hit or perform SWR logic.
|
|
987
|
+
*/
|
|
988
|
+
getEntry(key) {
|
|
989
|
+
const entry = this.cache.get(key);
|
|
990
|
+
if (!entry) return void 0;
|
|
991
|
+
if (entry.expiresAt <= Date.now()) return void 0;
|
|
992
|
+
return entry;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Return true if the key exists in L1 and has not expired.
|
|
996
|
+
* Uses the bloom filter as a fast negative check.
|
|
997
|
+
*/
|
|
998
|
+
has(key) {
|
|
999
|
+
if (!this.bloom.mightContain(key)) return false;
|
|
1000
|
+
const entry = this.cache.get(key);
|
|
1001
|
+
if (!entry) return false;
|
|
1002
|
+
if (entry.expiresAt <= Date.now()) {
|
|
1003
|
+
this._delete(key, "ttl");
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
return true;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1010
|
+
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1011
|
+
*/
|
|
1012
|
+
touch(key, newTtlMs) {
|
|
1013
|
+
const entry = this.cache.get(key);
|
|
1014
|
+
if (!entry) return false;
|
|
1015
|
+
const now = Date.now();
|
|
1016
|
+
if (entry.expiresAt <= now) {
|
|
1017
|
+
this._delete(key, "ttl");
|
|
1018
|
+
return false;
|
|
1019
|
+
}
|
|
1020
|
+
entry.expiresAt = now + newTtlMs;
|
|
1021
|
+
return true;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1025
|
+
* Returns `false` if the key is absent or already expired.
|
|
1026
|
+
*/
|
|
1027
|
+
bumpExpiry(key, additionalMs) {
|
|
1028
|
+
const entry = this.cache.get(key);
|
|
1029
|
+
if (!entry) return false;
|
|
1030
|
+
if (entry.expiresAt <= Date.now()) return false;
|
|
1031
|
+
entry.expiresAt += additionalMs;
|
|
1032
|
+
return true;
|
|
1033
|
+
}
|
|
764
1034
|
bloomMightContain(key) {
|
|
765
1035
|
return this.bloom.mightContain(key);
|
|
766
1036
|
}
|
|
@@ -1024,6 +1294,23 @@ var DiskTier = class {
|
|
|
1024
1294
|
}
|
|
1025
1295
|
return purged;
|
|
1026
1296
|
}
|
|
1297
|
+
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1298
|
+
clear() {
|
|
1299
|
+
this.ensureDir();
|
|
1300
|
+
if (!this.dirReady) return 0;
|
|
1301
|
+
let cleared = 0;
|
|
1302
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
1303
|
+
try {
|
|
1304
|
+
const stat = fs.statSync(filePath);
|
|
1305
|
+
fs.unlinkSync(filePath);
|
|
1306
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1307
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1308
|
+
cleared++;
|
|
1309
|
+
} catch {
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
return cleared;
|
|
1313
|
+
}
|
|
1027
1314
|
get stats() {
|
|
1028
1315
|
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
1029
1316
|
}
|
|
@@ -1056,6 +1343,9 @@ var CacheService = class _CacheService {
|
|
|
1056
1343
|
_redisDisabled;
|
|
1057
1344
|
inflight = /* @__PURE__ */ new Map();
|
|
1058
1345
|
revalidating = /* @__PURE__ */ new Set();
|
|
1346
|
+
_l1Counters = /* @__PURE__ */ new Map();
|
|
1347
|
+
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
1348
|
+
tagIndex = /* @__PURE__ */ new Map();
|
|
1059
1349
|
redis = null;
|
|
1060
1350
|
redisConnecting = null;
|
|
1061
1351
|
snapshotLoaded = false;
|
|
@@ -1089,7 +1379,13 @@ var CacheService = class _CacheService {
|
|
|
1089
1379
|
this.logger = logger;
|
|
1090
1380
|
const ns = options.namespace?.trim() ?? "";
|
|
1091
1381
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
1092
|
-
this.enc = new CacheEncryption(
|
|
1382
|
+
this.enc = new CacheEncryption(
|
|
1383
|
+
encKeyRaw,
|
|
1384
|
+
logger,
|
|
1385
|
+
options.encryptionMode,
|
|
1386
|
+
options.previousEncryptionKey,
|
|
1387
|
+
options.previousEncryptionMode
|
|
1388
|
+
);
|
|
1093
1389
|
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
1094
1390
|
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
1095
1391
|
this.opts = {
|
|
@@ -1123,7 +1419,10 @@ var CacheService = class _CacheService {
|
|
|
1123
1419
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
1124
1420
|
oomEvictPercent: options.oomEvictPercent ?? 0.2,
|
|
1125
1421
|
onMetrics: options.onMetrics,
|
|
1126
|
-
metricsIntervalMs: options.metricsIntervalMs ?? 6e4
|
|
1422
|
+
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1423
|
+
staleIfError: options.staleIfError ?? 0,
|
|
1424
|
+
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1425
|
+
instanceName: options.instanceName ?? ""
|
|
1127
1426
|
};
|
|
1128
1427
|
this.disk = new DiskTier({
|
|
1129
1428
|
dir: this.opts.diskCacheDir,
|
|
@@ -1142,6 +1441,7 @@ var CacheService = class _CacheService {
|
|
|
1142
1441
|
diskSpill: (key, entry) => {
|
|
1143
1442
|
void this.disk.save(key, entry);
|
|
1144
1443
|
},
|
|
1444
|
+
onEviction: options.onEviction,
|
|
1145
1445
|
logger
|
|
1146
1446
|
});
|
|
1147
1447
|
if (!this.snapshotLoaded) {
|
|
@@ -1208,6 +1508,17 @@ var CacheService = class _CacheService {
|
|
|
1208
1508
|
if (!g[key]) g[key] = new _CacheService(options);
|
|
1209
1509
|
return g[key];
|
|
1210
1510
|
}
|
|
1511
|
+
/**
|
|
1512
|
+
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
1513
|
+
* Useful when config is fetched from a secret store at startup.
|
|
1514
|
+
*
|
|
1515
|
+
* @example
|
|
1516
|
+
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
1517
|
+
*/
|
|
1518
|
+
static async createAsync(options) {
|
|
1519
|
+
const resolved = await options;
|
|
1520
|
+
return _CacheService.create(resolved);
|
|
1521
|
+
}
|
|
1211
1522
|
/** Replace the singleton (useful in tests). */
|
|
1212
1523
|
static reset(options) {
|
|
1213
1524
|
const g = globalThis;
|
|
@@ -1249,25 +1560,7 @@ var CacheService = class _CacheService {
|
|
|
1249
1560
|
});
|
|
1250
1561
|
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
1251
1562
|
sub.on("message", (_channel, message) => {
|
|
1252
|
-
|
|
1253
|
-
const msg = JSON.parse(message);
|
|
1254
|
-
if (msg.src === this.instanceId) {
|
|
1255
|
-
this.counters.invSkipped++;
|
|
1256
|
-
return;
|
|
1257
|
-
}
|
|
1258
|
-
this.counters.invReceived++;
|
|
1259
|
-
if (msg.op === "del") {
|
|
1260
|
-
this.l1.delete(msg.key);
|
|
1261
|
-
this.disk.delete(msg.key);
|
|
1262
|
-
} else if (msg.op === "del-glob") {
|
|
1263
|
-
this.l1.deletePattern(msg.key);
|
|
1264
|
-
}
|
|
1265
|
-
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1266
|
-
op: msg.op,
|
|
1267
|
-
key: msg.key.slice(0, 60)
|
|
1268
|
-
});
|
|
1269
|
-
} catch {
|
|
1270
|
-
}
|
|
1563
|
+
this._handleBackplaneMessage(message);
|
|
1271
1564
|
});
|
|
1272
1565
|
sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
1273
1566
|
channel: this.backplaneChannel,
|
|
@@ -1277,6 +1570,28 @@ var CacheService = class _CacheService {
|
|
|
1277
1570
|
}));
|
|
1278
1571
|
this.subClient = sub;
|
|
1279
1572
|
}
|
|
1573
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
1574
|
+
_handleBackplaneMessage(message) {
|
|
1575
|
+
try {
|
|
1576
|
+
const msg = JSON.parse(message);
|
|
1577
|
+
if (msg.src === this.instanceId) {
|
|
1578
|
+
this.counters.invSkipped++;
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
this.counters.invReceived++;
|
|
1582
|
+
if (msg.op === "del") {
|
|
1583
|
+
this.l1.delete(msg.key);
|
|
1584
|
+
setImmediate(() => this.disk.delete(msg.key));
|
|
1585
|
+
} else if (msg.op === "del-glob") {
|
|
1586
|
+
this.l1.deletePattern(msg.key);
|
|
1587
|
+
}
|
|
1588
|
+
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1589
|
+
op: msg.op,
|
|
1590
|
+
key: msg.key.slice(0, 60)
|
|
1591
|
+
});
|
|
1592
|
+
} catch {
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1280
1595
|
async publishInvalidation(op, key) {
|
|
1281
1596
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1282
1597
|
try {
|
|
@@ -1293,43 +1608,49 @@ var CacheService = class _CacheService {
|
|
|
1293
1608
|
if (this.redis?.status === "ready") return this.redis;
|
|
1294
1609
|
if (this.redisConnecting) return this.redisConnecting;
|
|
1295
1610
|
this.redisConnecting = (async () => {
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1611
|
+
try {
|
|
1612
|
+
const client = new RedisClient({
|
|
1613
|
+
host: this.opts.redisHost,
|
|
1614
|
+
port: this.opts.redisPort,
|
|
1615
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
1616
|
+
connectTimeout: 1e4,
|
|
1617
|
+
lazyConnect: false,
|
|
1618
|
+
maxRetriesPerRequest: 3,
|
|
1619
|
+
enableAutoPipelining: true,
|
|
1620
|
+
keepAlive: 3e4,
|
|
1621
|
+
family: 4,
|
|
1622
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
1623
|
+
});
|
|
1624
|
+
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
1625
|
+
client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
|
|
1626
|
+
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
1627
|
+
await new Promise((resolve, reject) => {
|
|
1628
|
+
client.once("ready", resolve);
|
|
1629
|
+
client.once("error", reject);
|
|
1630
|
+
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1631
|
+
});
|
|
1632
|
+
this.redis = client;
|
|
1633
|
+
this.redisConnecting = null;
|
|
1634
|
+
return client;
|
|
1635
|
+
} catch (err) {
|
|
1636
|
+
this.redisConnecting = null;
|
|
1637
|
+
throw err;
|
|
1638
|
+
}
|
|
1319
1639
|
})();
|
|
1320
1640
|
return this.redisConnecting;
|
|
1321
1641
|
}
|
|
1322
1642
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
1323
|
-
writeSnapshot() {
|
|
1643
|
+
writeSnapshot(altPath) {
|
|
1324
1644
|
try {
|
|
1325
1645
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
1326
1646
|
if (entries.length === 0) return;
|
|
1327
1647
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
1328
1648
|
const packed = pack3(payload);
|
|
1329
1649
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
1330
|
-
|
|
1650
|
+
const dest = altPath ?? this.opts.snapshotPath;
|
|
1651
|
+
fs2.writeFileSync(dest, final, { mode: 384 });
|
|
1331
1652
|
this.logger.info("Cache snapshot written", {
|
|
1332
|
-
path:
|
|
1653
|
+
path: dest,
|
|
1333
1654
|
entries: entries.length,
|
|
1334
1655
|
sizeKB: Math.round(final.length / 1024),
|
|
1335
1656
|
encrypted: this.enc.isEnabled
|
|
@@ -1492,7 +1813,7 @@ var CacheService = class _CacheService {
|
|
|
1492
1813
|
const data = await fetchFn();
|
|
1493
1814
|
const staleAt = Date.now() + ttlMs;
|
|
1494
1815
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
|
|
1495
|
-
if (!this._redisDisabled) {
|
|
1816
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1496
1817
|
try {
|
|
1497
1818
|
const client = await this.getRedis();
|
|
1498
1819
|
const s = JSON.stringify(data);
|
|
@@ -1503,20 +1824,53 @@ var CacheService = class _CacheService {
|
|
|
1503
1824
|
}
|
|
1504
1825
|
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
1505
1826
|
} catch (err) {
|
|
1506
|
-
this.
|
|
1827
|
+
if (this.opts.staleIfError > 0) {
|
|
1828
|
+
const additionalMs = this.opts.staleIfError * 1e3;
|
|
1829
|
+
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
1830
|
+
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
1831
|
+
cacheKey,
|
|
1832
|
+
staleIfErrorSecs: this.opts.staleIfError
|
|
1833
|
+
});
|
|
1834
|
+
} else {
|
|
1835
|
+
this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
|
|
1836
|
+
}
|
|
1507
1837
|
} finally {
|
|
1508
1838
|
this.revalidating.delete(cacheKey);
|
|
1509
1839
|
}
|
|
1510
1840
|
}
|
|
1511
1841
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1512
1842
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1513
|
-
async set(cacheKey, data, ttlSeconds = 300, priority) {
|
|
1843
|
+
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1514
1844
|
const ttlMs = ttlSeconds * 1e3;
|
|
1515
1845
|
const p = priority ?? inferPriority(cacheKey);
|
|
1516
1846
|
const k = this.nk(cacheKey);
|
|
1517
1847
|
this.counters.sets++;
|
|
1518
1848
|
this.l1.set(k, data, ttlMs, p);
|
|
1519
|
-
if (
|
|
1849
|
+
if (opts?.tags?.length) {
|
|
1850
|
+
for (const tag of opts.tags) {
|
|
1851
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1852
|
+
let members = this.tagIndex.get(tagKey);
|
|
1853
|
+
if (!members) {
|
|
1854
|
+
members = /* @__PURE__ */ new Set();
|
|
1855
|
+
this.tagIndex.set(tagKey, members);
|
|
1856
|
+
}
|
|
1857
|
+
members.add(k);
|
|
1858
|
+
}
|
|
1859
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1860
|
+
try {
|
|
1861
|
+
const client = await this.getRedis();
|
|
1862
|
+
const pl = client.pipeline();
|
|
1863
|
+
for (const tag of opts.tags) {
|
|
1864
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1865
|
+
pl.sadd(tagKey, k);
|
|
1866
|
+
pl.expire(tagKey, ttlSeconds + 3600);
|
|
1867
|
+
}
|
|
1868
|
+
await pl.exec();
|
|
1869
|
+
} catch {
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1520
1874
|
try {
|
|
1521
1875
|
const client = await this.getRedis();
|
|
1522
1876
|
const s = JSON.stringify(data);
|
|
@@ -1545,7 +1899,7 @@ var CacheService = class _CacheService {
|
|
|
1545
1899
|
this.l1.delete(k);
|
|
1546
1900
|
this.disk.delete(k);
|
|
1547
1901
|
}
|
|
1548
|
-
if (!this._redisDisabled) {
|
|
1902
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1549
1903
|
try {
|
|
1550
1904
|
const client = await this.getRedis();
|
|
1551
1905
|
if (isPattern) {
|
|
@@ -1572,8 +1926,18 @@ var CacheService = class _CacheService {
|
|
|
1572
1926
|
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
1573
1927
|
*/
|
|
1574
1928
|
async increment(cacheKey, ttlSeconds) {
|
|
1575
|
-
if (this._redisDisabled) return 0;
|
|
1576
1929
|
const k = this.nk(cacheKey);
|
|
1930
|
+
if (this._redisDisabled) {
|
|
1931
|
+
const now = Date.now();
|
|
1932
|
+
const ttlMs = (ttlSeconds ?? 60) * 1e3;
|
|
1933
|
+
const entry = this._l1Counters.get(k);
|
|
1934
|
+
if (entry && entry.expiresAt > now) {
|
|
1935
|
+
entry.value++;
|
|
1936
|
+
return entry.value;
|
|
1937
|
+
}
|
|
1938
|
+
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
1939
|
+
return 1;
|
|
1940
|
+
}
|
|
1577
1941
|
try {
|
|
1578
1942
|
const client = await this.getRedis();
|
|
1579
1943
|
const count = await client.incr(k);
|
|
@@ -1584,7 +1948,262 @@ var CacheService = class _CacheService {
|
|
|
1584
1948
|
return 0;
|
|
1585
1949
|
}
|
|
1586
1950
|
}
|
|
1587
|
-
// ──
|
|
1951
|
+
// ── Clear / Rebalance / TTL ────────────────────────────────────────────────
|
|
1952
|
+
/**
|
|
1953
|
+
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
1954
|
+
*
|
|
1955
|
+
* @example
|
|
1956
|
+
* await cache.clear(); // flush everything
|
|
1957
|
+
* await cache.clear('user:abc'); // flush all keys for one user
|
|
1958
|
+
*/
|
|
1959
|
+
async clear(prefix) {
|
|
1960
|
+
this.counters.deletes++;
|
|
1961
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
1962
|
+
if (k) {
|
|
1963
|
+
this.l1.deletePattern(k);
|
|
1964
|
+
} else {
|
|
1965
|
+
this.l1.clear();
|
|
1966
|
+
this.disk.clear();
|
|
1967
|
+
this._l1Counters.clear();
|
|
1968
|
+
this.tagIndex.clear();
|
|
1969
|
+
}
|
|
1970
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1971
|
+
try {
|
|
1972
|
+
const client = await this.getRedis();
|
|
1973
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
1974
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
1975
|
+
const keys = [];
|
|
1976
|
+
await new Promise((resolve, reject) => {
|
|
1977
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
1978
|
+
stream.on("end", resolve);
|
|
1979
|
+
stream.on("error", reject);
|
|
1980
|
+
});
|
|
1981
|
+
if (keys.length > 0) await client.del(...keys);
|
|
1982
|
+
} catch (err) {
|
|
1983
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
void this.publishInvalidation(
|
|
1987
|
+
"del-glob",
|
|
1988
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
1989
|
+
);
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* Evict L1 entries that violate the current category or global capacity limits.
|
|
1993
|
+
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
1994
|
+
* Returns the number of entries evicted.
|
|
1995
|
+
*/
|
|
1996
|
+
rebalance() {
|
|
1997
|
+
return this.l1.rebalance();
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* Return the remaining TTL in seconds for a key currently in L1.
|
|
2001
|
+
* Returns null if the key is absent from L1 or has already expired.
|
|
2002
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
2003
|
+
*/
|
|
2004
|
+
ttl(cacheKey) {
|
|
2005
|
+
return this.l1.ttl(this.nk(cacheKey));
|
|
2006
|
+
}
|
|
2007
|
+
/**
|
|
2008
|
+
* Return true if the key exists in L1 and has not expired.
|
|
2009
|
+
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
2010
|
+
*/
|
|
2011
|
+
has(cacheKey) {
|
|
2012
|
+
return this.l1.has(this.nk(cacheKey));
|
|
2013
|
+
}
|
|
2014
|
+
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
2015
|
+
/**
|
|
2016
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
2017
|
+
*
|
|
2018
|
+
* @example
|
|
2019
|
+
* for (const key of cache.keys()) console.log(key);
|
|
2020
|
+
*/
|
|
2021
|
+
*keys() {
|
|
2022
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2023
|
+
for (const key of this.l1.liveKeys()) {
|
|
2024
|
+
yield prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Lazily yield every non-expired L1 value.
|
|
2029
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
2030
|
+
*
|
|
2031
|
+
* @example
|
|
2032
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
2033
|
+
*/
|
|
2034
|
+
*values() {
|
|
2035
|
+
yield* this.l1.liveValues();
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
2039
|
+
* Keys are stripped of their namespace prefix.
|
|
2040
|
+
*
|
|
2041
|
+
* @example
|
|
2042
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
2043
|
+
*/
|
|
2044
|
+
*entries() {
|
|
2045
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2046
|
+
for (const [key, entry] of this.l1.liveEntries()) {
|
|
2047
|
+
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2048
|
+
yield [k, entry.value !== void 0 ? entry.value : entry.data];
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
2053
|
+
* Returns `false` if the key is absent or already expired.
|
|
2054
|
+
*
|
|
2055
|
+
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
2056
|
+
*/
|
|
2057
|
+
async touch(cacheKey, newTtlSeconds) {
|
|
2058
|
+
const k = this.nk(cacheKey);
|
|
2059
|
+
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
2060
|
+
if (hit && !this._redisDisabled) {
|
|
2061
|
+
try {
|
|
2062
|
+
const client = await this.getRedis();
|
|
2063
|
+
void client.expire(k, newTtlSeconds);
|
|
2064
|
+
} catch {
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
return hit;
|
|
2068
|
+
}
|
|
2069
|
+
/**
|
|
2070
|
+
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
2071
|
+
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
2072
|
+
*
|
|
2073
|
+
* @example
|
|
2074
|
+
* const fresh = cache.getIfFresh('user:123');
|
|
2075
|
+
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
2076
|
+
*/
|
|
2077
|
+
getIfFresh(cacheKey) {
|
|
2078
|
+
const k = this.nk(cacheKey);
|
|
2079
|
+
const entry = this.l1.getEntry(k);
|
|
2080
|
+
if (!entry) return null;
|
|
2081
|
+
const now = Date.now();
|
|
2082
|
+
if (entry.expiresAt <= now) return null;
|
|
2083
|
+
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
2084
|
+
return entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
2088
|
+
* Preserves input ordering. Uses inflight coalescing per key.
|
|
2089
|
+
*
|
|
2090
|
+
* @param keys - Array of cache keys.
|
|
2091
|
+
* @param fetchFn - Called with only the keys that missed L1.
|
|
2092
|
+
* @param ttl - TTL in seconds for newly fetched values.
|
|
2093
|
+
*/
|
|
2094
|
+
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
2095
|
+
const result = new Array(keys.length);
|
|
2096
|
+
const missIndexes = [];
|
|
2097
|
+
const missKeys = [];
|
|
2098
|
+
for (let i = 0; i < keys.length; i++) {
|
|
2099
|
+
const entry = this.l1.getEntry(this.nk(keys[i]));
|
|
2100
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
2101
|
+
result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
2102
|
+
this.counters.l1Hits++;
|
|
2103
|
+
} else {
|
|
2104
|
+
missIndexes.push(i);
|
|
2105
|
+
missKeys.push(keys[i]);
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
if (missKeys.length > 0) {
|
|
2109
|
+
const fetched = await fetchFn(missKeys);
|
|
2110
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
2111
|
+
const v = fetched[missKeys[j]];
|
|
2112
|
+
result[missIndexes[j]] = v;
|
|
2113
|
+
if (v !== void 0) {
|
|
2114
|
+
await this.set(missKeys[j], v, ttl, priority);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
return result;
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Invalidate all keys associated with a tag.
|
|
2122
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
2123
|
+
*
|
|
2124
|
+
* @example
|
|
2125
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
2126
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
2127
|
+
*/
|
|
2128
|
+
async invalidateTag(tag) {
|
|
2129
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
2130
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
2131
|
+
for (const k of members) {
|
|
2132
|
+
this.l1.delete(k);
|
|
2133
|
+
this.disk.delete(k);
|
|
2134
|
+
}
|
|
2135
|
+
this.tagIndex.delete(tagKey);
|
|
2136
|
+
if (!this._redisDisabled) {
|
|
2137
|
+
try {
|
|
2138
|
+
const client = await this.getRedis();
|
|
2139
|
+
const redisMembers = await client.smembers(tagKey);
|
|
2140
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
2141
|
+
if (toDelete.length > 0) {
|
|
2142
|
+
await client.del(...toDelete, tagKey);
|
|
2143
|
+
} else {
|
|
2144
|
+
await client.del(tagKey);
|
|
2145
|
+
}
|
|
2146
|
+
} catch (err) {
|
|
2147
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
/**
|
|
2152
|
+
* Measure L1 / disk / Redis latency.
|
|
2153
|
+
* Useful for health checks and dashboards.
|
|
2154
|
+
*
|
|
2155
|
+
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
2156
|
+
* `l2` is `null` when Redis is disabled.
|
|
2157
|
+
*/
|
|
2158
|
+
async ping() {
|
|
2159
|
+
const t0 = Date.now();
|
|
2160
|
+
this.l1.has("__ping__");
|
|
2161
|
+
const l1 = Date.now() - t0;
|
|
2162
|
+
const t1 = Date.now();
|
|
2163
|
+
void this.disk.stats;
|
|
2164
|
+
const disk = Date.now() - t1;
|
|
2165
|
+
let l2 = null;
|
|
2166
|
+
if (!this._redisDisabled) {
|
|
2167
|
+
try {
|
|
2168
|
+
const client = await this.getRedis();
|
|
2169
|
+
const t2 = Date.now();
|
|
2170
|
+
await client.ping();
|
|
2171
|
+
l2 = Date.now() - t2;
|
|
2172
|
+
} catch {
|
|
2173
|
+
l2 = null;
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
return { l1, disk, l2 };
|
|
2177
|
+
}
|
|
2178
|
+
/**
|
|
2179
|
+
* Export all live L1 entries to Redis via a single pipeline.
|
|
2180
|
+
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
2181
|
+
* Returns the number of keys written.
|
|
2182
|
+
*/
|
|
2183
|
+
async drainToL2() {
|
|
2184
|
+
if (this._redisDisabled) return 0;
|
|
2185
|
+
try {
|
|
2186
|
+
const client = await this.getRedis();
|
|
2187
|
+
const entries = this.l1.exportEntries([]);
|
|
2188
|
+
const now = Date.now();
|
|
2189
|
+
if (entries.length === 0) return 0;
|
|
2190
|
+
const pl = client.pipeline();
|
|
2191
|
+
for (const { key, entry } of entries) {
|
|
2192
|
+
const remainingMs = entry.expiresAt - now;
|
|
2193
|
+
if (remainingMs <= 0) continue;
|
|
2194
|
+
const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
|
|
2195
|
+
const s = JSON.stringify(entry.value);
|
|
2196
|
+
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
2197
|
+
pl.setex(key, ttlSecs, stored);
|
|
2198
|
+
}
|
|
2199
|
+
await pl.exec();
|
|
2200
|
+
return entries.length;
|
|
2201
|
+
} catch (err) {
|
|
2202
|
+
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
2203
|
+
return 0;
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
// ── Stats ─────────────────────────────────────────────────────────────
|
|
1588
2207
|
stats() {
|
|
1589
2208
|
return {
|
|
1590
2209
|
l1: this.l1.getStats(),
|
|
@@ -1651,8 +2270,11 @@ var CacheService = class _CacheService {
|
|
|
1651
2270
|
* @param m - Snapshot returned by `cache.metrics()`
|
|
1652
2271
|
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
1653
2272
|
*/
|
|
1654
|
-
static toPrometheusText(m, prefix = "tricache") {
|
|
1655
|
-
const
|
|
2273
|
+
static toPrometheusText(m, prefix = "tricache", instanceName) {
|
|
2274
|
+
const parts = [];
|
|
2275
|
+
if (m.namespace) parts.push(`namespace="${m.namespace}"`);
|
|
2276
|
+
if (instanceName) parts.push(`instance="${instanceName}"`);
|
|
2277
|
+
const lbl = parts.length ? `{${parts.join(",")}}` : "";
|
|
1656
2278
|
const lines = [];
|
|
1657
2279
|
const counter = (name, val, help) => {
|
|
1658
2280
|
lines.push(`# HELP ${prefix}_${name}_total ${help}`);
|