tricache 0.4.0 → 0.5.1
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 +81 -27
- package/dist/index.cjs +567 -133
- package/dist/index.d.cts +174 -10
- package/dist/index.d.ts +174 -10
- package/dist/index.js +567 -133
- package/package.json +2 -2
- package/src/cache-service.ts +233 -48
- package/src/disk-tier.ts +263 -25
- package/src/encryption.ts +14 -12
- package/src/smart-memory-cache.ts +187 -39
- package/src/types.ts +43 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"license": "MIT",
|
|
21
|
-
"packageManager": "pnpm@11.0
|
|
21
|
+
"packageManager": "pnpm@11.3.0",
|
|
22
22
|
"type": "module",
|
|
23
23
|
"main": "./dist/index.js",
|
|
24
24
|
"module": "./dist/index.js",
|
package/src/cache-service.ts
CHANGED
|
@@ -112,6 +112,18 @@ class L2CircuitBreaker {
|
|
|
112
112
|
// Priority inference — override by passing priority explicitly to get()
|
|
113
113
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
114
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Recursively freezes an object and all its nested properties.
|
|
117
|
+
* Used only when `CacheOptions.frozen` is true (dev/test mode).
|
|
118
|
+
* Already-frozen objects are skipped to avoid redundant traversal.
|
|
119
|
+
*/
|
|
120
|
+
function deepFreeze<T>(obj: T): T {
|
|
121
|
+
if (obj === null || typeof obj !== 'object' || Object.isFrozen(obj)) return obj;
|
|
122
|
+
Object.freeze(obj);
|
|
123
|
+
for (const v of Object.values(obj as object)) deepFreeze(v);
|
|
124
|
+
return obj;
|
|
125
|
+
}
|
|
126
|
+
|
|
115
127
|
function inferPriority(cacheKey: string): CachePriority {
|
|
116
128
|
if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
|
|
117
129
|
if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
|
|
@@ -150,6 +162,10 @@ export class CacheService {
|
|
|
150
162
|
ttlJitterFactor: number;
|
|
151
163
|
tracer: ICacheTracer | undefined;
|
|
152
164
|
notFoundTtl: number;
|
|
165
|
+
warmKeys: string | undefined;
|
|
166
|
+
onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
|
|
167
|
+
onMiss: ((key: string) => void) | undefined;
|
|
168
|
+
frozen: boolean;
|
|
153
169
|
};
|
|
154
170
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
155
171
|
private readonly _namespace: string;
|
|
@@ -169,7 +185,9 @@ export class CacheService {
|
|
|
169
185
|
private redisConnecting: Promise<RedisClient> | null = null;
|
|
170
186
|
private readonly cb: L2CircuitBreaker;
|
|
171
187
|
private snapshotLoaded = false;
|
|
188
|
+
private _readyPromise: Promise<void> = Promise.resolve();
|
|
172
189
|
private cleanupInterval: ReturnType<typeof setInterval> | null = null;
|
|
190
|
+
private diskJanitorInterval: ReturnType<typeof setInterval> | null = null;
|
|
173
191
|
private oomInterval: ReturnType<typeof setInterval> | null = null;
|
|
174
192
|
private metricsInterval: ReturnType<typeof setInterval> | null = null;
|
|
175
193
|
private _shutdownHandler: (() => void) | null = null;
|
|
@@ -255,6 +273,10 @@ export class CacheService {
|
|
|
255
273
|
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
256
274
|
tracer: options.tracer,
|
|
257
275
|
notFoundTtl: options.notFoundTtl ?? 0,
|
|
276
|
+
warmKeys: options.warmKeys,
|
|
277
|
+
onHit: options.onHit,
|
|
278
|
+
onMiss: options.onMiss,
|
|
279
|
+
frozen: options.frozen ?? false,
|
|
258
280
|
};
|
|
259
281
|
|
|
260
282
|
// Circuit breaker for L2 Redis
|
|
@@ -280,7 +302,13 @@ export class CacheService {
|
|
|
280
302
|
maxBytes: this.opts.l1MaxBytes,
|
|
281
303
|
maxEntries: this.opts.l1MaxEntries,
|
|
282
304
|
categories: this.opts.categoryLimits,
|
|
283
|
-
diskSpill:
|
|
305
|
+
diskSpill: (key: string, entry: SmartCacheEntry) => {
|
|
306
|
+
// Defer disk.save() entirely to the next event-loop tick so the synchronous
|
|
307
|
+
// preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
|
|
308
|
+
// the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
|
|
309
|
+
// backplane handler already does for remote invalidations.
|
|
310
|
+
setImmediate(() => { void this.disk.save(key, entry as unknown as DiskCacheEntry); });
|
|
311
|
+
},
|
|
284
312
|
onEviction: options.onEviction,
|
|
285
313
|
logger,
|
|
286
314
|
});
|
|
@@ -296,16 +324,24 @@ export class CacheService {
|
|
|
296
324
|
process.once('SIGTERM', this._shutdownHandler);
|
|
297
325
|
process.once('SIGINT', this._shutdownHandler);
|
|
298
326
|
|
|
299
|
-
// Periodic cleanup (5 min)
|
|
327
|
+
// Periodic L1 cleanup (5 min): expires stale entries and rebalances frequency counters.
|
|
328
|
+
// Disk cleanup is handled entirely by the janitor below — purgeExpired() is NOT called
|
|
329
|
+
// here to avoid a synchronous O(fileCount) event-loop stall at scale.
|
|
300
330
|
this.cleanupInterval = setInterval(() => {
|
|
301
331
|
const cleaned = this.l1.cleanup();
|
|
302
|
-
|
|
303
|
-
if (cleaned > 0 || diskPurged > 0) {
|
|
304
|
-
this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
|
|
305
|
-
}
|
|
332
|
+
if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
|
|
306
333
|
}, 5 * 60 * 1000);
|
|
307
334
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
|
|
308
335
|
|
|
336
|
+
// Disk janitor: sole owner of disk expiry. Scans one of 256 subdirectory buckets per tick
|
|
337
|
+
// (30 s × 256 = 128-min full cycle). Each tick is bounded to one bucket's worth of
|
|
338
|
+
// readFileSync + decrypt + unpack work, capping per-tick event-loop occupancy.
|
|
339
|
+
this.diskJanitorInterval = setInterval(() => {
|
|
340
|
+
const purged = this.disk.purgeNextBucket();
|
|
341
|
+
if (purged > 0) this.logger.debug('Disk janitor tick', { purged });
|
|
342
|
+
}, 30_000);
|
|
343
|
+
if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
|
|
344
|
+
|
|
309
345
|
// OOM protection: evict coldest L1 entries when heap pressure rises
|
|
310
346
|
if (this.opts.oomProtection) {
|
|
311
347
|
this.oomInterval = setInterval(() => {
|
|
@@ -337,6 +373,11 @@ export class CacheService {
|
|
|
337
373
|
this.instanceId = crypto.randomBytes(8).toString('hex');
|
|
338
374
|
this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
|
|
339
375
|
this.initBackplane();
|
|
376
|
+
|
|
377
|
+
// Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
|
|
378
|
+
if (this.opts.warmKeys) {
|
|
379
|
+
this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
|
|
380
|
+
}
|
|
340
381
|
}
|
|
341
382
|
|
|
342
383
|
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
@@ -405,10 +446,18 @@ export class CacheService {
|
|
|
405
446
|
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
406
447
|
}
|
|
407
448
|
|
|
449
|
+
/** Shared no-op span for the common case where no tracer is configured.
|
|
450
|
+
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
451
|
+
private static readonly _nullSpan: ICacheSpan = {
|
|
452
|
+
setAttribute() { return this; },
|
|
453
|
+
setStatus() { return this; },
|
|
454
|
+
end() {},
|
|
455
|
+
};
|
|
456
|
+
|
|
408
457
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
409
458
|
private _startSpan(name: string): ICacheSpan {
|
|
410
459
|
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
411
|
-
return
|
|
460
|
+
return CacheService._nullSpan;
|
|
412
461
|
}
|
|
413
462
|
|
|
414
463
|
private initBackplane(): void {
|
|
@@ -460,6 +509,11 @@ export class CacheService {
|
|
|
460
509
|
// message returns immediately without blocking hot get() calls.
|
|
461
510
|
this.l1.delete(msg.key);
|
|
462
511
|
setImmediate(() => this.disk.delete(msg.key));
|
|
512
|
+
// Cascade: evict dependents registered on this instance for the
|
|
513
|
+
// deleted key — same logic the local delete() path runs, now also
|
|
514
|
+
// applied to peer-originated invalidations so fleet-wide deletes
|
|
515
|
+
// propagate dependency cascades to every node.
|
|
516
|
+
this._cascadeDependencies(msg.key);
|
|
463
517
|
} else if (msg.op === 'del-glob') {
|
|
464
518
|
// Glob patterns clean L1 only — disk entries expire naturally via
|
|
465
519
|
// the background purge timer or are bypassed on the next L1 miss.
|
|
@@ -632,10 +686,17 @@ export class CacheService {
|
|
|
632
686
|
refreshAhead?: number; // 0–1: trigger background recompute at this fraction of TTL elapsed
|
|
633
687
|
xfetchBeta?: number; // > 0: XFetch probabilistic early expiration (uses stored delta)
|
|
634
688
|
notFoundTtl?: number; // seconds; cache null/undefined results with this TTL instead
|
|
689
|
+
/**
|
|
690
|
+
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
691
|
+
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
692
|
+
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
693
|
+
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
694
|
+
*/
|
|
695
|
+
tags?: string[];
|
|
635
696
|
} = {},
|
|
636
697
|
): Promise<T> {
|
|
637
698
|
const span = this._startSpan('tricache.get');
|
|
638
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
699
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
639
700
|
const k = this.nk(cacheKey); // namespaced key used for all storage
|
|
640
701
|
this.counters.gets++;
|
|
641
702
|
|
|
@@ -657,23 +718,29 @@ export class CacheService {
|
|
|
657
718
|
this.logger.debug('L1 hit');
|
|
658
719
|
// Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
|
|
659
720
|
// l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
|
|
660
|
-
|
|
661
|
-
|
|
721
|
+
// Check opts first — pointless work when neither feature is configured.
|
|
722
|
+
if (opts.refreshAhead || opts.xfetchBeta) {
|
|
723
|
+
// Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
|
|
724
|
+
const now = l1Hit.fetchedAt ?? Date.now();
|
|
662
725
|
const remaining = l1Hit.expiresAt - now;
|
|
663
726
|
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
|
|
664
|
-
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
665
727
|
|
|
666
|
-
const shouldRefreshAhead = opts.refreshAhead
|
|
728
|
+
const shouldRefreshAhead = !!opts.refreshAhead
|
|
667
729
|
? remaining <= entryTtl * (1 - opts.refreshAhead)
|
|
668
730
|
: false;
|
|
669
731
|
|
|
670
732
|
// XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
|
|
671
733
|
// Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
|
|
672
|
-
const shouldXFetch = opts.xfetchBeta
|
|
734
|
+
const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null
|
|
673
735
|
? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
|
|
674
736
|
: false;
|
|
675
737
|
|
|
676
|
-
|
|
738
|
+
// Set.has() deferred to here — the common case (fresh key, threshold not crossed)
|
|
739
|
+
// never pays the ~30 ns lookup cost.
|
|
740
|
+
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
741
|
+
// Defer inferPriority until we actually need it — avoids 3× string.includes()
|
|
742
|
+
// scans on every warm hit when the threshold check is false (the common case).
|
|
743
|
+
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
677
744
|
this.revalidating.add(k);
|
|
678
745
|
void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
|
|
679
746
|
this.counters.swrRevalidations++;
|
|
@@ -685,6 +752,8 @@ export class CacheService {
|
|
|
685
752
|
}
|
|
686
753
|
}
|
|
687
754
|
this.counters.l1Hits++;
|
|
755
|
+
this.opts.onHit?.(cacheKey, 'l1');
|
|
756
|
+
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
688
757
|
span.setAttribute('cache.hit', 'l1').end();
|
|
689
758
|
return l1Hit.value as T;
|
|
690
759
|
}
|
|
@@ -704,6 +773,7 @@ export class CacheService {
|
|
|
704
773
|
const parsed = JSON.parse(decrypted) as T;
|
|
705
774
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
706
775
|
this.counters.l2Hits++;
|
|
776
|
+
this.opts.onHit?.(cacheKey, 'l2');
|
|
707
777
|
this.logger.debug('L2 hit (Redis)', { cacheKey });
|
|
708
778
|
span.setAttribute('cache.hit', 'l2').end();
|
|
709
779
|
return parsed;
|
|
@@ -725,6 +795,7 @@ export class CacheService {
|
|
|
725
795
|
const l1Check = this.l1.get(k);
|
|
726
796
|
if (l1Check !== null) {
|
|
727
797
|
this.counters.diskHits++;
|
|
798
|
+
this.opts.onHit?.(cacheKey, 'disk');
|
|
728
799
|
this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
|
|
729
800
|
span.setAttribute('cache.hit', 'disk').end();
|
|
730
801
|
return l1Check.value as T;
|
|
@@ -733,6 +804,7 @@ export class CacheService {
|
|
|
733
804
|
}
|
|
734
805
|
|
|
735
806
|
span.setAttribute('cache.hit', 'miss');
|
|
807
|
+
this.opts.onMiss?.(cacheKey);
|
|
736
808
|
|
|
737
809
|
// Cache MISS: thundering-herd prevention
|
|
738
810
|
const existing = this.inflight.get(k);
|
|
@@ -758,6 +830,7 @@ export class CacheService {
|
|
|
758
830
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
759
831
|
|
|
760
832
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta);
|
|
833
|
+
if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1_000));
|
|
761
834
|
|
|
762
835
|
if (!this._redisDisabled) {
|
|
763
836
|
try {
|
|
@@ -829,35 +902,14 @@ export class CacheService {
|
|
|
829
902
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
830
903
|
async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
|
|
831
904
|
const span = this._startSpan('tricache.set');
|
|
832
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
905
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
833
906
|
const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
|
|
834
907
|
const p = priority ?? inferPriority(cacheKey);
|
|
835
908
|
const k = this.nk(cacheKey);
|
|
836
909
|
this.counters.sets++;
|
|
837
910
|
this.l1.set(k, data, ttlMs, p);
|
|
838
911
|
|
|
839
|
-
|
|
840
|
-
if (opts?.tags?.length) {
|
|
841
|
-
for (const tag of opts.tags) {
|
|
842
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
843
|
-
let members = this.tagIndex.get(tagKey);
|
|
844
|
-
if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
|
|
845
|
-
members.add(k);
|
|
846
|
-
}
|
|
847
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
|
|
848
|
-
try {
|
|
849
|
-
const client = await this.getRedis();
|
|
850
|
-
const pl = client.pipeline();
|
|
851
|
-
for (const tag of opts.tags) {
|
|
852
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
853
|
-
pl.sadd(tagKey, k);
|
|
854
|
-
pl.expire(tagKey, ttlSeconds + 3_600);
|
|
855
|
-
}
|
|
856
|
-
await pl.exec();
|
|
857
|
-
this.cb.onSuccess();
|
|
858
|
-
} catch { this.cb.onFailure(); /* tags are best-effort */ }
|
|
859
|
-
}
|
|
860
|
-
}
|
|
912
|
+
if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
|
|
861
913
|
|
|
862
914
|
// Register dependency patterns: when any key matching a pattern is deleted,
|
|
863
915
|
// this key (k) is automatically cascaded.
|
|
@@ -887,6 +939,32 @@ export class CacheService {
|
|
|
887
939
|
span.end();
|
|
888
940
|
}
|
|
889
941
|
|
|
942
|
+
/**
|
|
943
|
+
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
944
|
+
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
945
|
+
*/
|
|
946
|
+
private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
|
|
947
|
+
for (const tag of tags) {
|
|
948
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
949
|
+
let members = this.tagIndex.get(tagKey);
|
|
950
|
+
if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
|
|
951
|
+
members.add(k);
|
|
952
|
+
}
|
|
953
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
|
|
954
|
+
try {
|
|
955
|
+
const client = await this.getRedis();
|
|
956
|
+
const pl = client.pipeline();
|
|
957
|
+
for (const tag of tags) {
|
|
958
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
959
|
+
pl.sadd(tagKey, k);
|
|
960
|
+
pl.expire(tagKey, ttlSeconds + 3_600);
|
|
961
|
+
}
|
|
962
|
+
await pl.exec();
|
|
963
|
+
this.cb.onSuccess();
|
|
964
|
+
} catch { this.cb.onFailure(); /* tags are best-effort */ }
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
890
968
|
/**
|
|
891
969
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
892
970
|
*
|
|
@@ -896,7 +974,7 @@ export class CacheService {
|
|
|
896
974
|
*/
|
|
897
975
|
async delete(cacheKey: string): Promise<void> {
|
|
898
976
|
const span = this._startSpan('tricache.delete');
|
|
899
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
977
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
900
978
|
const isPattern = cacheKey.includes('*');
|
|
901
979
|
const k = this.nk(cacheKey);
|
|
902
980
|
this.counters.deletes++;
|
|
@@ -905,7 +983,13 @@ export class CacheService {
|
|
|
905
983
|
this.l1.deletePattern(k);
|
|
906
984
|
} else {
|
|
907
985
|
this.l1.delete(k);
|
|
908
|
-
|
|
986
|
+
// Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
|
|
987
|
+
// the caller's await resolves without blocking. Matches what the backplane handler
|
|
988
|
+
// already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
|
|
989
|
+
// A re-get in the narrow window before the deferred call fires would get an L1 miss
|
|
990
|
+
// and promote the disk entry back — acceptable for a cache (same trade-off the backplane
|
|
991
|
+
// path already accepts).
|
|
992
|
+
setImmediate(() => this.disk.delete(k));
|
|
909
993
|
// Cascade: invalidate any key that declared it depends on this exact key's pattern
|
|
910
994
|
this._cascadeDependencies(k);
|
|
911
995
|
// Clean up: remove k from all dependency registrations (it is gone)
|
|
@@ -1085,6 +1169,34 @@ export class CacheService {
|
|
|
1085
1169
|
}
|
|
1086
1170
|
}
|
|
1087
1171
|
|
|
1172
|
+
/**
|
|
1173
|
+
* High-throughput bulk scan over all live L1 entries.
|
|
1174
|
+
*
|
|
1175
|
+
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
1176
|
+
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
1177
|
+
* caller uses the `offset` parameter instead of pre-slicing.
|
|
1178
|
+
*
|
|
1179
|
+
* ```typescript
|
|
1180
|
+
* // Zero extra string allocations — use rawKey + offset directly:
|
|
1181
|
+
* cache.scan((rawKey, value, offset) => {
|
|
1182
|
+
* const key = rawKey.slice(offset); // allocate only if needed
|
|
1183
|
+
* sync(key, value as User);
|
|
1184
|
+
* });
|
|
1185
|
+
* ```
|
|
1186
|
+
*
|
|
1187
|
+
* @param fn Called once per live L1 entry.
|
|
1188
|
+
* `rawKey` — key with namespace prefix still attached.
|
|
1189
|
+
* `value` — deserialized cached value.
|
|
1190
|
+
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
1191
|
+
*/
|
|
1192
|
+
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
|
|
1193
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
1194
|
+
this.l1.scan((key, entry, pfx) => {
|
|
1195
|
+
const value = (entry.value !== undefined ? entry.value : entry.data) as T;
|
|
1196
|
+
fn(key, value, pfx);
|
|
1197
|
+
}, prefixLen);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1088
1200
|
/**
|
|
1089
1201
|
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
1090
1202
|
* Returns `false` if the key is absent or already expired.
|
|
@@ -1127,12 +1239,13 @@ export class CacheService {
|
|
|
1127
1239
|
*
|
|
1128
1240
|
* @param keys - Array of cache keys.
|
|
1129
1241
|
* @param fetchFn - Called with only the keys that missed L1.
|
|
1130
|
-
* @param ttl - TTL in seconds for newly fetched values.
|
|
1242
|
+
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
1243
|
+
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
1131
1244
|
*/
|
|
1132
1245
|
async mget<T>(
|
|
1133
1246
|
keys: string[],
|
|
1134
1247
|
fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
|
|
1135
|
-
ttl = 300,
|
|
1248
|
+
ttl: number | ((key: string) => number) = 300,
|
|
1136
1249
|
priority?: CachePriority,
|
|
1137
1250
|
): Promise<(T | undefined)[]> {
|
|
1138
1251
|
const result: (T | undefined)[] = new Array(keys.length);
|
|
@@ -1156,7 +1269,8 @@ export class CacheService {
|
|
|
1156
1269
|
const v = fetched[missKeys[j]];
|
|
1157
1270
|
result[missIndexes[j]] = v;
|
|
1158
1271
|
if (v !== undefined) {
|
|
1159
|
-
|
|
1272
|
+
const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
|
|
1273
|
+
await this.set(missKeys[j], v, resolvedTtl, priority);
|
|
1160
1274
|
}
|
|
1161
1275
|
}
|
|
1162
1276
|
}
|
|
@@ -1164,6 +1278,21 @@ export class CacheService {
|
|
|
1164
1278
|
return result;
|
|
1165
1279
|
}
|
|
1166
1280
|
|
|
1281
|
+
/**
|
|
1282
|
+
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
1283
|
+
* startup warming configured via `warmKeys` has completed.
|
|
1284
|
+
*
|
|
1285
|
+
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
1286
|
+
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
1287
|
+
*
|
|
1288
|
+
* @example
|
|
1289
|
+
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
1290
|
+
* await cache.ready(); // gate traffic until warm
|
|
1291
|
+
*/
|
|
1292
|
+
ready(): Promise<void> {
|
|
1293
|
+
return this._readyPromise;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1167
1296
|
/**
|
|
1168
1297
|
* Batch write — set multiple entries in a single call.
|
|
1169
1298
|
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
@@ -1208,7 +1337,7 @@ export class CacheService {
|
|
|
1208
1337
|
* const loaded = await cache.warmFromL2('org:*');
|
|
1209
1338
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
1210
1339
|
*/
|
|
1211
|
-
async warmFromL2(pattern: string): Promise<number> {
|
|
1340
|
+
async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
|
|
1212
1341
|
if (this._redisDisabled) return 0;
|
|
1213
1342
|
try {
|
|
1214
1343
|
const client = await this.getRedis();
|
|
@@ -1245,8 +1374,8 @@ export class CacheService {
|
|
|
1245
1374
|
// Use a 10-minute TTL as a reasonable default; the real TTL is not
|
|
1246
1375
|
// returned by GET (use PTTL to be precise, but that doubles round-trips).
|
|
1247
1376
|
const remainingMs = 10 * 60 * 1_000;
|
|
1248
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
1249
|
-
loaded
|
|
1377
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
|
|
1378
|
+
loaded++;;
|
|
1250
1379
|
} catch { /* skip malformed entries */ }
|
|
1251
1380
|
}
|
|
1252
1381
|
void now; // suppress unused warning
|
|
@@ -1297,6 +1426,61 @@ export class CacheService {
|
|
|
1297
1426
|
}
|
|
1298
1427
|
}
|
|
1299
1428
|
|
|
1429
|
+
/**
|
|
1430
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
1431
|
+
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
1432
|
+
* reducing latency when invalidating several related tags together.
|
|
1433
|
+
*
|
|
1434
|
+
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
1435
|
+
* synchronously before the Redis round-trip.
|
|
1436
|
+
*
|
|
1437
|
+
* @example
|
|
1438
|
+
* // Instead of three serial round-trips:
|
|
1439
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
1440
|
+
*/
|
|
1441
|
+
async invalidateTags(tags: string[]): Promise<void> {
|
|
1442
|
+
if (tags.length === 0) return;
|
|
1443
|
+
if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
|
|
1444
|
+
|
|
1445
|
+
// In-process: collect all member keys across all tags and remove from L1 + disk
|
|
1446
|
+
const tagKeys: string[] = [];
|
|
1447
|
+
const allMembers = new Set<string>();
|
|
1448
|
+
for (const tag of tags) {
|
|
1449
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1450
|
+
tagKeys.push(tagKey);
|
|
1451
|
+
const members = this.tagIndex.get(tagKey) ?? new Set<string>();
|
|
1452
|
+
for (const k of members) allMembers.add(k);
|
|
1453
|
+
this.tagIndex.delete(tagKey);
|
|
1454
|
+
}
|
|
1455
|
+
for (const k of allMembers) {
|
|
1456
|
+
this.l1.delete(k);
|
|
1457
|
+
this.disk.delete(k);
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
if (!this._redisDisabled) {
|
|
1461
|
+
try {
|
|
1462
|
+
const client = await this.getRedis();
|
|
1463
|
+
// Single round-trip: pipeline SMEMBERS for all tag keys
|
|
1464
|
+
const pl = client.pipeline();
|
|
1465
|
+
for (const tagKey of tagKeys) pl.smembers(tagKey);
|
|
1466
|
+
const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
|
|
1467
|
+
|
|
1468
|
+
// Merge Redis members into the master delete set
|
|
1469
|
+
const toDelete: string[] = [...allMembers];
|
|
1470
|
+
for (const [err, redisMembers] of smResults) {
|
|
1471
|
+
if (!err && redisMembers) {
|
|
1472
|
+
for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
// Single DEL for all member keys + tag keys
|
|
1476
|
+
const keysToRemove = [...toDelete, ...tagKeys];
|
|
1477
|
+
if (keysToRemove.length > 0) await client.del(...keysToRemove);
|
|
1478
|
+
} catch (err) {
|
|
1479
|
+
this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1300
1484
|
/**
|
|
1301
1485
|
* Measure L1 / disk / Redis latency.
|
|
1302
1486
|
* Useful for health checks and dashboards.
|
|
@@ -1601,9 +1785,10 @@ export class CacheService {
|
|
|
1601
1785
|
|
|
1602
1786
|
/** Close Redis connections and stop all background timers. */
|
|
1603
1787
|
async destroy(): Promise<void> {
|
|
1604
|
-
if (this.cleanupInterval)
|
|
1605
|
-
if (this.
|
|
1606
|
-
if (this.
|
|
1788
|
+
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
1789
|
+
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
1790
|
+
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
1791
|
+
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
1607
1792
|
if (this._shutdownHandler) {
|
|
1608
1793
|
process.off('SIGTERM', this._shutdownHandler);
|
|
1609
1794
|
process.off('SIGINT', this._shutdownHandler);
|