tricache 0.5.0 → 0.6.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.
@@ -19,6 +19,7 @@ import { Redis as RedisClient } from 'ioredis';
19
19
  import { pack, unpack } from 'msgpackr';
20
20
  import crypto from 'crypto';
21
21
  import os from 'os';
22
+ import v8 from 'node:v8';
22
23
  import fs from 'fs';
23
24
  import path from 'path';
24
25
  import { CachePriority, consoleLogger, } from './types';
@@ -82,6 +83,106 @@ class L2CircuitBreaker {
82
83
  // ─────────────────────────────────────────────────────────────────────────────
83
84
  // Priority inference — override by passing priority explicitly to get()
84
85
  // ─────────────────────────────────────────────────────────────────────────────
86
+ /**
87
+ * Recursively freezes an object and all its nested properties.
88
+ * Used only when `CacheOptions.frozen` is true (dev/test mode).
89
+ * Already-frozen objects are skipped to avoid redundant traversal.
90
+ */
91
+ function deepFreeze(obj) {
92
+ if (obj === null || typeof obj !== 'object' || Object.isFrozen(obj))
93
+ return obj;
94
+ Object.freeze(obj);
95
+ for (const v of Object.values(obj))
96
+ deepFreeze(v);
97
+ return obj;
98
+ }
99
+ class LatencyTracker {
100
+ samples;
101
+ maxKeys;
102
+ bufs = new Map();
103
+ meta = new Map();
104
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
105
+ scratch;
106
+ constructor(samples, maxKeys) {
107
+ this.samples = samples;
108
+ this.maxKeys = maxKeys;
109
+ this.scratch = new Float64Array(samples);
110
+ }
111
+ record(key, deltaMs) {
112
+ let buf = this.bufs.get(key);
113
+ let m = this.meta.get(key);
114
+ if (buf === undefined) {
115
+ if (this.bufs.size >= this.maxKeys) {
116
+ // Evict oldest key (Map insertion order)
117
+ const oldest = this.bufs.keys().next().value;
118
+ this.bufs.delete(oldest);
119
+ this.meta.delete(oldest);
120
+ }
121
+ buf = new Float64Array(this.samples);
122
+ m = { head: 0, count: 0, p95: 0, dirty: false };
123
+ this.bufs.set(key, buf);
124
+ this.meta.set(key, m);
125
+ }
126
+ buf[m.head] = deltaMs;
127
+ m.head = (m.head + 1) % this.samples;
128
+ if (m.count < this.samples)
129
+ m.count++;
130
+ m.dirty = true; // new sample → cached p95 is stale
131
+ }
132
+ /**
133
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
134
+ * Uses the shared scratch buffer — no heap allocation.
135
+ */
136
+ _computeP95(buf, m) {
137
+ const n = m.count;
138
+ this.scratch.set(buf.subarray(0, n));
139
+ const view = this.scratch.subarray(0, n);
140
+ view.sort(); // TypedArray numeric sort — no comparator needed
141
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
142
+ m.dirty = false;
143
+ }
144
+ /**
145
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
146
+ * fewer than 5 samples have been collected (not enough data yet).
147
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
148
+ */
149
+ p95(key) {
150
+ const buf = this.bufs.get(key);
151
+ const m = this.meta.get(key);
152
+ if (!buf || !m || m.count < 5)
153
+ return null;
154
+ if (m.dirty)
155
+ this._computeP95(buf, m);
156
+ return m.p95;
157
+ }
158
+ get trackedKeys() { return this.bufs.size; }
159
+ /**
160
+ * Top-20 slowest keys by p95, sorted descending.
161
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
162
+ *
163
+ * Only dirty keys (those with new samples since the last call) pay the sort
164
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
165
+ * metrics() calls with no intervening fetches are essentially free.
166
+ */
167
+ snapshot(prefixLen, multiplierSec, minMs, maxMs) {
168
+ const out = [];
169
+ for (const [key, buf] of this.bufs) {
170
+ const m = this.meta.get(key);
171
+ if (m.count < 5)
172
+ continue;
173
+ if (m.dirty)
174
+ this._computeP95(buf, m); // sort only when new sample arrived
175
+ const p95 = m.p95;
176
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1_000)));
177
+ out.push({
178
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
179
+ p95Ms: Math.round(p95),
180
+ adaptedTtlSec: Math.round(adaptedMs / 1_000),
181
+ });
182
+ }
183
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
184
+ }
185
+ }
85
186
  function inferPriority(cacheKey) {
86
187
  if (cacheKey.includes('auth:') || cacheKey.includes('session:'))
87
188
  return CachePriority.CRITICAL;
@@ -122,9 +223,11 @@ export class CacheService {
122
223
  snapshotLoaded = false;
123
224
  _readyPromise = Promise.resolve();
124
225
  cleanupInterval = null;
226
+ diskJanitorInterval = null;
125
227
  oomInterval = null;
126
228
  metricsInterval = null;
127
229
  _shutdownHandler = null;
230
+ latencyTracker = null;
128
231
  instanceId;
129
232
  backplaneChannel;
130
233
  subClient = null;
@@ -190,15 +293,29 @@ export class CacheService {
190
293
  staleIfError: options.staleIfError ?? 0,
191
294
  l2WriteMode: options.l2WriteMode ?? 'read-write',
192
295
  instanceName: options.instanceName ?? '',
296
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
193
297
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
194
298
  tracer: options.tracer,
195
299
  notFoundTtl: options.notFoundTtl ?? 0,
196
300
  warmKeys: options.warmKeys,
301
+ onHit: options.onHit,
302
+ onMiss: options.onMiss,
303
+ frozen: options.frozen ?? false,
304
+ adaptiveTtl: options.adaptiveTtl ?? false,
305
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1_000,
306
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86_400) * 1_000,
307
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
197
308
  };
198
309
  // Circuit breaker for L2 Redis
199
310
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
200
311
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
201
312
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
313
+ // Adaptive TTL latency tracker (only allocated when the feature is enabled)
314
+ if (this.opts.adaptiveTtl) {
315
+ const samples = options.adaptiveTtlSamples ?? 32;
316
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5_000;
317
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
318
+ }
202
319
  // L1.5 disk tier
203
320
  this.disk = new DiskTier({
204
321
  dir: this.opts.diskCacheDir,
@@ -215,7 +332,14 @@ export class CacheService {
215
332
  maxBytes: this.opts.l1MaxBytes,
216
333
  maxEntries: this.opts.l1MaxEntries,
217
334
  categories: this.opts.categoryLimits,
218
- diskSpill: (key, entry) => { void this.disk.save(key, entry); },
335
+ evictionWatermark: this.opts.l1EvictionWatermark,
336
+ diskSpill: (key, entry) => {
337
+ // Defer disk.save() entirely to the next event-loop tick so the synchronous
338
+ // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
339
+ // the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
340
+ // backplane handler already does for remote invalidations.
341
+ setImmediate(() => { void this.disk.save(key, entry); });
342
+ },
219
343
  onEviction: options.onEviction,
220
344
  logger,
221
345
  });
@@ -228,21 +352,31 @@ export class CacheService {
228
352
  this._shutdownHandler = () => { this.writeSnapshot(); process.exit(0); };
229
353
  process.once('SIGTERM', this._shutdownHandler);
230
354
  process.once('SIGINT', this._shutdownHandler);
231
- // Periodic cleanup (5 min)
355
+ // Periodic L1 cleanup (5 min): expires stale entries and rebalances frequency counters.
356
+ // Disk cleanup is handled entirely by the janitor below — purgeExpired() is NOT called
357
+ // here to avoid a synchronous O(fileCount) event-loop stall at scale.
232
358
  this.cleanupInterval = setInterval(() => {
233
359
  const cleaned = this.l1.cleanup();
234
- const diskPurged = this.disk.purgeExpired();
235
- if (cleaned > 0 || diskPurged > 0) {
236
- this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
237
- }
360
+ if (cleaned > 0)
361
+ this.logger.debug('Periodic L1 cleanup', { cleaned });
238
362
  }, 5 * 60 * 1000);
239
363
  if (this.cleanupInterval.unref)
240
364
  this.cleanupInterval.unref(); // don't block process exit
365
+ // Disk janitor: sole owner of disk expiry. Scans one of 256 subdirectory buckets per tick
366
+ // (30 s × 256 = 128-min full cycle). Each tick is bounded to one bucket's worth of
367
+ // readFileSync + decrypt + unpack work, capping per-tick event-loop occupancy.
368
+ this.diskJanitorInterval = setInterval(() => {
369
+ const purged = this.disk.purgeNextBucket();
370
+ if (purged > 0)
371
+ this.logger.debug('Disk janitor tick', { purged });
372
+ }, 30_000);
373
+ if (this.diskJanitorInterval.unref)
374
+ this.diskJanitorInterval.unref();
241
375
  // OOM protection: evict coldest L1 entries when heap pressure rises
242
376
  if (this.opts.oomProtection) {
243
377
  this.oomInterval = setInterval(() => {
244
- const mem = process.memoryUsage();
245
- const used = mem.heapUsed / mem.heapTotal;
378
+ const heap = v8.getHeapStatistics();
379
+ const used = heap.used_heap_size / heap.heap_size_limit;
246
380
  if (used >= this.opts.oomHeapThreshold) {
247
381
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
248
382
  this.counters.oomEvictions++;
@@ -338,11 +472,18 @@ export class CacheService {
338
472
  return ttlMs;
339
473
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
340
474
  }
475
+ /** Shared no-op span for the common case where no tracer is configured.
476
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
477
+ static _nullSpan = {
478
+ setAttribute() { return this; },
479
+ setStatus() { return this; },
480
+ end() { },
481
+ };
341
482
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
342
483
  _startSpan(name) {
343
484
  if (this.opts.tracer)
344
485
  return this.opts.tracer.startSpan(name);
345
- return { setAttribute() { return this; }, setStatus() { return this; }, end() { } };
486
+ return CacheService._nullSpan;
346
487
  }
347
488
  initBackplane() {
348
489
  if (!this.opts.invalidationBackplane || this._redisDisabled)
@@ -546,16 +687,28 @@ export class CacheService {
546
687
  */
547
688
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
548
689
  const span = this._startSpan('tricache.get');
549
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
690
+ if (this.opts.tracer)
691
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
550
692
  const k = this.nk(cacheKey); // namespaced key used for all storage
551
693
  this.counters.gets++;
694
+ // Normalize all opts fields to plain locals once. Every opts.XXX read
695
+ // elsewhere in this function would hit a polymorphic IC when callers pass
696
+ // different option shapes: {}, { swr }, { refreshAhead }, { tags }, etc.
697
+ // Reading everything here collapses all downstream accesses to fast
698
+ // monomorphic local-variable reads regardless of call-site variety.
699
+ const optSwr = opts.swr ?? 0;
700
+ const optPriority = opts.priority;
701
+ const optRefreshAhead = opts.refreshAhead;
702
+ const optXfetchBeta = opts.xfetchBeta;
703
+ const optNotFoundTtl = opts.notFoundTtl;
704
+ const optTags = opts.tags;
552
705
  // L1: in-memory (fastest path)
553
706
  const l1Hit = this.l1.get(k);
554
707
  if (l1Hit !== null) {
555
708
  if (l1Hit.isStale) {
556
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
709
+ const swrGraceMs = optSwr * 1_000;
557
710
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
558
- const priority = opts.priority ?? inferPriority(cacheKey);
711
+ const priority = optPriority ?? inferPriority(cacheKey);
559
712
  this.revalidating.add(k);
560
713
  void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
561
714
  this.counters.swrRevalidations++;
@@ -569,36 +722,44 @@ export class CacheService {
569
722
  this.logger.debug('L1 hit');
570
723
  // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
571
724
  // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
572
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
573
- const now = Date.now();
725
+ // Check opts first — pointless work when neither feature is configured.
726
+ // Local aliases for the opts fields already normalised at function entry.
727
+ const ra = optRefreshAhead;
728
+ const xb = optXfetchBeta;
729
+ if (ra || xb) {
730
+ // Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
731
+ const now = l1Hit.fetchedAt ?? Date.now();
574
732
  const remaining = l1Hit.expiresAt - now;
575
733
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
576
- const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
577
- ? remaining <= entryTtl * (1 - opts.refreshAhead)
578
- : false;
734
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
579
735
  // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
580
736
  // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
581
- const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null
582
- ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
737
+ const shouldXFetch = xb && l1Hit.delta != null
738
+ ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
583
739
  : false;
584
- if (shouldRefreshAhead || shouldXFetch) {
740
+ // Set.has() deferred to here — the common case (fresh key, threshold not crossed)
741
+ // never pays the ~30 ns lookup cost.
742
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
585
743
  // Defer inferPriority until we actually need it — avoids 3× string.includes()
586
744
  // scans on every warm hit when the threshold check is false (the common case).
587
- const priority = opts.priority ?? inferPriority(cacheKey);
745
+ const priority = optPriority ?? inferPriority(cacheKey);
588
746
  this.revalidating.add(k);
589
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
747
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
590
748
  this.counters.swrRevalidations++;
591
749
  this.logger.debug(shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute', { cacheKey, remainingMs: remaining, ttlMs: entryTtl });
592
750
  }
593
751
  }
594
752
  }
595
753
  this.counters.l1Hits++;
754
+ this.opts.onHit?.(cacheKey, 'l1');
755
+ if (this.opts.frozen)
756
+ deepFreeze(l1Hit.value);
596
757
  span.setAttribute('cache.hit', 'l1').end();
597
758
  return l1Hit.value;
598
759
  }
599
760
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
600
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
601
- const priority = opts.priority ?? inferPriority(cacheKey);
761
+ const swrGraceMs = optSwr * 1_000;
762
+ const priority = optPriority ?? inferPriority(cacheKey);
602
763
  // L2: Redis (distributed, production-only by default)
603
764
  if (!this._redisDisabled) {
604
765
  try {
@@ -610,6 +771,7 @@ export class CacheService {
610
771
  const parsed = JSON.parse(decrypted);
611
772
  this.l1.set(k, parsed, ttlMs, priority);
612
773
  this.counters.l2Hits++;
774
+ this.opts.onHit?.(cacheKey, 'l2');
613
775
  this.logger.debug('L2 hit (Redis)', { cacheKey });
614
776
  span.setAttribute('cache.hit', 'l2').end();
615
777
  return parsed;
@@ -628,6 +790,7 @@ export class CacheService {
628
790
  const l1Check = this.l1.get(k);
629
791
  if (l1Check !== null) {
630
792
  this.counters.diskHits++;
793
+ this.opts.onHit?.(cacheKey, 'disk');
631
794
  this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
632
795
  span.setAttribute('cache.hit', 'disk').end();
633
796
  return l1Check.value;
@@ -635,6 +798,7 @@ export class CacheService {
635
798
  }
636
799
  }
637
800
  span.setAttribute('cache.hit', 'miss');
801
+ this.opts.onMiss?.(cacheKey);
638
802
  // Cache MISS: thundering-herd prevention
639
803
  const existing = this.inflight.get(k);
640
804
  if (existing) {
@@ -650,11 +814,24 @@ export class CacheService {
650
814
  const data = await fetchFn();
651
815
  const delta = Date.now() - fetchStart;
652
816
  // Negative caching: null/undefined results get their own (shorter) TTL
653
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
654
- const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
817
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
818
+ let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
819
+ // Adaptive TTL: record this fetch duration and override the caller-supplied
820
+ // TTL once ≥ 5 samples are available for the key.
821
+ // Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
822
+ if (this.latencyTracker && data != null) {
823
+ this.latencyTracker.record(k, delta);
824
+ const p95 = this.latencyTracker.p95(k);
825
+ if (p95 !== null) {
826
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1_000);
827
+ effectiveTtl = Math.max(this.opts.adaptiveTtlMinMs, Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs));
828
+ }
829
+ }
655
830
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
656
831
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
657
832
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
833
+ if (optTags?.length)
834
+ await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
658
835
  if (!this._redisDisabled) {
659
836
  try {
660
837
  const client = await this.getRedis();
@@ -688,6 +865,9 @@ export class CacheService {
688
865
  const data = await fetchFn();
689
866
  const delta = Date.now() - fetchStart;
690
867
  const staleAt = Date.now() + ttlMs;
868
+ // Keep the latency tracker current during SWR background revalidations too
869
+ if (this.latencyTracker && data != null)
870
+ this.latencyTracker.record(cacheKey, delta);
691
871
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
692
872
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
693
873
  try {
@@ -720,40 +900,15 @@ export class CacheService {
720
900
  /** Explicitly write a value into L1 (+ L2 in production). */
721
901
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
722
902
  const span = this._startSpan('tricache.set');
723
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
903
+ if (this.opts.tracer)
904
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
724
905
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
725
906
  const p = priority ?? inferPriority(cacheKey);
726
907
  const k = this.nk(cacheKey);
727
908
  this.counters.sets++;
728
909
  this.l1.set(k, data, ttlMs, p);
729
- // Register tags in the in-process index (+ Redis SADD)
730
- if (opts?.tags?.length) {
731
- for (const tag of opts.tags) {
732
- const tagKey = this.nk(`_tag_:${tag}`);
733
- let members = this.tagIndex.get(tagKey);
734
- if (!members) {
735
- members = new Set();
736
- this.tagIndex.set(tagKey, members);
737
- }
738
- members.add(k);
739
- }
740
- if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
741
- try {
742
- const client = await this.getRedis();
743
- const pl = client.pipeline();
744
- for (const tag of opts.tags) {
745
- const tagKey = this.nk(`_tag_:${tag}`);
746
- pl.sadd(tagKey, k);
747
- pl.expire(tagKey, ttlSeconds + 3_600);
748
- }
749
- await pl.exec();
750
- this.cb.onSuccess();
751
- }
752
- catch {
753
- this.cb.onFailure(); /* tags are best-effort */
754
- }
755
- }
756
- }
910
+ if (opts?.tags?.length)
911
+ await this._registerTags(k, opts.tags, ttlSeconds);
757
912
  // Register dependency patterns: when any key matching a pattern is deleted,
758
913
  // this key (k) is automatically cascaded.
759
914
  if (opts?.dependsOn?.length) {
@@ -783,6 +938,37 @@ export class CacheService {
783
938
  void this.publishInvalidation('del', k);
784
939
  span.end();
785
940
  }
941
+ /**
942
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
943
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
944
+ */
945
+ async _registerTags(k, tags, ttlSeconds) {
946
+ for (const tag of tags) {
947
+ const tagKey = this.nk(`_tag_:${tag}`);
948
+ let members = this.tagIndex.get(tagKey);
949
+ if (!members) {
950
+ members = new Set();
951
+ this.tagIndex.set(tagKey, members);
952
+ }
953
+ members.add(k);
954
+ }
955
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
956
+ try {
957
+ const client = await this.getRedis();
958
+ const pl = client.pipeline();
959
+ for (const tag of tags) {
960
+ const tagKey = this.nk(`_tag_:${tag}`);
961
+ pl.sadd(tagKey, k);
962
+ pl.expire(tagKey, ttlSeconds + 3_600);
963
+ }
964
+ await pl.exec();
965
+ this.cb.onSuccess();
966
+ }
967
+ catch {
968
+ this.cb.onFailure(); /* tags are best-effort */
969
+ }
970
+ }
971
+ }
786
972
  /**
787
973
  * Delete one key or a glob pattern (supports `*` wildcard).
788
974
  *
@@ -792,7 +978,8 @@ export class CacheService {
792
978
  */
793
979
  async delete(cacheKey) {
794
980
  const span = this._startSpan('tricache.delete');
795
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
981
+ if (this.opts.tracer)
982
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
796
983
  const isPattern = cacheKey.includes('*');
797
984
  const k = this.nk(cacheKey);
798
985
  this.counters.deletes++;
@@ -801,7 +988,13 @@ export class CacheService {
801
988
  }
802
989
  else {
803
990
  this.l1.delete(k);
804
- this.disk.delete(k);
991
+ // Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
992
+ // the caller's await resolves without blocking. Matches what the backplane handler
993
+ // already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
994
+ // A re-get in the narrow window before the deferred call fires would get an L1 miss
995
+ // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
996
+ // path already accepts).
997
+ setImmediate(() => this.disk.delete(k));
805
998
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
806
999
  this._cascadeDependencies(k);
807
1000
  // Clean up: remove k from all dependency registrations (it is gone)
@@ -970,6 +1163,33 @@ export class CacheService {
970
1163
  yield [k, (entry.value !== undefined ? entry.value : entry.data)];
971
1164
  }
972
1165
  }
1166
+ /**
1167
+ * High-throughput bulk scan over all live L1 entries.
1168
+ *
1169
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
1170
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
1171
+ * caller uses the `offset` parameter instead of pre-slicing.
1172
+ *
1173
+ * ```typescript
1174
+ * // Zero extra string allocations — use rawKey + offset directly:
1175
+ * cache.scan((rawKey, value, offset) => {
1176
+ * const key = rawKey.slice(offset); // allocate only if needed
1177
+ * sync(key, value as User);
1178
+ * });
1179
+ * ```
1180
+ *
1181
+ * @param fn Called once per live L1 entry.
1182
+ * `rawKey` — key with namespace prefix still attached.
1183
+ * `value` — deserialized cached value.
1184
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
1185
+ */
1186
+ scan(fn) {
1187
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1188
+ this.l1.scan((key, entry, pfx) => {
1189
+ const value = (entry.value !== undefined ? entry.value : entry.data);
1190
+ fn(key, value, pfx);
1191
+ }, prefixLen);
1192
+ }
973
1193
  /**
974
1194
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
975
1195
  * Returns `false` if the key is absent or already expired.
@@ -1099,7 +1319,7 @@ export class CacheService {
1099
1319
  * const loaded = await cache.warmFromL2('org:*');
1100
1320
  * console.log(`Warmed ${loaded} keys from Redis`);
1101
1321
  */
1102
- async warmFromL2(pattern) {
1322
+ async warmFromL2(pattern, opts) {
1103
1323
  if (this._redisDisabled)
1104
1324
  return 0;
1105
1325
  try {
@@ -1135,8 +1355,9 @@ export class CacheService {
1135
1355
  // Use a 10-minute TTL as a reasonable default; the real TTL is not
1136
1356
  // returned by GET (use PTTL to be precise, but that doubles round-trips).
1137
1357
  const remainingMs = 10 * 60 * 1_000;
1138
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
1358
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
1139
1359
  loaded++;
1360
+ ;
1140
1361
  }
1141
1362
  catch { /* skip malformed entries */ }
1142
1363
  }
@@ -1186,6 +1407,68 @@ export class CacheService {
1186
1407
  }
1187
1408
  }
1188
1409
  }
1410
+ /**
1411
+ * Invalidate all keys associated with any of the given tags in a single operation.
1412
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
1413
+ * reducing latency when invalidating several related tags together.
1414
+ *
1415
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
1416
+ * synchronously before the Redis round-trip.
1417
+ *
1418
+ * @example
1419
+ * // Instead of three serial round-trips:
1420
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
1421
+ */
1422
+ async invalidateTags(tags) {
1423
+ if (tags.length === 0)
1424
+ return;
1425
+ if (tags.length === 1) {
1426
+ await this.invalidateTag(tags[0]);
1427
+ return;
1428
+ }
1429
+ // In-process: collect all member keys across all tags and remove from L1 + disk
1430
+ const tagKeys = [];
1431
+ const allMembers = new Set();
1432
+ for (const tag of tags) {
1433
+ const tagKey = this.nk(`_tag_:${tag}`);
1434
+ tagKeys.push(tagKey);
1435
+ const members = this.tagIndex.get(tagKey) ?? new Set();
1436
+ for (const k of members)
1437
+ allMembers.add(k);
1438
+ this.tagIndex.delete(tagKey);
1439
+ }
1440
+ for (const k of allMembers) {
1441
+ this.l1.delete(k);
1442
+ this.disk.delete(k);
1443
+ }
1444
+ if (!this._redisDisabled) {
1445
+ try {
1446
+ const client = await this.getRedis();
1447
+ // Single round-trip: pipeline SMEMBERS for all tag keys
1448
+ const pl = client.pipeline();
1449
+ for (const tagKey of tagKeys)
1450
+ pl.smembers(tagKey);
1451
+ const smResults = await pl.exec();
1452
+ // Merge Redis members into the master delete set
1453
+ const toDelete = [...allMembers];
1454
+ for (const [err, redisMembers] of smResults) {
1455
+ if (!err && redisMembers) {
1456
+ for (const k of redisMembers) {
1457
+ if (!allMembers.has(k))
1458
+ toDelete.push(k);
1459
+ }
1460
+ }
1461
+ }
1462
+ // Single DEL for all member keys + tag keys
1463
+ const keysToRemove = [...toDelete, ...tagKeys];
1464
+ if (keysToRemove.length > 0)
1465
+ await client.del(...keysToRemove);
1466
+ }
1467
+ catch (err) {
1468
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: err.message });
1469
+ }
1470
+ }
1471
+ }
1189
1472
  /**
1190
1473
  * Measure L1 / disk / Redis latency.
1191
1474
  * Useful for health checks and dashboards.
@@ -1407,6 +1690,14 @@ export class CacheService {
1407
1690
  maxBytes: this.opts.l1MaxBytes,
1408
1691
  },
1409
1692
  disk: this.disk.stats,
1693
+ ...(this.latencyTracker && {
1694
+ adaptiveTtl: {
1695
+ enabled: true,
1696
+ trackedKeys: this.latencyTracker.trackedKeys,
1697
+ slowestKeys: this.latencyTracker.snapshot(this._namespace ? this._namespace.length + 1 : 0, // strip "namespace:" prefix
1698
+ this.opts.adaptiveTtlMultiplier, this.opts.adaptiveTtlMinMs, this.opts.adaptiveTtlMaxMs),
1699
+ },
1700
+ }),
1410
1701
  };
1411
1702
  }
1412
1703
  /**
@@ -1466,6 +1757,8 @@ export class CacheService {
1466
1757
  async destroy() {
1467
1758
  if (this.cleanupInterval)
1468
1759
  clearInterval(this.cleanupInterval);
1760
+ if (this.diskJanitorInterval)
1761
+ clearInterval(this.diskJanitorInterval);
1469
1762
  if (this.oomInterval)
1470
1763
  clearInterval(this.oomInterval);
1471
1764
  if (this.metricsInterval)
@@ -1489,6 +1782,7 @@ export class CacheService {
1489
1782
  catch { /* ok */ }
1490
1783
  this.redis = null;
1491
1784
  }
1785
+ this.disk.close();
1492
1786
  }
1493
1787
  }
1494
1788
  //# sourceMappingURL=cache-service.js.map