tricache 0.6.6 → 0.7.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.
Files changed (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +500 -24
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1181 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3697
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +64 -15
  33. package/src/cache-service.ts +1005 -192
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +244 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
@@ -38,10 +38,31 @@ import {
38
38
  ICacheTracer,
39
39
  ICacheSpan,
40
40
  consoleLogger,
41
+ WrapOptions,
42
+ LockOptions,
43
+ ICacheMeter,
44
+ ICacheCounter,
41
45
  } from './types';
42
- import { CacheEncryption } from './encryption';
46
+ import { CacheEncryption, type EncryptionMode } from './encryption';
43
47
  import { SmartMemoryCache } from './smart-memory-cache';
44
48
  import { DiskTier } from './disk-tier';
49
+ import {
50
+ compressBuffer,
51
+ decompressBuffer,
52
+ PREFIX_COMPRESSED,
53
+ PREFIX_ENC_COMPRESSED,
54
+ type CompressionAlgorithm,
55
+ } from './compression';
56
+
57
+ // ─── Lua scripts ─────────────────────────────────────────────────────────────
58
+
59
+ const LUA_COMPARE_AND_DELETE = `
60
+ local currentTs = redis.call('HGET', KEYS[1], 't')
61
+ if currentTs and currentTs == ARGV[1] then
62
+ return redis.call('DEL', KEYS[1])
63
+ end
64
+ return 0
65
+ `;
45
66
 
46
67
  // ─── Snapshot constants ───────────────────────────────────────────────────────
47
68
 
@@ -59,6 +80,36 @@ const DEFAULT_CATEGORY_LIMITS: Record<string, CategoryLimit> = {
59
80
 
60
81
  const DEFAULT_FORBIDDEN_PREFIXES = ['auth:', 'session:', 'mfa:', 'rate_limit:'] as const;
61
82
 
83
+ // ─── Default counter TTL ──────────────────────────────────────────────────────
84
+ const DEFAULT_COUNTER_TTL_SECONDS = 60;
85
+
86
+ // ─── Glob regex cache (bounded LRU, max 256 compiled patterns) ───────────────
87
+ const GLOB_REGEX_CACHE_MAX = 256;
88
+ const globRegexCache = new Map<string, RegExp>();
89
+
90
+ function getGlobRegex(pattern: string): RegExp {
91
+ let re = globRegexCache.get(pattern);
92
+ if (re) {
93
+ globRegexCache.delete(pattern);
94
+ globRegexCache.set(pattern, re);
95
+ return re;
96
+ }
97
+
98
+ // Escape special regex characters except '*', then collapse multiple consecutive '*' into '.*'
99
+ const escaped = pattern
100
+ .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
101
+ .replace(/\*+/g, '.*');
102
+
103
+ re = new RegExp('^' + escaped + '$');
104
+
105
+ if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
106
+ const oldestKey = globRegexCache.keys().next().value;
107
+ if (oldestKey !== undefined) globRegexCache.delete(oldestKey);
108
+ }
109
+ globRegexCache.set(pattern, re);
110
+ return re;
111
+ }
112
+
62
113
  // ─────────────────────────────────────────────────────────────────────────────
63
114
  // Circuit breaker — three-state (CLOSED → OPEN → HALF_OPEN) for L2 Redis
64
115
  // ─────────────────────────────────────────────────────────────────────────────
@@ -322,6 +373,7 @@ export class CacheService {
322
373
  l1EvictionWatermark: number;
323
374
  ttlJitterFactor: number;
324
375
  tracer: ICacheTracer | undefined;
376
+ meter: ICacheMeter | undefined;
325
377
  notFoundTtl: number;
326
378
  warmKeys: string | undefined;
327
379
  onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
@@ -338,8 +390,19 @@ export class CacheService {
338
390
  disableDisk: boolean;
339
391
  redisClusterNodes: Array<{ host: string; port: number }> | undefined;
340
392
  redisSentinel: { name: string; sentinels: Array<{ host: string; port: number }> } | undefined;
393
+ redisProtocol: 2 | 3 | undefined;
394
+ useShardedPubSub: boolean;
395
+ compression: CompressionAlgorithm;
396
+ compressionThresholdBytes: number;
341
397
  strictSingleton: boolean;
342
398
  failClosed: boolean;
399
+ tagStrategy: 'set' | 'generational';
400
+ tagVersionTtlMs: number;
401
+ cloneStrategy: 'none' | 'structuredClone';
402
+ backplaneMode: 'pubsub' | 'stream';
403
+ backplaneStreamMaxLen: number;
404
+ backplaneStreamBlockMs: number;
405
+ backplaneStreamKey?: string;
343
406
  };
344
407
  /** Pre-computed once — opts.namespace never changes after construction. */
345
408
  private readonly _namespace: string;
@@ -350,6 +413,8 @@ export class CacheService {
350
413
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
351
414
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
352
415
  private readonly tagIndex = new Map<string, Set<string>>();
416
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
417
+ private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number }>();
353
418
  /**
354
419
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
355
420
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -358,6 +423,10 @@ export class CacheService {
358
423
  private redis: AnyRedisClient | null = null;
359
424
  private redisConnecting: Promise<AnyRedisClient> | null = null;
360
425
  private readonly cb: L2CircuitBreaker;
426
+ /** In-process mutex lock map for single-process environments or Redis outages. */
427
+ private _localLocks = new Map<string, Promise<void>>();
428
+ /** Active OpenTelemetry monotonic counters. */
429
+ private _otelMetrics: Partial<Record<string, ICacheCounter>> = {};
361
430
  private snapshotLoaded = false;
362
431
  private _readyPromise: Promise<void> = Promise.resolve();
363
432
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
@@ -368,10 +437,14 @@ export class CacheService {
368
437
  private latencyTracker: LatencyTracker | null = null;
369
438
  private readonly instanceId: string;
370
439
  private readonly backplaneChannel: string;
440
+ private readonly backplaneStreamKey: string;
371
441
  private subClient: AnyRedisClient | null = null;
442
+ private streamClient: AnyRedisClient | null = null;
443
+ private _lastStreamId = '$';
444
+ private _destroyed = false;
372
445
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
373
446
  private _subDisconnectedAt: number | null = null;
374
- private readonly counters = {
447
+ private counters = {
375
448
  gets: 0,
376
449
  l1Hits: 0,
377
450
  diskHits: 0,
@@ -384,6 +457,9 @@ export class CacheService {
384
457
  invSent: 0,
385
458
  invReceived: 0,
386
459
  invSkipped: 0,
460
+ streamEntriesReceived: 0,
461
+ streamReplays: 0,
462
+ streamGaps: 0,
387
463
  oomEvictions: 0,
388
464
  oomLastAt: null as number | null,
389
465
  /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
@@ -391,6 +467,8 @@ export class CacheService {
391
467
  /** Times a later `create(ns)` call passed options differing from the live singleton. */
392
468
  singletonDivergences: 0,
393
469
  startedAt: Date.now(),
470
+ bloomChecks: 0,
471
+ bloomFalsePositives: 0,
394
472
  };
395
473
 
396
474
  /** One-time guard so the in-process increment() fallback warning fires only once. */
@@ -428,7 +506,7 @@ export class CacheService {
428
506
  logger,
429
507
  l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
430
508
  l1MaxEntries: options.l1MaxEntries ?? 2_000,
431
- categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...(options.categoryLimits ?? {}) },
509
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
432
510
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
433
511
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
434
512
  // two instances with different namespaces never share cache files.
@@ -457,6 +535,7 @@ export class CacheService {
457
535
  l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
458
536
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
459
537
  tracer: options.tracer,
538
+ meter: options.meter,
460
539
  notFoundTtl: options.notFoundTtl ?? 0,
461
540
  warmKeys: options.warmKeys,
462
541
  onHit: options.onHit,
@@ -473,8 +552,19 @@ export class CacheService {
473
552
  disableDisk: options.disableDisk ?? false,
474
553
  redisClusterNodes: options.redisClusterNodes,
475
554
  redisSentinel: options.redisSentinel,
555
+ redisProtocol: options.redisProtocol,
556
+ useShardedPubSub: options.useShardedPubSub ?? false,
557
+ compression: options.compression ?? 'none',
558
+ compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
476
559
  strictSingleton: options.strictSingleton ?? false,
477
560
  failClosed: options.failClosed ?? false,
561
+ tagStrategy: options.tagStrategy ?? 'set',
562
+ tagVersionTtlMs: options.tagVersionTtlMs ?? 5_000,
563
+ cloneStrategy: options.cloneStrategy ?? 'none',
564
+ backplaneMode: options.backplaneMode ?? 'pubsub',
565
+ backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
566
+ backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2_000,
567
+ backplaneStreamKey: options.backplaneStreamKey,
478
568
  };
479
569
 
480
570
  // Circuit breaker for L2 Redis
@@ -513,6 +603,8 @@ export class CacheService {
513
603
  entryMaxBytes: this.opts.diskEntryMaxBytes,
514
604
  forbiddenPrefixes: forbiddenPrefixes,
515
605
  encryption: this.enc.isEnabled ? this.enc : null,
606
+ compression: this.opts.compression,
607
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
516
608
  logger,
517
609
  });
518
610
 
@@ -551,8 +643,8 @@ export class CacheService {
551
643
  process.once('SIGTERM', this._shutdownHandler);
552
644
  process.once('SIGINT', this._shutdownHandler);
553
645
 
554
- // ── Fix 1: Worker thread pool for off-main-thread AES-GCM ────────────────
555
- if (this.opts.workerThreads && this.enc.isEnabled) {
646
+ // ── Fix 1: Worker thread pool for off-main-thread AES-GCM & Compression ──
647
+ if (this.opts.workerThreads) {
556
648
  try {
557
649
  const encRef = this.enc.toWorkerInit();
558
650
  this._workerPool = new WorkerPool({
@@ -560,6 +652,8 @@ export class CacheService {
560
652
  mode: encRef.mode as never,
561
653
  prevKeyBase64: encRef.prevKeyBase64,
562
654
  prevMode: encRef.prevMode as never,
655
+ compression: this.opts.compression,
656
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
563
657
  size: this.opts.workerPoolSize || undefined,
564
658
  });
565
659
  if (this._workerPool.isAvailable) {
@@ -621,15 +715,38 @@ export class CacheService {
621
715
  if (this.metricsInterval.unref) this.metricsInterval.unref();
622
716
  }
623
717
 
624
- // Backplane: assign instance ID + channel, then subscribe
625
- this.instanceId = crypto.randomBytes(8).toString('hex');
626
- this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
718
+ // Backplane: assign instance ID + channel + streamKey, then subscribe
719
+ this.instanceId = crypto.randomBytes(8).toString('hex');
720
+ this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
721
+ this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
627
722
  this.initBackplane();
628
723
 
629
724
  // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
630
725
  if (this.opts.warmKeys) {
631
726
  this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
632
727
  }
728
+
729
+ // Native OpenTelemetry metrics integration
730
+ if (this.opts.meter) {
731
+ this._initOtelMetrics(this.opts.meter);
732
+ const otel = this._otelMetrics;
733
+ const nsAttr = this._namespace ? { namespace: this._namespace } : undefined;
734
+ const targetCounters = this.counters;
735
+
736
+ this.counters = new Proxy(targetCounters, {
737
+ set(target, prop, value, receiver) {
738
+ const oldVal = (target as any)[prop];
739
+ const ok = Reflect.set(target, prop, value, receiver);
740
+ if (typeof prop === 'string' && typeof value === 'number' && typeof oldVal === 'number') {
741
+ const diff = value - oldVal;
742
+ if (diff > 0 && otel[prop]) {
743
+ otel[prop]!.add(diff, nsAttr);
744
+ }
745
+ }
746
+ return ok;
747
+ },
748
+ });
749
+ }
633
750
  }
634
751
 
635
752
  // ── Singleton factory ─────────────────────────────────────────────────────
@@ -775,7 +892,8 @@ export class CacheService {
775
892
  private _jitterTtl(ttlMs: number): number {
776
893
  const j = this.opts.ttlJitterFactor;
777
894
  if (j === 0) return ttlMs;
778
- return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
895
+ const rand = (crypto.randomInt(0, 100_000) / 50_000) - 1; // uniform [-1.0, +1.0)
896
+ return Math.round(ttlMs * (1 + rand * j));
779
897
  }
780
898
 
781
899
  /** Shared no-op span for the common case where no tracer is configured.
@@ -792,22 +910,18 @@ export class CacheService {
792
910
  return CacheService._nullSpan;
793
911
  }
794
912
 
795
- private initBackplane(): void {
796
- if (!this.opts.invalidationBackplane || this._redisDisabled) return;
797
- if (this.subClient) return;
798
-
799
- // ── Fix 4: Cluster/Sentinel subscriber ─────────────────────────────────
800
- let sub: AnyRedisClient;
913
+ private createDedicatedRedisClient(): AnyRedisClient {
801
914
  if (this.opts.redisClusterNodes?.length) {
802
- sub = new RedisCluster(this.opts.redisClusterNodes, {
915
+ return new RedisCluster(this.opts.redisClusterNodes, {
803
916
  redisOptions: {
804
917
  tls: this.opts.redisTls ? {} : undefined,
805
918
  connectTimeout: 10_000,
806
919
  maxRetriesPerRequest: null as unknown as number,
920
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
807
921
  },
808
922
  });
809
923
  } else if (this.opts.redisSentinel) {
810
- sub = new RedisClient({
924
+ return new RedisClient({
811
925
  sentinels: this.opts.redisSentinel.sentinels,
812
926
  name: this.opts.redisSentinel.name,
813
927
  tls: this.opts.redisTls ? {} : undefined,
@@ -816,9 +930,10 @@ export class CacheService {
816
930
  maxRetriesPerRequest: null as unknown as number,
817
931
  enableAutoPipelining: false,
818
932
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
933
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
819
934
  });
820
935
  } else {
821
- sub = new RedisClient({
936
+ return new RedisClient({
822
937
  host: this.opts.redisHost,
823
938
  port: this.opts.redisPort,
824
939
  tls: this.opts.redisTls ? {} : undefined,
@@ -828,13 +943,30 @@ export class CacheService {
828
943
  enableAutoPipelining: false,
829
944
  family: 4,
830
945
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
946
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
831
947
  });
832
948
  }
949
+ }
950
+
951
+ private initBackplane(): void {
952
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
953
+
954
+ if (this.opts.backplaneMode === 'stream') {
955
+ if (this.streamClient) return;
956
+ void this._startStreamConsumer();
957
+ return;
958
+ }
833
959
 
834
- sub.on('error', (e: Error) =>
835
- this.logger.debug('Backplane subscriber error', { error: e.message }));
960
+ if (this.subClient) return;
836
961
 
837
- // ── Fix 2: Staleness fence — track disconnect time ──────────────────────
962
+ const sub = this.createDedicatedRedisClient();
963
+
964
+ sub.on('error', (e: Error) => {
965
+ this._checkAndLogResp3Hint(e);
966
+ this.logger.debug('Backplane subscriber error', { error: e.message });
967
+ });
968
+
969
+ // ── Staleness fence — track disconnect time ──────────────────────
838
970
  sub.on('close', () => {
839
971
  if (this._subDisconnectedAt === null) {
840
972
  this._subDisconnectedAt = Date.now();
@@ -846,9 +978,6 @@ export class CacheService {
846
978
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
847
979
  const gapMs = Date.now() - this._subDisconnectedAt;
848
980
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
849
- // We were disconnected long enough that peer invalidations were
850
- // almost certainly missed. Evict every L1 entry written before
851
- // the disconnect started so stale data cannot be served.
852
981
  const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
853
982
  this.logger.warn('Backplane: reconnect after gap — flushed potentially stale L1 entries', {
854
983
  gapMs, evicted,
@@ -859,64 +988,292 @@ export class CacheService {
859
988
  }
860
989
  });
861
990
 
862
- sub.on('message', (_channel: string, message: string) => {
863
- this._handleBackplaneMessage(message);
864
- });
991
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
865
992
 
866
- sub.subscribe(this.backplaneChannel)
867
- .then(() => this.logger.info('Backplane: subscribed', {
868
- channel: this.backplaneChannel, instanceId: this.instanceId,
869
- }))
870
- .catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
871
- error: err.message,
872
- }));
993
+ if (isClusterSharded) {
994
+ sub.on('smessage', (_channel: string, message: string) => {
995
+ this._handleBackplaneMessage(message);
996
+ });
997
+ (sub as unknown as { ssubscribe: (c: string) => Promise<unknown> })
998
+ .ssubscribe(this.backplaneChannel)
999
+ .then(() => this.logger.info('Backplane: sharded subscribed', {
1000
+ channel: this.backplaneChannel, instanceId: this.instanceId,
1001
+ }))
1002
+ .catch((err: Error) => this.logger.warn('Backplane: sharded subscribe failed', {
1003
+ error: err.message,
1004
+ }));
1005
+ } else {
1006
+ sub.on('message', (_channel: string, message: string) => {
1007
+ this._handleBackplaneMessage(message);
1008
+ });
1009
+ sub.subscribe(this.backplaneChannel)
1010
+ .then(() => this.logger.info('Backplane: subscribed', {
1011
+ channel: this.backplaneChannel, instanceId: this.instanceId,
1012
+ }))
1013
+ .catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
1014
+ error: err.message,
1015
+ }));
1016
+ }
873
1017
 
874
1018
  this.subClient = sub;
875
1019
  }
876
1020
 
1021
+ private async _startStreamConsumer(): Promise<void> {
1022
+ const sub = this.streamClient ?? this.createDedicatedRedisClient();
1023
+ this.streamClient = sub;
1024
+
1025
+ if (typeof (sub as any).on === 'function') {
1026
+ sub.on('error', (e: Error) =>
1027
+ this.logger.debug('Backplane stream consumer error', { error: e.message }));
1028
+
1029
+ sub.on('close', () => {
1030
+ if (this._subDisconnectedAt === null) {
1031
+ this._subDisconnectedAt = Date.now();
1032
+ this.logger.debug('Backplane stream: consumer disconnected', { at: this._subDisconnectedAt });
1033
+ }
1034
+ });
1035
+
1036
+ sub.on('ready', () => {
1037
+ if (this._subDisconnectedAt !== null) {
1038
+ this.logger.debug('Backplane stream: consumer reconnected, resuming stream read', { lastId: this._lastStreamId });
1039
+ this._subDisconnectedAt = null;
1040
+ }
1041
+ });
1042
+ }
1043
+
1044
+ // Continuous async worker loop
1045
+ const runLoop = async () => {
1046
+ while (!this._destroyed && !this._redisDisabled) {
1047
+ try {
1048
+ const res = await (sub as any).xread(
1049
+ 'BLOCK', this.opts.backplaneStreamBlockMs,
1050
+ 'STREAMS', this.backplaneStreamKey, this._lastStreamId,
1051
+ ) as Array<[string, Array<[string, string[]]>]> | null;
1052
+
1053
+ if (this._destroyed) break;
1054
+
1055
+ if (res && res.length > 0) {
1056
+ for (const [, entries] of res) {
1057
+ if (entries.length > 0) {
1058
+ if (this._lastStreamId !== '$') {
1059
+ this.counters.streamReplays++;
1060
+ }
1061
+
1062
+ for (const [id, fields] of entries) {
1063
+ this._lastStreamId = id;
1064
+ this.counters.streamEntriesReceived++;
1065
+
1066
+ let op = '';
1067
+ let key = '';
1068
+ let src = '';
1069
+ let tagVersion: number | undefined;
1070
+
1071
+ for (let i = 0; i < fields.length; i += 2) {
1072
+ const f = fields[i];
1073
+ const v = fields[i + 1];
1074
+ if (f === 'op') op = v;
1075
+ else if (f === 'key') key = v;
1076
+ else if (f === 'src') src = v;
1077
+ else if (f === 'tagVersion') tagVersion = parseInt(v, 10);
1078
+ }
1079
+
1080
+ if (src === this.instanceId) {
1081
+ this.counters.invSkipped++;
1082
+ continue;
1083
+ }
1084
+
1085
+ this.counters.invReceived++;
1086
+ this._applyInvalidationEvent(op, key, tagVersion);
1087
+ }
1088
+ }
1089
+ }
1090
+ } else {
1091
+ // Idle timeout without messages — yield briefly before next long-poll
1092
+ await new Promise(resolve => setTimeout(resolve, 10));
1093
+ }
1094
+ } catch (err) {
1095
+ if (this._destroyed) break;
1096
+ const msg = (err as Error).message ?? '';
1097
+ if (msg.includes('NOGROUP') || msg.includes('smaller than') || msg.includes('trimmed')) {
1098
+ this.counters.streamGaps++;
1099
+ this.l1.clear();
1100
+ this._lastStreamId = '$';
1101
+ }
1102
+ await new Promise(resolve => setTimeout(resolve, 200));
1103
+ }
1104
+ }
1105
+ };
1106
+
1107
+ void runLoop();
1108
+ }
1109
+
1110
+ private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): void {
1111
+ if (op === 'del') {
1112
+ this.l1.delete(key);
1113
+ setImmediate(() => { if (!this._diskDisabled) this.disk.delete(key); });
1114
+ this._cascadeDependencies(key);
1115
+ } else if (op === 'del-glob') {
1116
+ this.l1.deletePattern(key);
1117
+ } else if (op === 'tag_incr') {
1118
+ const tag = key;
1119
+ const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1120
+ this._setLocalTagVersion(tag, ver, Date.now());
1121
+ }
1122
+ this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1123
+ }
1124
+
877
1125
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
878
1126
  _handleBackplaneMessage(message: string): void {
879
1127
  try {
880
- const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
1128
+ const msg = JSON.parse(message);
1129
+ if (
1130
+ !msg ||
1131
+ typeof msg !== 'object' ||
1132
+ Array.isArray(msg) ||
1133
+ typeof msg.src !== 'string' ||
1134
+ typeof msg.key !== 'string' ||
1135
+ (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr')
1136
+ ) {
1137
+ this.logger.warn('Backplane: rejected invalid pubsub message format', {
1138
+ raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
1139
+ });
1140
+ return;
1141
+ }
881
1142
  if (msg.src === this.instanceId) {
882
1143
  this.counters.invSkipped++;
883
1144
  return; // own message — our L1 is already current
884
1145
  }
885
1146
  this.counters.invReceived++;
886
- if (msg.op === 'del') {
887
- // L1 eviction is synchronous and O(1); disk delete is deferred via
888
- // setImmediate so the event-loop tick that processes this pub/sub
889
- // message returns immediately without blocking hot get() calls.
890
- this.l1.delete(msg.key);
891
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(msg.key); });
892
- // Cascade: evict dependents registered on this instance for the
893
- // deleted key — same logic the local delete() path runs, now also
894
- // applied to peer-originated invalidations so fleet-wide deletes
895
- // propagate dependency cascades to every node.
896
- this._cascadeDependencies(msg.key);
897
- } else if (msg.op === 'del-glob') {
898
- // Glob patterns clean L1 only — disk entries expire naturally via
899
- // the background purge timer or are bypassed on the next L1 miss.
900
- this.l1.deletePattern(msg.key);
901
- }
902
- this.logger.debug('Backplane: peer invalidation applied', {
903
- op: msg.op, key: msg.key.slice(0, 60),
904
- });
905
- } catch { /* malformed message — ignore */ }
1147
+ this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === 'number' ? msg.tagVersion : undefined);
1148
+ } catch {
1149
+ this.logger.warn('Backplane: malformed message JSON parse failed');
1150
+ }
906
1151
  }
907
1152
 
908
- private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
1153
+ private async publishInvalidation(op: 'del' | 'del-glob' | 'tag_incr', key: string, tagVersion?: number): Promise<void> {
909
1154
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
910
1155
  try {
911
1156
  const client = await this.getRedis();
912
- await client.publish(
913
- this.backplaneChannel,
914
- JSON.stringify({ op, key, src: this.instanceId }),
915
- );
1157
+
1158
+ if (this.opts.backplaneMode === 'stream') {
1159
+ const args: string[] = [
1160
+ this.backplaneStreamKey,
1161
+ 'MAXLEN', '~', String(this.opts.backplaneStreamMaxLen),
1162
+ '*',
1163
+ 'op', op,
1164
+ 'key', key,
1165
+ 'src', this.instanceId,
1166
+ ];
1167
+ if (typeof tagVersion === 'number') {
1168
+ args.push('tagVersion', String(tagVersion));
1169
+ }
1170
+ await (client as any).xadd(...args);
1171
+ this.counters.invSent++;
1172
+ return;
1173
+ }
1174
+
1175
+ const payload = JSON.stringify({ op, key, src: this.instanceId, tagVersion });
1176
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
1177
+ if (isClusterSharded && typeof (client as unknown as { spublish?: unknown }).spublish === 'function') {
1178
+ await (client as unknown as { spublish: (c: string, m: string) => Promise<unknown> }).spublish(
1179
+ this.backplaneChannel,
1180
+ payload,
1181
+ );
1182
+ } else {
1183
+ await client.publish(
1184
+ this.backplaneChannel,
1185
+ payload,
1186
+ );
1187
+ }
916
1188
  this.counters.invSent++;
917
1189
  } catch { /* non-critical — never block the caller */ }
918
1190
  }
919
1191
 
1192
+ private _setLocalTagVersion(tag: string, version: number, now = Date.now()): void {
1193
+ const existing = this.tagVersions.get(tag)?.version ?? 0;
1194
+ const finalVersion = Math.max(existing, version);
1195
+ if (this.tagVersions.size >= 10_000 && !this.tagVersions.has(tag)) {
1196
+ const oldestKey = this.tagVersions.keys().next().value;
1197
+ if (oldestKey !== undefined) this.tagVersions.delete(oldestKey);
1198
+ }
1199
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
1200
+ }
1201
+
1202
+ private async _getTagVersion(tag: string): Promise<number> {
1203
+ const now = Date.now();
1204
+ const local = this.tagVersions.get(tag);
1205
+ if (local && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
1206
+ return local.version;
1207
+ }
1208
+ if (!this._redisDisabled) {
1209
+ try {
1210
+ const client = await this.getRedis();
1211
+ const raw = await client.get(this.nk(`tag_ver:${tag}`));
1212
+ const version = raw ? parseInt(raw, 10) : 0;
1213
+ this._setLocalTagVersion(tag, version, now);
1214
+ return version;
1215
+ } catch {
1216
+ /* fallback to local */
1217
+ }
1218
+ }
1219
+ return local?.version ?? 0;
1220
+ }
1221
+
1222
+ private _deleteIfStale(k: string, setAtMs: number): void {
1223
+ this.l1.deleteIfSetBefore(k, setAtMs);
1224
+ if (!this._diskDisabled) this.disk.delete(k);
1225
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
1226
+ void this.getRedis().then(client => {
1227
+ return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
1228
+ }).catch(() => {});
1229
+ }
1230
+ }
1231
+
1232
+ /**
1233
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
1234
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
1235
+ */
1236
+ private async _serializeAndEncrypt(serialized: string): Promise<string> {
1237
+ const isCompressed = this.opts.compression && this.opts.compression !== 'none' && serialized.length > this.opts.compressionThresholdBytes;
1238
+ if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1239
+ return this._workerPool.encrypt(serialized);
1240
+ }
1241
+ if (isCompressed) {
1242
+ const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression);
1243
+ if (this.enc.isEnabled) {
1244
+ const encrypted = this.enc.encryptBuffer(compressed);
1245
+ return PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
1246
+ }
1247
+ return PREFIX_COMPRESSED + compressed.toString('base64');
1248
+ }
1249
+ return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1250
+ }
1251
+
1252
+ /**
1253
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
1254
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
1255
+ */
1256
+ private async _decryptAndDeserialize<T>(raw: string): Promise<T> {
1257
+ let plain: string;
1258
+ if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
1259
+ plain = await this._workerPool.decrypt(raw);
1260
+ } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
1261
+ const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
1262
+ const decBuf = this.enc.decryptBuffer(encBuf);
1263
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1264
+ plain = decompressed.toString('utf8');
1265
+ } else if (raw.startsWith(PREFIX_COMPRESSED)) {
1266
+ const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), 'base64');
1267
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1268
+ plain = decompressed.toString('utf8');
1269
+ } else if (raw.startsWith('enc:v1:') || this.enc.isEnabled) {
1270
+ plain = this.enc.decrypt(raw);
1271
+ } else {
1272
+ plain = raw;
1273
+ }
1274
+ return JSON.parse(plain) as T;
1275
+ }
1276
+
920
1277
  /**
921
1278
  * Scan all keys matching `pattern` across single-node or Cluster clients.
922
1279
  * For Cluster, iterates every master node independently (SCAN is node-local).
@@ -944,8 +1301,26 @@ export class CacheService {
944
1301
  return keys;
945
1302
  }
946
1303
 
1304
+ private _checkAndLogResp3Hint(err: Error): void {
1305
+ const msg = err?.message || '';
1306
+ if (
1307
+ !this.opts.redisProtocol &&
1308
+ (msg.includes('unknown command') ||
1309
+ msg.includes('HELLO') ||
1310
+ msg.includes('protocol error') ||
1311
+ msg.includes('ProtocolError') ||
1312
+ msg.includes('Connection is closed'))
1313
+ ) {
1314
+ this.logger.warn(
1315
+ 'Redis connection/protocol error detected. If your Redis endpoint or proxy (e.g. Twemproxy, Envoy, older ElastiCache) does not support RESP3, set redisProtocol: 2 in CacheOptions to force RESP2 compatibility.',
1316
+ { hint: 'redisProtocol: 2', originalError: msg },
1317
+ );
1318
+ }
1319
+ }
1320
+
947
1321
  private async getRedis(): Promise<AnyRedisClient> {
948
1322
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
1323
+ if (this.redis) return this.redis;
949
1324
  if (this.redisConnecting) return this.redisConnecting;
950
1325
 
951
1326
  this.redisConnecting = (async () => {
@@ -961,13 +1336,17 @@ export class CacheService {
961
1336
  connectTimeout: 10_000,
962
1337
  maxRetriesPerRequest: 3,
963
1338
  keepAlive: 30_000,
1339
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
964
1340
  },
965
1341
  enableAutoPipelining: true,
966
1342
  retryDelayOnClusterDown: 200,
967
1343
  retryDelayOnFailover: 1_000,
968
1344
  });
969
1345
  client.on('connect', () => this.logger.info('Redis Cluster connected'));
970
- client.on('error', (e: Error) => this.logger.error('Redis Cluster error', {}, e));
1346
+ client.on('error', (e: Error) => {
1347
+ this._checkAndLogResp3Hint(e);
1348
+ this.logger.error('Redis Cluster error', {}, e);
1349
+ });
971
1350
  client.on('reconnecting', () => this.logger.debug('Redis Cluster reconnecting'));
972
1351
  } else if (this.opts.redisSentinel) {
973
1352
  // Redis Sentinel — ioredis monitors master via sentinel topology.
@@ -981,9 +1360,13 @@ export class CacheService {
981
1360
  enableAutoPipelining: true,
982
1361
  keepAlive: 30_000,
983
1362
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
1363
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
984
1364
  });
985
1365
  client.on('connect', () => this.logger.info('Redis Sentinel connected', { name: this.opts.redisSentinel!.name }));
986
- client.on('error', (e: Error) => this.logger.error('Redis Sentinel error', { name: this.opts.redisSentinel!.name }, e));
1366
+ client.on('error', (e: Error) => {
1367
+ this._checkAndLogResp3Hint(e);
1368
+ this.logger.error('Redis Sentinel error', { name: this.opts.redisSentinel!.name }, e);
1369
+ });
987
1370
  client.on('reconnecting', () => this.logger.debug('Redis Sentinel reconnecting'));
988
1371
  } else {
989
1372
  // Single-node (original path)
@@ -998,15 +1381,22 @@ export class CacheService {
998
1381
  keepAlive: 30_000,
999
1382
  family: 4,
1000
1383
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
1384
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
1001
1385
  });
1002
1386
  client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
1003
- client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
1387
+ client.on('error', (e: Error) => {
1388
+ this._checkAndLogResp3Hint(e);
1389
+ this.logger.error('Redis error', { host: this.opts.redisHost }, e);
1390
+ });
1004
1391
  client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
1005
1392
  }
1006
1393
 
1007
1394
  await new Promise<void>((resolve, reject) => {
1008
1395
  client.once('ready', resolve);
1009
- client.once('error', reject);
1396
+ client.once('error', (e: Error) => {
1397
+ this._checkAndLogResp3Hint(e);
1398
+ reject(e);
1399
+ });
1010
1400
  setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
1011
1401
  });
1012
1402
 
@@ -1017,6 +1407,7 @@ export class CacheService {
1017
1407
  } catch (err) {
1018
1408
  this.cb.onFailure();
1019
1409
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
1410
+ this._checkAndLogResp3Hint(err as Error);
1020
1411
  throw err;
1021
1412
  }
1022
1413
  })();
@@ -1035,7 +1426,7 @@ export class CacheService {
1035
1426
  const packed = pack(payload);
1036
1427
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1037
1428
  const dest = altPath ?? this.opts.snapshotPath;
1038
-
1429
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1039
1430
  fs.writeFileSync(dest, final, { mode: 0o600 });
1040
1431
  this.logger.info('Cache snapshot written', {
1041
1432
  path: dest, entries: entries.length,
@@ -1159,60 +1550,67 @@ export class CacheService {
1159
1550
  // L1: in-memory (fastest path)
1160
1551
  const l1Hit = this.l1.get(k);
1161
1552
  if (l1Hit !== null) {
1162
- if (l1Hit.isStale) {
1163
- const swrGraceMs = optSwr * 1_000;
1164
- if (swrGraceMs > 0 && !this.revalidating.has(k)) {
1165
- const priority = optPriority ?? inferPriority(cacheKey);
1166
- this.revalidating.add(k);
1167
- void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
1168
- this.counters.swrRevalidations++;
1169
- this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
1170
- } else {
1171
- this.logger.debug('L1 hit');
1553
+ let isGenerationalStale = false;
1554
+ if (this.opts.tagStrategy === 'generational' && l1Hit.tagVersions) {
1555
+ for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
1556
+ const currentVer = await this._getTagVersion(tag);
1557
+ if (currentVer > entryVer) {
1558
+ isGenerationalStale = true;
1559
+ break;
1560
+ }
1172
1561
  }
1562
+ }
1563
+
1564
+ if (isGenerationalStale) {
1565
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
1173
1566
  } else {
1174
- this.logger.debug('L1 hit');
1175
- // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
1176
- // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
1177
- // Check opts first — pointless work when neither feature is configured.
1178
- // Local aliases for the opts fields already normalised at function entry.
1179
- const ra = optRefreshAhead;
1180
- const xb = optXfetchBeta;
1181
- if (ra || xb) {
1182
- // Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
1183
- const now = l1Hit.fetchedAt ?? Date.now();
1184
- const remaining = l1Hit.expiresAt - now;
1185
- const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
1186
-
1187
- const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
1188
-
1189
- // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
1190
- // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
1191
- const shouldXFetch = xb && l1Hit.delta != null
1192
- ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
1193
- : false;
1194
-
1195
- // Set.has() deferred to here — the common case (fresh key, threshold not crossed)
1196
- // never pays the ~30 ns lookup cost.
1197
- if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
1198
- // Defer inferPriority until we actually need it — avoids 3× string.includes()
1199
- // scans on every warm hit when the threshold check is false (the common case).
1567
+ if (l1Hit.isStale) {
1568
+ const swrGraceMs = optSwr * 1_000;
1569
+ if (swrGraceMs > 0 && !this.revalidating.has(k)) {
1200
1570
  const priority = optPriority ?? inferPriority(cacheKey);
1201
1571
  this.revalidating.add(k);
1202
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
1572
+ void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
1203
1573
  this.counters.swrRevalidations++;
1204
- this.logger.debug(
1205
- shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
1206
- { cacheKey, remainingMs: remaining, ttlMs: entryTtl },
1207
- );
1574
+ this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
1575
+ } else {
1576
+ this.logger.debug('L1 hit');
1577
+ }
1578
+ } else {
1579
+ this.logger.debug('L1 hit');
1580
+ // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
1581
+ // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
1582
+ const ra = optRefreshAhead;
1583
+ const xb = optXfetchBeta;
1584
+ if (ra || xb) {
1585
+ const now = l1Hit.fetchedAt ?? Date.now();
1586
+ const remaining = l1Hit.expiresAt - now;
1587
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
1588
+
1589
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
1590
+ const shouldXFetch = xb && l1Hit.delta != null
1591
+ ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
1592
+ : false;
1593
+
1594
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
1595
+ const priority = optPriority ?? inferPriority(cacheKey);
1596
+ this.revalidating.add(k);
1597
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
1598
+ this.counters.swrRevalidations++;
1599
+ this.logger.debug(
1600
+ shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
1601
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl },
1602
+ );
1603
+ }
1208
1604
  }
1209
1605
  }
1606
+ this.counters.l1Hits++;
1607
+ this.opts.onHit?.(cacheKey, 'l1');
1608
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
1609
+ span.setAttribute('cache.hit', 'l1').end();
1610
+ return (this.opts.cloneStrategy === 'structuredClone' && l1Hit.value != null && typeof l1Hit.value === 'object')
1611
+ ? structuredClone(l1Hit.value) as T
1612
+ : l1Hit.value as T;
1210
1613
  }
1211
- this.counters.l1Hits++;
1212
- this.opts.onHit?.(cacheKey, 'l1');
1213
- if (this.opts.frozen) deepFreeze(l1Hit.value);
1214
- span.setAttribute('cache.hit', 'l1').end();
1215
- return l1Hit.value as T;
1216
1614
  }
1217
1615
 
1218
1616
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
@@ -1223,23 +1621,53 @@ export class CacheService {
1223
1621
  if (!this._redisDisabled) {
1224
1622
  try {
1225
1623
  const client = await this.getRedis();
1226
- const raw = await client.get(k);
1227
- this.cb.onSuccess();
1228
- if (raw) {
1229
- // ── Fix 1: offload decryption to worker thread for large payloads ──
1230
- let decrypted: string;
1231
- if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
1232
- decrypted = await this._workerPool.decrypt(raw);
1233
- } else {
1234
- decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1624
+ if (this.opts.tagStrategy === 'generational') {
1625
+ const hashData = await client.hgetall(k);
1626
+ this.cb.onSuccess();
1627
+ if (hashData && hashData.d) {
1628
+ let isStale = false;
1629
+ let storedTagVersions: Record<string, number> = {};
1630
+ if (hashData.tv) {
1631
+ try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
1632
+ }
1633
+ for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
1634
+ const currentVer = await this._getTagVersion(tag);
1635
+ if (currentVer > entryVer) {
1636
+ isStale = true;
1637
+ break;
1638
+ }
1639
+ }
1640
+ if (isStale) {
1641
+ const setAtMs = parseInt(hashData.t, 10) || 0;
1642
+ this._deleteIfStale(k, setAtMs);
1643
+ } else {
1644
+ const parsed = await this._decryptAndDeserialize<T>(hashData.d);
1645
+ this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
1646
+ this.counters.l2Hits++;
1647
+ this.opts.onHit?.(cacheKey, 'l2');
1648
+ this.logger.debug('L2 hit (Redis hash)', { cacheKey });
1649
+ span.setAttribute('cache.hit', 'l2').end();
1650
+ if (this.opts.frozen) deepFreeze(parsed);
1651
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
1652
+ ? structuredClone(parsed)
1653
+ : parsed;
1654
+ }
1655
+ }
1656
+ } else {
1657
+ const raw = await client.get(k);
1658
+ this.cb.onSuccess();
1659
+ if (raw) {
1660
+ const parsed = await this._decryptAndDeserialize<T>(raw);
1661
+ this.l1.set(k, parsed, ttlMs, priority);
1662
+ this.counters.l2Hits++;
1663
+ this.opts.onHit?.(cacheKey, 'l2');
1664
+ this.logger.debug('L2 hit (Redis)', { cacheKey });
1665
+ span.setAttribute('cache.hit', 'l2').end();
1666
+ if (this.opts.frozen) deepFreeze(parsed);
1667
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
1668
+ ? structuredClone(parsed)
1669
+ : parsed;
1235
1670
  }
1236
- const parsed = JSON.parse(decrypted) as T;
1237
- this.l1.set(k, parsed, ttlMs, priority);
1238
- this.counters.l2Hits++;
1239
- this.opts.onHit?.(cacheKey, 'l2');
1240
- this.logger.debug('L2 hit (Redis)', { cacheKey });
1241
- span.setAttribute('cache.hit', 'l2').end();
1242
- return parsed;
1243
1671
  }
1244
1672
  } catch (err) {
1245
1673
  this.cb.onFailure();
@@ -1251,18 +1679,36 @@ export class CacheService {
1251
1679
  if (!this._diskDisabled) {
1252
1680
  const diskHit = this.disk.load(k);
1253
1681
  if (diskHit !== null) {
1254
- const promoted = this.l1.importEntries(
1255
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
1256
- this.opts.forbiddenSnapshotPrefixes,
1257
- );
1258
- if (promoted > 0) {
1259
- const l1Check = this.l1.get(k);
1260
- if (l1Check !== null) {
1261
- this.counters.diskHits++;
1262
- this.opts.onHit?.(cacheKey, 'disk');
1263
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
1264
- span.setAttribute('cache.hit', 'disk').end();
1265
- return l1Check.value as T;
1682
+ let isDiskStale = false;
1683
+ if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
1684
+ for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
1685
+ const currentVer = await this._getTagVersion(tag);
1686
+ if (currentVer > entryVer) {
1687
+ isDiskStale = true;
1688
+ break;
1689
+ }
1690
+ }
1691
+ }
1692
+
1693
+ if (isDiskStale) {
1694
+ this.disk.delete(k);
1695
+ } else {
1696
+ const promoted = this.l1.importEntries(
1697
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
1698
+ this.opts.forbiddenSnapshotPrefixes,
1699
+ );
1700
+ if (promoted > 0) {
1701
+ const l1Check = this.l1.get(k);
1702
+ if (l1Check !== null) {
1703
+ this.counters.diskHits++;
1704
+ this.opts.onHit?.(cacheKey, 'disk');
1705
+ this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
1706
+ span.setAttribute('cache.hit', 'disk').end();
1707
+ if (this.opts.frozen) deepFreeze(l1Check.value);
1708
+ return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
1709
+ ? structuredClone(l1Check.value) as T
1710
+ : l1Check.value as T;
1711
+ }
1266
1712
  }
1267
1713
  }
1268
1714
  }
@@ -1291,9 +1737,6 @@ export class CacheService {
1291
1737
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
1292
1738
  let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
1293
1739
 
1294
- // Adaptive TTL: record this fetch duration and override the caller-supplied
1295
- // TTL once ≥ 5 samples are available for the key.
1296
- // Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
1297
1740
  if (this.latencyTracker && data != null) {
1298
1741
  this.latencyTracker.record(k, delta);
1299
1742
  const p95 = this.latencyTracker.p95(k);
@@ -1309,21 +1752,39 @@ export class CacheService {
1309
1752
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
1310
1753
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1311
1754
 
1312
- this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1313
- if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
1755
+ let activeTagVersions: Record<string, number> | undefined;
1756
+ if (optTags?.length) {
1757
+ if (this.opts.tagStrategy === 'generational') {
1758
+ activeTagVersions = {};
1759
+ for (const tag of optTags) {
1760
+ activeTagVersions[tag] = await this._getTagVersion(tag);
1761
+ }
1762
+ } else {
1763
+ await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
1764
+ }
1765
+ }
1766
+
1767
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
1314
1768
 
1315
1769
  if (!this._redisDisabled) {
1316
1770
  try {
1317
1771
  const client = await this.getRedis();
1318
1772
  const serialized = JSON.stringify(data);
1319
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1320
- let toStore: string;
1321
- if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
1322
- toStore = await this._workerPool.encrypt(serialized);
1773
+ const toStore = await this._serializeAndEncrypt(serialized);
1774
+ const ttlSec = Math.ceil(effectiveTtl / 1_000);
1775
+ if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
1776
+ const now = Date.now();
1777
+ const tx = client.multi();
1778
+ tx.hset(k, {
1779
+ d: toStore,
1780
+ t: String(now),
1781
+ tv: JSON.stringify(activeTagVersions),
1782
+ });
1783
+ tx.expire(k, ttlSec);
1784
+ await tx.exec();
1323
1785
  } else {
1324
- toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1786
+ await client.setex(k, ttlSec, toStore);
1325
1787
  }
1326
- await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
1327
1788
  this.cb.onSuccess();
1328
1789
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1329
1790
  } catch {
@@ -1334,7 +1795,10 @@ export class CacheService {
1334
1795
  this.logger.debug('Cached L1', { cacheKey });
1335
1796
  }
1336
1797
 
1337
- return data;
1798
+ if (this.opts.frozen) deepFreeze(data);
1799
+ return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
1800
+ ? structuredClone(data)
1801
+ : data;
1338
1802
  } finally {
1339
1803
  this.inflight.delete(k);
1340
1804
  span.end();
@@ -1345,6 +1809,28 @@ export class CacheService {
1345
1809
  return fetchPromise;
1346
1810
  }
1347
1811
 
1812
+ /**
1813
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
1814
+ *
1815
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
1816
+ * from `cache-manager` and `keyv`.
1817
+ *
1818
+ * @param cacheKey - Unique cache key.
1819
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
1820
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
1821
+ *
1822
+ * @example
1823
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
1824
+ * ttl: 300,
1825
+ * swr: 60,
1826
+ * tags: ['users'],
1827
+ * });
1828
+ */
1829
+ wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T> {
1830
+ const ttl = options?.ttl ?? 300;
1831
+ return this.get<T>(cacheKey, fetchFn, ttl, options);
1832
+ }
1833
+
1348
1834
  private async _revalidate<T>(
1349
1835
  cacheKey: string,
1350
1836
  fetchFn: () => Promise<T>,
@@ -1361,20 +1847,36 @@ export class CacheService {
1361
1847
  // Keep the latency tracker current during SWR background revalidations too
1362
1848
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
1363
1849
 
1364
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
1850
+ let activeTagVersions: Record<string, number> | undefined;
1851
+ const l1Existing = this.l1.get(cacheKey);
1852
+ if (this.opts.tagStrategy === 'generational' && l1Existing?.tagVersions) {
1853
+ activeTagVersions = {};
1854
+ for (const tag of Object.keys(l1Existing.tagVersions)) {
1855
+ activeTagVersions[tag] = await this._getTagVersion(tag);
1856
+ }
1857
+ }
1858
+
1859
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
1365
1860
 
1366
1861
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
1367
1862
  try {
1368
1863
  const client = await this.getRedis();
1369
1864
  const s = JSON.stringify(data);
1370
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1371
- let stored: string;
1372
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
1373
- stored = await this._workerPool.encrypt(s);
1865
+ const stored = await this._serializeAndEncrypt(s);
1866
+ const ttlSec = Math.ceil(ttlMs / 1_000);
1867
+ if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
1868
+ const now = Date.now();
1869
+ const tx = client.multi();
1870
+ tx.hset(cacheKey, {
1871
+ d: stored,
1872
+ t: String(now),
1873
+ tv: JSON.stringify(activeTagVersions),
1874
+ });
1875
+ tx.expire(cacheKey, ttlSec);
1876
+ await tx.exec();
1374
1877
  } else {
1375
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1878
+ await client.setex(cacheKey, ttlSec, stored);
1376
1879
  }
1377
- await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
1378
1880
  } catch { /* ok */ }
1379
1881
  }
1380
1882
  this.logger.debug('SWR: revalidation complete', { cacheKey });
@@ -1403,9 +1905,20 @@ export class CacheService {
1403
1905
  const p = priority ?? inferPriority(cacheKey);
1404
1906
  const k = this.nk(cacheKey);
1405
1907
  this.counters.sets++;
1406
- this.l1.set(k, data, ttlMs, p);
1407
1908
 
1408
- if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
1909
+ let activeTagVersions: Record<string, number> | undefined;
1910
+ if (opts?.tags?.length) {
1911
+ if (this.opts.tagStrategy === 'generational') {
1912
+ activeTagVersions = {};
1913
+ for (const tag of opts.tags) {
1914
+ activeTagVersions[tag] = await this._getTagVersion(tag);
1915
+ }
1916
+ } else {
1917
+ await this._registerTags(k, opts.tags, ttlSeconds);
1918
+ }
1919
+ }
1920
+
1921
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
1409
1922
 
1410
1923
  // Register dependency patterns: when any key matching a pattern is deleted,
1411
1924
  // this key (k) is automatically cascaded.
@@ -1422,14 +1935,21 @@ export class CacheService {
1422
1935
  try {
1423
1936
  const client = await this.getRedis();
1424
1937
  const s = JSON.stringify(data);
1425
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1426
- let stored: string;
1427
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
1428
- stored = await this._workerPool.encrypt(s);
1938
+ const stored = await this._serializeAndEncrypt(s);
1939
+ const ttlSec = Math.ceil(ttlMs / 1_000);
1940
+ if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
1941
+ const now = Date.now();
1942
+ const tx = client.multi();
1943
+ tx.hset(k, {
1944
+ d: stored,
1945
+ t: String(now),
1946
+ tv: JSON.stringify(activeTagVersions),
1947
+ });
1948
+ tx.expire(k, ttlSec);
1949
+ await tx.exec();
1429
1950
  } else {
1430
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1951
+ await client.setex(k, ttlSec, stored);
1431
1952
  }
1432
- await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
1433
1953
  this.cb.onSuccess();
1434
1954
  } catch (err) {
1435
1955
  this.cb.onFailure();
@@ -1548,7 +2068,7 @@ export class CacheService {
1548
2068
  );
1549
2069
  }
1550
2070
  const now = Date.now();
1551
- const ttlMs = (ttlSeconds ?? 60) * 1_000;
2071
+ const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1_000;
1552
2072
  const entry = this._l1Counters.get(k);
1553
2073
  if (entry && entry.expiresAt > now) {
1554
2074
  entry.value++;
@@ -1596,6 +2116,7 @@ export class CacheService {
1596
2116
  if (!this._diskDisabled) this.disk.clear();
1597
2117
  this._l1Counters.clear();
1598
2118
  this.tagIndex.clear();
2119
+ this.tagVersions.clear();
1599
2120
  }
1600
2121
 
1601
2122
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -1648,9 +2169,10 @@ export class CacheService {
1648
2169
  * for (const key of cache.keys()) console.log(key);
1649
2170
  */
1650
2171
  *keys(): Generator<string> {
1651
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2172
+ const prefix = this._namespace ? this._namespace + ':' : '';
1652
2173
  for (const key of this.l1.liveKeys()) {
1653
- yield prefixLen > 0 ? key.slice(prefixLen) : key;
2174
+ if (prefix && !key.startsWith(prefix)) continue;
2175
+ yield prefix ? key.slice(prefix.length) : key;
1654
2176
  }
1655
2177
  }
1656
2178
 
@@ -1662,8 +2184,15 @@ export class CacheService {
1662
2184
  * for (const val of cache.values<User>()) console.log(val.id);
1663
2185
  */
1664
2186
  *values<T = unknown>(): Generator<T> {
1665
- // yield* delegates directly into liveValues(), collapsing one generator frame.
1666
- yield* this.l1.liveValues() as Generator<T>;
2187
+ const prefix = this._namespace ? this._namespace + ':' : '';
2188
+ if (!prefix) {
2189
+ yield* this.l1.liveValues() as Generator<T>;
2190
+ } else {
2191
+ for (const [key, entry] of this.l1.liveEntries()) {
2192
+ if (!key.startsWith(prefix)) continue;
2193
+ yield this.l1.resolveValue(entry) as T;
2194
+ }
2195
+ }
1667
2196
  }
1668
2197
 
1669
2198
  /**
@@ -1674,10 +2203,10 @@ export class CacheService {
1674
2203
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
1675
2204
  */
1676
2205
  *entries<T = unknown>(): Generator<[string, T]> {
1677
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2206
+ const prefix = this._namespace ? this._namespace + ':' : '';
1678
2207
  for (const [key, entry] of this.l1.liveEntries()) {
1679
- const k = prefixLen > 0 ? key.slice(prefixLen) : key;
1680
- yield [k, this.l1.resolveValue(entry) as T];
2208
+ if (prefix && !key.startsWith(prefix)) continue;
2209
+ yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry) as T];
1681
2210
  }
1682
2211
  }
1683
2212
 
@@ -1745,6 +2274,77 @@ export class CacheService {
1745
2274
  return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
1746
2275
  }
1747
2276
 
2277
+ /**
2278
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
2279
+ * Returns the cached value if found and valid, or `null` if absent / expired.
2280
+ * Does not write dummy entries on misses or trigger side-effects.
2281
+ *
2282
+ * @example
2283
+ * const val = await cache.peek<User>('user:123');
2284
+ */
2285
+ async peek<T = unknown>(cacheKey: string): Promise<T | null> {
2286
+ const k = this.nk(cacheKey);
2287
+
2288
+ // 1. L1 RAM
2289
+ const l1Hit = this.l1.get(k);
2290
+ if (l1Hit !== null) {
2291
+ this.counters.gets++;
2292
+ this.counters.l1Hits++;
2293
+ const val = l1Hit.value as T;
2294
+ if (this.opts.frozen) deepFreeze(val);
2295
+ return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
2296
+ ? structuredClone(val)
2297
+ : val;
2298
+ }
2299
+
2300
+ // 2. L1.5 Disk
2301
+ if (!this._diskDisabled) {
2302
+ const diskHit = this.disk.load(k);
2303
+ if (diskHit !== null) {
2304
+ const promoted = this.l1.importEntries(
2305
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2306
+ this.opts.forbiddenSnapshotPrefixes,
2307
+ );
2308
+ if (promoted > 0) {
2309
+ const l1Check = this.l1.get(k);
2310
+ if (l1Check !== null) {
2311
+ this.counters.gets++;
2312
+ this.counters.diskHits++;
2313
+ const val = l1Check.value as T;
2314
+ if (this.opts.frozen) deepFreeze(val);
2315
+ return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
2316
+ ? structuredClone(val)
2317
+ : val;
2318
+ }
2319
+ }
2320
+ }
2321
+ }
2322
+
2323
+ // 3. L2 Redis
2324
+ if (!this._redisDisabled && !this.cb.isOpen) {
2325
+ try {
2326
+ const client = await this.getRedis();
2327
+ const raw = await client.get(k);
2328
+ if (raw !== null) {
2329
+ const parsed = await this._decryptAndDeserialize<T>(raw);
2330
+ this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
2331
+ this.counters.gets++;
2332
+ this.counters.l2Hits++;
2333
+ this.cb.onSuccess();
2334
+ if (this.opts.frozen) deepFreeze(parsed);
2335
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2336
+ ? structuredClone(parsed)
2337
+ : parsed;
2338
+ }
2339
+ } catch (err) {
2340
+ this.cb.onFailure();
2341
+ this.logger.debug('peek: Redis read failed', { cacheKey, error: (err as Error).message });
2342
+ }
2343
+ }
2344
+
2345
+ return null;
2346
+ }
2347
+
1748
2348
  /**
1749
2349
  * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1750
2350
  * Preserves input ordering. Uses inflight coalescing per key.
@@ -1760,7 +2360,7 @@ export class CacheService {
1760
2360
  ttl: number | ((key: string) => number) = 300,
1761
2361
  priority?: CachePriority,
1762
2362
  ): Promise<(T | undefined)[]> {
1763
- const result: (T | undefined)[] = new Array(keys.length);
2363
+ const result: (T | undefined)[] = Array.from({ length: keys.length });
1764
2364
  const missIndexes: number[] = [];
1765
2365
  const missKeys: string[] = [];
1766
2366
 
@@ -1792,15 +2392,7 @@ export class CacheService {
1792
2392
  const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
1793
2393
  const idx = missIndexes[j];
1794
2394
  if (raw) {
1795
- let parsed: T;
1796
- if (this.enc.isEnabled) {
1797
- const decrypted = (this._workerPool && raw.length > this.opts.workerThresholdBytes)
1798
- ? await this._workerPool.decrypt(raw)
1799
- : this.enc.decrypt(raw);
1800
- parsed = JSON.parse(decrypted) as T;
1801
- } else {
1802
- parsed = JSON.parse(raw) as T;
1803
- }
2395
+ const parsed = await this._decryptAndDeserialize<T>(raw);
1804
2396
  const k = nsKeys[j];
1805
2397
  const p = priority ?? inferPriority(missKeys[j]);
1806
2398
  this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
@@ -1955,13 +2547,12 @@ export class CacheService {
1955
2547
  const [err, raw] = results[i];
1956
2548
  if (err || raw == null) continue;
1957
2549
  try {
1958
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1959
- const parsed = JSON.parse(decrypted) as unknown;
2550
+ const parsed = await this._decryptAndDeserialize<unknown>(raw);
1960
2551
  // Use a 10-minute TTL as a reasonable default; the real TTL is not
1961
2552
  // returned by GET (use PTTL to be precise, but that doubles round-trips).
1962
2553
  const remainingMs = 10 * 60 * 1_000;
1963
2554
  this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
1964
- loaded++;;
2555
+ loaded++;
1965
2556
  } catch { /* skip malformed entries */ }
1966
2557
  }
1967
2558
  void now; // suppress unused warning
@@ -1986,6 +2577,26 @@ export class CacheService {
1986
2577
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
1987
2578
  */
1988
2579
  async invalidateTag(tag: string): Promise<void> {
2580
+ if (this.opts.tagStrategy === 'generational') {
2581
+ let newVer = 1;
2582
+ if (!this._redisDisabled) {
2583
+ try {
2584
+ const client = await this.getRedis();
2585
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
2586
+ } catch (err) {
2587
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
2588
+ const current = this.tagVersions.get(tag)?.version ?? 0;
2589
+ newVer = current + 1;
2590
+ }
2591
+ } else {
2592
+ const current = this.tagVersions.get(tag)?.version ?? 0;
2593
+ newVer = current + 1;
2594
+ }
2595
+ this._setLocalTagVersion(tag, newVer, Date.now());
2596
+ void this.publishInvalidation('tag_incr', tag, newVer);
2597
+ return;
2598
+ }
2599
+
1989
2600
  const tagKey = this.nk(`_tag_:${tag}`);
1990
2601
  const members = this.tagIndex.get(tagKey) ?? new Set<string>();
1991
2602
 
@@ -2028,6 +2639,33 @@ export class CacheService {
2028
2639
  if (tags.length === 0) return;
2029
2640
  if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
2030
2641
 
2642
+ if (this.opts.tagStrategy === 'generational') {
2643
+ const now = Date.now();
2644
+ if (!this._redisDisabled) {
2645
+ try {
2646
+ const client = await this.getRedis();
2647
+ const pl = client.pipeline();
2648
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
2649
+ const results = await pl.exec() as Array<[Error | null, number]>;
2650
+ for (let i = 0; i < tags.length; i++) {
2651
+ const [err, newVer] = results[i] ?? [null, null];
2652
+ const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
2653
+ this._setLocalTagVersion(tags[i], ver, now);
2654
+ void this.publishInvalidation('tag_incr', tags[i], ver);
2655
+ }
2656
+ return;
2657
+ } catch (err) {
2658
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
2659
+ }
2660
+ }
2661
+ for (const tag of tags) {
2662
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
2663
+ this._setLocalTagVersion(tag, ver, now);
2664
+ void this.publishInvalidation('tag_incr', tag, ver);
2665
+ }
2666
+ return;
2667
+ }
2668
+
2031
2669
  // In-process: collect all member keys across all tags and remove from L1 + disk
2032
2670
  const tagKeys: string[] = [];
2033
2671
  const allMembers = new Set<string>();
@@ -2067,6 +2705,13 @@ export class CacheService {
2067
2705
  }
2068
2706
  }
2069
2707
 
2708
+ /**
2709
+ * Get the current generational tag version for a tag (synced with Redis when due).
2710
+ */
2711
+ async getTagVersion(tag: string): Promise<number> {
2712
+ return this._getTagVersion(tag);
2713
+ }
2714
+
2070
2715
  /**
2071
2716
  * Measure L1 / disk / Redis latency.
2072
2717
  * Useful for health checks and dashboards.
@@ -2182,6 +2827,148 @@ export class CacheService {
2182
2827
  return true;
2183
2828
  }
2184
2829
 
2830
+ // ── Distributed / In-Process Mutex Lock ───────────────────────────────────
2831
+
2832
+ /**
2833
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
2834
+ * execute `fn`, and automatically release the lock on completion or error.
2835
+ *
2836
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
2837
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
2838
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
2839
+ *
2840
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
2841
+ * @param fn Task to run exclusively while holding the lock.
2842
+ * @param options TTL, acquire timeout, and retry polling intervals.
2843
+ */
2844
+ async lock<T>(
2845
+ resourceKey: string,
2846
+ fn: () => Promise<T>,
2847
+ options?: LockOptions,
2848
+ ): Promise<T> {
2849
+ const ttlSeconds = Math.max(1, options?.ttl ?? 30);
2850
+ const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5_000);
2851
+ const retryInterval = Math.max(10, options?.retryInterval ?? 100);
2852
+
2853
+ const lockKey = this.nk(`lock:${resourceKey}`);
2854
+ const token = crypto.randomUUID();
2855
+ const deadline = Date.now() + acquireTimeout;
2856
+
2857
+ let acquired = false;
2858
+
2859
+ if (!this._redisDisabled) {
2860
+ try {
2861
+ const client = await this.getRedis();
2862
+ while (Date.now() <= deadline) {
2863
+ const res = await client.set(lockKey, token, 'EX', ttlSeconds, 'NX');
2864
+ if (res === 'OK') {
2865
+ acquired = true;
2866
+ break;
2867
+ }
2868
+ const remaining = deadline - Date.now();
2869
+ if (remaining <= 0) break;
2870
+ await new Promise(r => setTimeout(r, Math.min(retryInterval, remaining)));
2871
+ }
2872
+
2873
+ if (!acquired) {
2874
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
2875
+ }
2876
+
2877
+ try {
2878
+ return await fn();
2879
+ } finally {
2880
+ try {
2881
+ const LUA_RELEASE_LOCK = `
2882
+ if redis.call("get", KEYS[1]) == ARGV[1] then
2883
+ return redis.call("del", KEYS[1])
2884
+ else
2885
+ return 0
2886
+ end
2887
+ `;
2888
+ await client.eval(LUA_RELEASE_LOCK, 1, lockKey, token);
2889
+ } catch { /* ok */ }
2890
+ }
2891
+ } catch (err) {
2892
+ if ((err as Error).message.startsWith('Failed to acquire lock')) throw err;
2893
+ this.logger.debug('Distributed lock: Redis error, falling back to in-process mutex', {
2894
+ resourceKey, error: (err as Error).message,
2895
+ });
2896
+ }
2897
+ }
2898
+
2899
+ // In-process lock fallback
2900
+ let unlock: () => void = () => {};
2901
+ const lockPromise = new Promise<void>(resolve => { unlock = resolve; });
2902
+
2903
+ while (Date.now() <= deadline) {
2904
+ const existing = this._localLocks.get(lockKey);
2905
+ if (!existing) {
2906
+ this._localLocks.set(lockKey, lockPromise);
2907
+ acquired = true;
2908
+ break;
2909
+ }
2910
+ const remaining = deadline - Date.now();
2911
+ if (remaining <= 0) break;
2912
+ await Promise.race([
2913
+ existing,
2914
+ new Promise(r => setTimeout(r, Math.min(retryInterval, remaining))),
2915
+ ]);
2916
+ }
2917
+
2918
+ if (!acquired) {
2919
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
2920
+ }
2921
+
2922
+ try {
2923
+ return await fn();
2924
+ } finally {
2925
+ unlock();
2926
+ if (this._localLocks.get(lockKey) === lockPromise) {
2927
+ this._localLocks.delete(lockKey);
2928
+ }
2929
+ }
2930
+ }
2931
+
2932
+ // ── OpenTelemetry Metrics Integration ──────────────────────────────────────
2933
+
2934
+ private _initOtelMetrics(meter: ICacheMeter): void {
2935
+ try {
2936
+ this._otelMetrics.gets = meter.createCounter('tricache.gets.total', { description: 'Total cache get operations' });
2937
+ this._otelMetrics.l1Hits = meter.createCounter('tricache.l1.hits', { description: 'L1 RAM cache hits' });
2938
+ this._otelMetrics.l2Hits = meter.createCounter('tricache.l2.hits', { description: 'L2 Redis cache hits' });
2939
+ this._otelMetrics.diskHits = meter.createCounter('tricache.disk.hits', { description: 'L1.5 disk cache hits' });
2940
+ this._otelMetrics.fetches = meter.createCounter('tricache.fetches', { description: 'Cache miss fetch calls' });
2941
+ this._otelMetrics.stampedes = meter.createCounter('tricache.stampedes.prevented', { description: 'Coalesced duplicate inflight requests' });
2942
+ this._otelMetrics.sets = meter.createCounter('tricache.sets.total', { description: 'Total set operations' });
2943
+ this._otelMetrics.deletes = meter.createCounter('tricache.deletes.total', { description: 'Total delete operations' });
2944
+ this._otelMetrics.swrRevalidations = meter.createCounter('tricache.swr.revalidations', { description: 'SWR background revalidations' });
2945
+
2946
+ const gL1Entries = meter.createObservableGauge('tricache.l1.entries', { description: 'Current L1 entry count' });
2947
+ const gL1Bytes = meter.createObservableGauge('tricache.l1.bytes', { description: 'Current L1 memory usage in bytes' });
2948
+ const gDiskFiles = meter.createObservableGauge('tricache.disk.files', { description: 'Current L1.5 disk file count' });
2949
+ const gDiskBytes = meter.createObservableGauge('tricache.disk.bytes', { description: 'Current L1.5 disk size in bytes' });
2950
+ const gBloomFpr = meter.createObservableGauge('tricache.bloom.fpr', { description: 'Bloom filter false-positive rate' });
2951
+
2952
+ meter.addBatchObservableCallback((observableResult) => {
2953
+ const stats = this.stats();
2954
+ const l1 = stats.l1;
2955
+ const disk = stats.disk;
2956
+ const checks = this.counters.bloomChecks;
2957
+ const fps = this.counters.bloomFalsePositives;
2958
+ const fpr = checks > 0 ? fps / checks : 0;
2959
+ const attrs = this._namespace ? { namespace: this._namespace } : undefined;
2960
+
2961
+ observableResult.observe(gL1Entries, l1.entries, attrs);
2962
+ observableResult.observe(gL1Bytes, l1.sizeBytes, attrs);
2963
+ observableResult.observe(gDiskFiles, disk.files, attrs);
2964
+ observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
2965
+ observableResult.observe(gBloomFpr, fpr, attrs);
2966
+ }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
2967
+ } catch (err) {
2968
+ this.logger.warn('Failed to initialize OpenTelemetry metrics meter', { error: (err as Error).message });
2969
+ }
2970
+ }
2971
+
2185
2972
  // ── Hot key introspection ─────────────────────────────────────────────
2186
2973
 
2187
2974
  /**
@@ -2215,25 +3002,29 @@ export class CacheService {
2215
3002
  */
2216
3003
  private _matchesGlob(key: string, pattern: string): boolean {
2217
3004
  if (!pattern.includes('*')) return key === pattern;
2218
- const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
2219
- return re.test(key);
3005
+ return getGlobRegex(pattern).test(key);
2220
3006
  }
2221
3007
 
2222
3008
  /**
2223
3009
  * When an exact key `deletedKey` is removed, cascade to every dependent key
2224
3010
  * that was registered via `dependsOn` and whose source pattern matches.
3011
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
2225
3012
  */
2226
- private _cascadeDependencies(deletedKey: string): void {
3013
+ private _cascadeDependencies(deletedKey: string, visited: Set<string> = new Set()): void {
3014
+ if (visited.has(deletedKey)) return;
3015
+ visited.add(deletedKey);
3016
+
2227
3017
  for (const [pattern, dependents] of this.dependencyIndex) {
2228
3018
  if (!this._matchesGlob(deletedKey, pattern)) continue;
2229
3019
  for (const dep of dependents) {
2230
- if (dep === deletedKey) continue; // no self-cascade
3020
+ if (visited.has(dep)) continue;
2231
3021
  this.l1.delete(dep);
2232
3022
  if (!this._diskDisabled) this.disk.delete(dep);
2233
3023
  void this.publishInvalidation('del', dep);
2234
3024
  this.logger.debug('Dependency cascade: invalidated dependent key', {
2235
3025
  trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
2236
3026
  });
3027
+ this._cascadeDependencies(dep, visited);
2237
3028
  }
2238
3029
  }
2239
3030
  }
@@ -2286,9 +3077,13 @@ export class CacheService {
2286
3077
 
2287
3078
  backplane: {
2288
3079
  enabled: this.opts.invalidationBackplane && !this._redisDisabled,
3080
+ mode: this.opts.backplaneMode,
2289
3081
  sent: c.invSent,
2290
3082
  received: c.invReceived,
2291
3083
  skipped: c.invSkipped,
3084
+ streamEntriesReceived: c.streamEntriesReceived,
3085
+ streamReplays: c.streamReplays,
3086
+ streamGaps: c.streamGaps,
2292
3087
  },
2293
3088
 
2294
3089
  l2CircuitBreaker: {
@@ -2385,8 +3180,22 @@ export class CacheService {
2385
3180
 
2386
3181
  // ── Lifecycle ────────────────────────────────────────────────────────────
2387
3182
 
3183
+ /**
3184
+ * Dynamically rotate the active encryption key at runtime without restarting.
3185
+ * Installs the new key as primary for all subsequent writes, while preserving
3186
+ * the previous key for seamless fallback decryption of existing cache entries.
3187
+ */
3188
+ async rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void> {
3189
+ this.enc.rotateKey(newKeyBase64, newMode);
3190
+ if (this._workerPool) {
3191
+ await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
3192
+ }
3193
+ this.logger.info('tricache: encryption key rotated dynamically', { mode: this.enc.mode });
3194
+ }
3195
+
2388
3196
  /** Close Redis connections and stop all background timers. */
2389
3197
  async destroy(): Promise<void> {
3198
+ this._destroyed = true;
2390
3199
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
2391
3200
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2392
3201
  if (this.oomInterval) clearInterval(this.oomInterval);
@@ -2401,9 +3210,13 @@ export class CacheService {
2401
3210
  this._workerPool = null;
2402
3211
  }
2403
3212
  if (this.subClient) {
2404
- try { await this.subClient.quit(); } catch { /* ok */ }
3213
+ try { this.subClient.disconnect(); } catch { /* ok */ }
2405
3214
  this.subClient = null;
2406
3215
  }
3216
+ if (this.streamClient) {
3217
+ try { this.streamClient.disconnect(); } catch { /* ok */ }
3218
+ this.streamClient = null;
3219
+ }
2407
3220
  if (this.redis) {
2408
3221
  try { await this.redis.disconnect(); } catch { /* ok */ }
2409
3222
  this.redis = null;