tricache 0.5.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 +18 -0
- package/dist/index.cjs +518 -112
- package/dist/index.d.cts +152 -8
- package/dist/index.d.ts +1310 -18
- package/dist/index.js +3131 -25
- package/package.json +11 -10
- package/src/cache-service.ts +197 -44
- package/src/disk-tier.ts +263 -25
- package/src/encryption.ts +14 -12
- package/src/smart-memory-cache.ts +152 -13
- package/src/types.ts +37 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
- package/dist/cache-service.d.ts +0 -366
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1494
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -83
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -324
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -88
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -371
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -178
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -753
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -428
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -99
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.5.
|
|
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,6 +18,7 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"license": "MIT",
|
|
21
|
+
"packageManager": "pnpm@11.3.0",
|
|
21
22
|
"type": "module",
|
|
22
23
|
"main": "./dist/index.js",
|
|
23
24
|
"module": "./dist/index.js",
|
|
@@ -35,6 +36,14 @@
|
|
|
35
36
|
"README.md",
|
|
36
37
|
"LICENSE"
|
|
37
38
|
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
41
|
+
"dev": "tsup src/index.ts --format esm,cjs --dts --watch",
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:watch": "vitest",
|
|
45
|
+
"bench": "node --import tsx/esm bench/benchmark.ts"
|
|
46
|
+
},
|
|
38
47
|
"dependencies": {
|
|
39
48
|
"ioredis": "^5.3.2",
|
|
40
49
|
"msgpackr": "^2.0.1"
|
|
@@ -53,13 +62,5 @@
|
|
|
53
62
|
"repository": {
|
|
54
63
|
"type": "git",
|
|
55
64
|
"url": "git+https://github.com/Kareem411/TriCache.git"
|
|
56
|
-
},
|
|
57
|
-
"scripts": {
|
|
58
|
-
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
59
|
-
"dev": "tsup src/index.ts --format esm,cjs --dts --watch",
|
|
60
|
-
"typecheck": "tsc --noEmit",
|
|
61
|
-
"test": "vitest run",
|
|
62
|
-
"test:watch": "vitest",
|
|
63
|
-
"bench": "node --import tsx/esm bench/benchmark.ts"
|
|
64
65
|
}
|
|
65
|
-
}
|
|
66
|
+
}
|
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;
|
|
@@ -151,6 +163,9 @@ export class CacheService {
|
|
|
151
163
|
tracer: ICacheTracer | undefined;
|
|
152
164
|
notFoundTtl: number;
|
|
153
165
|
warmKeys: string | undefined;
|
|
166
|
+
onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
|
|
167
|
+
onMiss: ((key: string) => void) | undefined;
|
|
168
|
+
frozen: boolean;
|
|
154
169
|
};
|
|
155
170
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
156
171
|
private readonly _namespace: string;
|
|
@@ -172,6 +187,7 @@ export class CacheService {
|
|
|
172
187
|
private snapshotLoaded = false;
|
|
173
188
|
private _readyPromise: Promise<void> = Promise.resolve();
|
|
174
189
|
private cleanupInterval: ReturnType<typeof setInterval> | null = null;
|
|
190
|
+
private diskJanitorInterval: ReturnType<typeof setInterval> | null = null;
|
|
175
191
|
private oomInterval: ReturnType<typeof setInterval> | null = null;
|
|
176
192
|
private metricsInterval: ReturnType<typeof setInterval> | null = null;
|
|
177
193
|
private _shutdownHandler: (() => void) | null = null;
|
|
@@ -258,6 +274,9 @@ export class CacheService {
|
|
|
258
274
|
tracer: options.tracer,
|
|
259
275
|
notFoundTtl: options.notFoundTtl ?? 0,
|
|
260
276
|
warmKeys: options.warmKeys,
|
|
277
|
+
onHit: options.onHit,
|
|
278
|
+
onMiss: options.onMiss,
|
|
279
|
+
frozen: options.frozen ?? false,
|
|
261
280
|
};
|
|
262
281
|
|
|
263
282
|
// Circuit breaker for L2 Redis
|
|
@@ -283,7 +302,13 @@ export class CacheService {
|
|
|
283
302
|
maxBytes: this.opts.l1MaxBytes,
|
|
284
303
|
maxEntries: this.opts.l1MaxEntries,
|
|
285
304
|
categories: this.opts.categoryLimits,
|
|
286
|
-
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
|
+
},
|
|
287
312
|
onEviction: options.onEviction,
|
|
288
313
|
logger,
|
|
289
314
|
});
|
|
@@ -299,16 +324,24 @@ export class CacheService {
|
|
|
299
324
|
process.once('SIGTERM', this._shutdownHandler);
|
|
300
325
|
process.once('SIGINT', this._shutdownHandler);
|
|
301
326
|
|
|
302
|
-
// 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.
|
|
303
330
|
this.cleanupInterval = setInterval(() => {
|
|
304
331
|
const cleaned = this.l1.cleanup();
|
|
305
|
-
|
|
306
|
-
if (cleaned > 0 || diskPurged > 0) {
|
|
307
|
-
this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
|
|
308
|
-
}
|
|
332
|
+
if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
|
|
309
333
|
}, 5 * 60 * 1000);
|
|
310
334
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
|
|
311
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
|
+
|
|
312
345
|
// OOM protection: evict coldest L1 entries when heap pressure rises
|
|
313
346
|
if (this.opts.oomProtection) {
|
|
314
347
|
this.oomInterval = setInterval(() => {
|
|
@@ -413,10 +446,18 @@ export class CacheService {
|
|
|
413
446
|
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
414
447
|
}
|
|
415
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
|
+
|
|
416
457
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
417
458
|
private _startSpan(name: string): ICacheSpan {
|
|
418
459
|
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
419
|
-
return
|
|
460
|
+
return CacheService._nullSpan;
|
|
420
461
|
}
|
|
421
462
|
|
|
422
463
|
private initBackplane(): void {
|
|
@@ -645,10 +686,17 @@ export class CacheService {
|
|
|
645
686
|
refreshAhead?: number; // 0–1: trigger background recompute at this fraction of TTL elapsed
|
|
646
687
|
xfetchBeta?: number; // > 0: XFetch probabilistic early expiration (uses stored delta)
|
|
647
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[];
|
|
648
696
|
} = {},
|
|
649
697
|
): Promise<T> {
|
|
650
698
|
const span = this._startSpan('tricache.get');
|
|
651
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
699
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
652
700
|
const k = this.nk(cacheKey); // namespaced key used for all storage
|
|
653
701
|
this.counters.gets++;
|
|
654
702
|
|
|
@@ -670,22 +718,26 @@ export class CacheService {
|
|
|
670
718
|
this.logger.debug('L1 hit');
|
|
671
719
|
// Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
|
|
672
720
|
// l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
|
|
673
|
-
|
|
674
|
-
|
|
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();
|
|
675
725
|
const remaining = l1Hit.expiresAt - now;
|
|
676
726
|
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
|
|
677
727
|
|
|
678
|
-
const shouldRefreshAhead = opts.refreshAhead
|
|
728
|
+
const shouldRefreshAhead = !!opts.refreshAhead
|
|
679
729
|
? remaining <= entryTtl * (1 - opts.refreshAhead)
|
|
680
730
|
: false;
|
|
681
731
|
|
|
682
732
|
// XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
|
|
683
733
|
// Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
|
|
684
|
-
const shouldXFetch = opts.xfetchBeta
|
|
734
|
+
const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null
|
|
685
735
|
? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
|
|
686
736
|
: false;
|
|
687
737
|
|
|
688
|
-
|
|
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)) {
|
|
689
741
|
// Defer inferPriority until we actually need it — avoids 3× string.includes()
|
|
690
742
|
// scans on every warm hit when the threshold check is false (the common case).
|
|
691
743
|
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
@@ -700,6 +752,8 @@ export class CacheService {
|
|
|
700
752
|
}
|
|
701
753
|
}
|
|
702
754
|
this.counters.l1Hits++;
|
|
755
|
+
this.opts.onHit?.(cacheKey, 'l1');
|
|
756
|
+
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
703
757
|
span.setAttribute('cache.hit', 'l1').end();
|
|
704
758
|
return l1Hit.value as T;
|
|
705
759
|
}
|
|
@@ -719,6 +773,7 @@ export class CacheService {
|
|
|
719
773
|
const parsed = JSON.parse(decrypted) as T;
|
|
720
774
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
721
775
|
this.counters.l2Hits++;
|
|
776
|
+
this.opts.onHit?.(cacheKey, 'l2');
|
|
722
777
|
this.logger.debug('L2 hit (Redis)', { cacheKey });
|
|
723
778
|
span.setAttribute('cache.hit', 'l2').end();
|
|
724
779
|
return parsed;
|
|
@@ -740,6 +795,7 @@ export class CacheService {
|
|
|
740
795
|
const l1Check = this.l1.get(k);
|
|
741
796
|
if (l1Check !== null) {
|
|
742
797
|
this.counters.diskHits++;
|
|
798
|
+
this.opts.onHit?.(cacheKey, 'disk');
|
|
743
799
|
this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
|
|
744
800
|
span.setAttribute('cache.hit', 'disk').end();
|
|
745
801
|
return l1Check.value as T;
|
|
@@ -748,6 +804,7 @@ export class CacheService {
|
|
|
748
804
|
}
|
|
749
805
|
|
|
750
806
|
span.setAttribute('cache.hit', 'miss');
|
|
807
|
+
this.opts.onMiss?.(cacheKey);
|
|
751
808
|
|
|
752
809
|
// Cache MISS: thundering-herd prevention
|
|
753
810
|
const existing = this.inflight.get(k);
|
|
@@ -773,6 +830,7 @@ export class CacheService {
|
|
|
773
830
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
774
831
|
|
|
775
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));
|
|
776
834
|
|
|
777
835
|
if (!this._redisDisabled) {
|
|
778
836
|
try {
|
|
@@ -844,35 +902,14 @@ export class CacheService {
|
|
|
844
902
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
845
903
|
async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
|
|
846
904
|
const span = this._startSpan('tricache.set');
|
|
847
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
905
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
848
906
|
const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
|
|
849
907
|
const p = priority ?? inferPriority(cacheKey);
|
|
850
908
|
const k = this.nk(cacheKey);
|
|
851
909
|
this.counters.sets++;
|
|
852
910
|
this.l1.set(k, data, ttlMs, p);
|
|
853
911
|
|
|
854
|
-
|
|
855
|
-
if (opts?.tags?.length) {
|
|
856
|
-
for (const tag of opts.tags) {
|
|
857
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
858
|
-
let members = this.tagIndex.get(tagKey);
|
|
859
|
-
if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
|
|
860
|
-
members.add(k);
|
|
861
|
-
}
|
|
862
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
|
|
863
|
-
try {
|
|
864
|
-
const client = await this.getRedis();
|
|
865
|
-
const pl = client.pipeline();
|
|
866
|
-
for (const tag of opts.tags) {
|
|
867
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
868
|
-
pl.sadd(tagKey, k);
|
|
869
|
-
pl.expire(tagKey, ttlSeconds + 3_600);
|
|
870
|
-
}
|
|
871
|
-
await pl.exec();
|
|
872
|
-
this.cb.onSuccess();
|
|
873
|
-
} catch { this.cb.onFailure(); /* tags are best-effort */ }
|
|
874
|
-
}
|
|
875
|
-
}
|
|
912
|
+
if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
|
|
876
913
|
|
|
877
914
|
// Register dependency patterns: when any key matching a pattern is deleted,
|
|
878
915
|
// this key (k) is automatically cascaded.
|
|
@@ -902,6 +939,32 @@ export class CacheService {
|
|
|
902
939
|
span.end();
|
|
903
940
|
}
|
|
904
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
|
+
|
|
905
968
|
/**
|
|
906
969
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
907
970
|
*
|
|
@@ -911,7 +974,7 @@ export class CacheService {
|
|
|
911
974
|
*/
|
|
912
975
|
async delete(cacheKey: string): Promise<void> {
|
|
913
976
|
const span = this._startSpan('tricache.delete');
|
|
914
|
-
span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
977
|
+
if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
|
|
915
978
|
const isPattern = cacheKey.includes('*');
|
|
916
979
|
const k = this.nk(cacheKey);
|
|
917
980
|
this.counters.deletes++;
|
|
@@ -920,7 +983,13 @@ export class CacheService {
|
|
|
920
983
|
this.l1.deletePattern(k);
|
|
921
984
|
} else {
|
|
922
985
|
this.l1.delete(k);
|
|
923
|
-
|
|
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));
|
|
924
993
|
// Cascade: invalidate any key that declared it depends on this exact key's pattern
|
|
925
994
|
this._cascadeDependencies(k);
|
|
926
995
|
// Clean up: remove k from all dependency registrations (it is gone)
|
|
@@ -1100,6 +1169,34 @@ export class CacheService {
|
|
|
1100
1169
|
}
|
|
1101
1170
|
}
|
|
1102
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
|
+
|
|
1103
1200
|
/**
|
|
1104
1201
|
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
1105
1202
|
* Returns `false` if the key is absent or already expired.
|
|
@@ -1240,7 +1337,7 @@ export class CacheService {
|
|
|
1240
1337
|
* const loaded = await cache.warmFromL2('org:*');
|
|
1241
1338
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
1242
1339
|
*/
|
|
1243
|
-
async warmFromL2(pattern: string): Promise<number> {
|
|
1340
|
+
async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
|
|
1244
1341
|
if (this._redisDisabled) return 0;
|
|
1245
1342
|
try {
|
|
1246
1343
|
const client = await this.getRedis();
|
|
@@ -1277,8 +1374,8 @@ export class CacheService {
|
|
|
1277
1374
|
// Use a 10-minute TTL as a reasonable default; the real TTL is not
|
|
1278
1375
|
// returned by GET (use PTTL to be precise, but that doubles round-trips).
|
|
1279
1376
|
const remainingMs = 10 * 60 * 1_000;
|
|
1280
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
1281
|
-
loaded
|
|
1377
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
|
|
1378
|
+
loaded++;;
|
|
1282
1379
|
} catch { /* skip malformed entries */ }
|
|
1283
1380
|
}
|
|
1284
1381
|
void now; // suppress unused warning
|
|
@@ -1329,6 +1426,61 @@ export class CacheService {
|
|
|
1329
1426
|
}
|
|
1330
1427
|
}
|
|
1331
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
|
+
|
|
1332
1484
|
/**
|
|
1333
1485
|
* Measure L1 / disk / Redis latency.
|
|
1334
1486
|
* Useful for health checks and dashboards.
|
|
@@ -1633,9 +1785,10 @@ export class CacheService {
|
|
|
1633
1785
|
|
|
1634
1786
|
/** Close Redis connections and stop all background timers. */
|
|
1635
1787
|
async destroy(): Promise<void> {
|
|
1636
|
-
if (this.cleanupInterval)
|
|
1637
|
-
if (this.
|
|
1638
|
-
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);
|
|
1639
1792
|
if (this._shutdownHandler) {
|
|
1640
1793
|
process.off('SIGTERM', this._shutdownHandler);
|
|
1641
1794
|
process.off('SIGINT', this._shutdownHandler);
|