tricache 0.6.7 → 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 +480 -22
  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 +1173 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3705
  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 +69 -21
  33. package/src/cache-service.ts +987 -190
  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 ─────────────────────────────────────────────────────
@@ -793,22 +910,18 @@ export class CacheService {
793
910
  return CacheService._nullSpan;
794
911
  }
795
912
 
796
- private initBackplane(): void {
797
- if (!this.opts.invalidationBackplane || this._redisDisabled) return;
798
- if (this.subClient) return;
799
-
800
- // ── Fix 4: Cluster/Sentinel subscriber ─────────────────────────────────
801
- let sub: AnyRedisClient;
913
+ private createDedicatedRedisClient(): AnyRedisClient {
802
914
  if (this.opts.redisClusterNodes?.length) {
803
- sub = new RedisCluster(this.opts.redisClusterNodes, {
915
+ return new RedisCluster(this.opts.redisClusterNodes, {
804
916
  redisOptions: {
805
917
  tls: this.opts.redisTls ? {} : undefined,
806
918
  connectTimeout: 10_000,
807
919
  maxRetriesPerRequest: null as unknown as number,
920
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
808
921
  },
809
922
  });
810
923
  } else if (this.opts.redisSentinel) {
811
- sub = new RedisClient({
924
+ return new RedisClient({
812
925
  sentinels: this.opts.redisSentinel.sentinels,
813
926
  name: this.opts.redisSentinel.name,
814
927
  tls: this.opts.redisTls ? {} : undefined,
@@ -817,9 +930,10 @@ export class CacheService {
817
930
  maxRetriesPerRequest: null as unknown as number,
818
931
  enableAutoPipelining: false,
819
932
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
933
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
820
934
  });
821
935
  } else {
822
- sub = new RedisClient({
936
+ return new RedisClient({
823
937
  host: this.opts.redisHost,
824
938
  port: this.opts.redisPort,
825
939
  tls: this.opts.redisTls ? {} : undefined,
@@ -829,13 +943,30 @@ export class CacheService {
829
943
  enableAutoPipelining: false,
830
944
  family: 4,
831
945
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
946
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
832
947
  });
833
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
+ }
959
+
960
+ if (this.subClient) return;
834
961
 
835
- sub.on('error', (e: Error) =>
836
- this.logger.debug('Backplane subscriber error', { error: e.message }));
962
+ const sub = this.createDedicatedRedisClient();
837
963
 
838
- // ── Fix 2: Staleness fence — track disconnect time ──────────────────────
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 ──────────────────────
839
970
  sub.on('close', () => {
840
971
  if (this._subDisconnectedAt === null) {
841
972
  this._subDisconnectedAt = Date.now();
@@ -847,9 +978,6 @@ export class CacheService {
847
978
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
848
979
  const gapMs = Date.now() - this._subDisconnectedAt;
849
980
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
850
- // We were disconnected long enough that peer invalidations were
851
- // almost certainly missed. Evict every L1 entry written before
852
- // the disconnect started so stale data cannot be served.
853
981
  const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
854
982
  this.logger.warn('Backplane: reconnect after gap — flushed potentially stale L1 entries', {
855
983
  gapMs, evicted,
@@ -860,21 +988,140 @@ export class CacheService {
860
988
  }
861
989
  });
862
990
 
863
- sub.on('message', (_channel: string, message: string) => {
864
- this._handleBackplaneMessage(message);
865
- });
991
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
866
992
 
867
- sub.subscribe(this.backplaneChannel)
868
- .then(() => this.logger.info('Backplane: subscribed', {
869
- channel: this.backplaneChannel, instanceId: this.instanceId,
870
- }))
871
- .catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
872
- error: err.message,
873
- }));
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
+ }
874
1017
 
875
1018
  this.subClient = sub;
876
1019
  }
877
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
+
878
1125
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
879
1126
  _handleBackplaneMessage(message: string): void {
880
1127
  try {
@@ -885,7 +1132,7 @@ export class CacheService {
885
1132
  Array.isArray(msg) ||
886
1133
  typeof msg.src !== 'string' ||
887
1134
  typeof msg.key !== 'string' ||
888
- (msg.op !== 'del' && msg.op !== 'del-glob')
1135
+ (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr')
889
1136
  ) {
890
1137
  this.logger.warn('Backplane: rejected invalid pubsub message format', {
891
1138
  raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
@@ -897,42 +1144,136 @@ export class CacheService {
897
1144
  return; // own message — our L1 is already current
898
1145
  }
899
1146
  this.counters.invReceived++;
900
- if (msg.op === 'del') {
901
- // L1 eviction is synchronous and O(1); disk delete is deferred via
902
- // setImmediate so the event-loop tick that processes this pub/sub
903
- // message returns immediately without blocking hot get() calls.
904
- this.l1.delete(msg.key);
905
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(msg.key); });
906
- // Cascade: evict dependents registered on this instance for the
907
- // deleted key — same logic the local delete() path runs, now also
908
- // applied to peer-originated invalidations so fleet-wide deletes
909
- // propagate dependency cascades to every node.
910
- this._cascadeDependencies(msg.key);
911
- } else if (msg.op === 'del-glob') {
912
- // Glob patterns clean L1 only — disk entries expire naturally via
913
- // the background purge timer or are bypassed on the next L1 miss.
914
- this.l1.deletePattern(msg.key);
915
- }
916
- this.logger.debug('Backplane: peer invalidation applied', {
917
- op: msg.op, key: msg.key.slice(0, 60),
918
- });
1147
+ this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === 'number' ? msg.tagVersion : undefined);
919
1148
  } catch {
920
1149
  this.logger.warn('Backplane: malformed message JSON parse failed');
921
1150
  }
922
1151
  }
923
1152
 
924
- 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> {
925
1154
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
926
1155
  try {
927
1156
  const client = await this.getRedis();
928
- await client.publish(
929
- this.backplaneChannel,
930
- JSON.stringify({ op, key, src: this.instanceId }),
931
- );
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
+ }
932
1188
  this.counters.invSent++;
933
1189
  } catch { /* non-critical — never block the caller */ }
934
1190
  }
935
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
+
936
1277
  /**
937
1278
  * Scan all keys matching `pattern` across single-node or Cluster clients.
938
1279
  * For Cluster, iterates every master node independently (SCAN is node-local).
@@ -960,8 +1301,26 @@ export class CacheService {
960
1301
  return keys;
961
1302
  }
962
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
+
963
1321
  private async getRedis(): Promise<AnyRedisClient> {
964
1322
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
1323
+ if (this.redis) return this.redis;
965
1324
  if (this.redisConnecting) return this.redisConnecting;
966
1325
 
967
1326
  this.redisConnecting = (async () => {
@@ -977,13 +1336,17 @@ export class CacheService {
977
1336
  connectTimeout: 10_000,
978
1337
  maxRetriesPerRequest: 3,
979
1338
  keepAlive: 30_000,
1339
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
980
1340
  },
981
1341
  enableAutoPipelining: true,
982
1342
  retryDelayOnClusterDown: 200,
983
1343
  retryDelayOnFailover: 1_000,
984
1344
  });
985
1345
  client.on('connect', () => this.logger.info('Redis Cluster connected'));
986
- 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
+ });
987
1350
  client.on('reconnecting', () => this.logger.debug('Redis Cluster reconnecting'));
988
1351
  } else if (this.opts.redisSentinel) {
989
1352
  // Redis Sentinel — ioredis monitors master via sentinel topology.
@@ -997,9 +1360,13 @@ export class CacheService {
997
1360
  enableAutoPipelining: true,
998
1361
  keepAlive: 30_000,
999
1362
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
1363
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
1000
1364
  });
1001
1365
  client.on('connect', () => this.logger.info('Redis Sentinel connected', { name: this.opts.redisSentinel!.name }));
1002
- 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
+ });
1003
1370
  client.on('reconnecting', () => this.logger.debug('Redis Sentinel reconnecting'));
1004
1371
  } else {
1005
1372
  // Single-node (original path)
@@ -1014,15 +1381,22 @@ export class CacheService {
1014
1381
  keepAlive: 30_000,
1015
1382
  family: 4,
1016
1383
  retryStrategy: (times: number) => Math.min(times * 50, 2_000),
1384
+ ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
1017
1385
  });
1018
1386
  client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
1019
- 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
+ });
1020
1391
  client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
1021
1392
  }
1022
1393
 
1023
1394
  await new Promise<void>((resolve, reject) => {
1024
1395
  client.once('ready', resolve);
1025
- client.once('error', reject);
1396
+ client.once('error', (e: Error) => {
1397
+ this._checkAndLogResp3Hint(e);
1398
+ reject(e);
1399
+ });
1026
1400
  setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
1027
1401
  });
1028
1402
 
@@ -1033,6 +1407,7 @@ export class CacheService {
1033
1407
  } catch (err) {
1034
1408
  this.cb.onFailure();
1035
1409
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
1410
+ this._checkAndLogResp3Hint(err as Error);
1036
1411
  throw err;
1037
1412
  }
1038
1413
  })();
@@ -1051,7 +1426,7 @@ export class CacheService {
1051
1426
  const packed = pack(payload);
1052
1427
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1053
1428
  const dest = altPath ?? this.opts.snapshotPath;
1054
-
1429
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1055
1430
  fs.writeFileSync(dest, final, { mode: 0o600 });
1056
1431
  this.logger.info('Cache snapshot written', {
1057
1432
  path: dest, entries: entries.length,
@@ -1175,60 +1550,67 @@ export class CacheService {
1175
1550
  // L1: in-memory (fastest path)
1176
1551
  const l1Hit = this.l1.get(k);
1177
1552
  if (l1Hit !== null) {
1178
- if (l1Hit.isStale) {
1179
- const swrGraceMs = optSwr * 1_000;
1180
- if (swrGraceMs > 0 && !this.revalidating.has(k)) {
1181
- const priority = optPriority ?? inferPriority(cacheKey);
1182
- this.revalidating.add(k);
1183
- void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
1184
- this.counters.swrRevalidations++;
1185
- this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
1186
- } else {
1187
- 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
+ }
1188
1561
  }
1562
+ }
1563
+
1564
+ if (isGenerationalStale) {
1565
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
1189
1566
  } else {
1190
- this.logger.debug('L1 hit');
1191
- // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
1192
- // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
1193
- // Check opts first — pointless work when neither feature is configured.
1194
- // Local aliases for the opts fields already normalised at function entry.
1195
- const ra = optRefreshAhead;
1196
- const xb = optXfetchBeta;
1197
- if (ra || xb) {
1198
- // Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
1199
- const now = l1Hit.fetchedAt ?? Date.now();
1200
- const remaining = l1Hit.expiresAt - now;
1201
- const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
1202
-
1203
- const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
1204
-
1205
- // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
1206
- // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
1207
- const shouldXFetch = xb && l1Hit.delta != null
1208
- ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
1209
- : false;
1210
-
1211
- // Set.has() deferred to here — the common case (fresh key, threshold not crossed)
1212
- // never pays the ~30 ns lookup cost.
1213
- if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
1214
- // Defer inferPriority until we actually need it — avoids 3× string.includes()
1215
- // 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)) {
1216
1570
  const priority = optPriority ?? inferPriority(cacheKey);
1217
1571
  this.revalidating.add(k);
1218
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
1572
+ void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
1219
1573
  this.counters.swrRevalidations++;
1220
- this.logger.debug(
1221
- shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
1222
- { cacheKey, remainingMs: remaining, ttlMs: entryTtl },
1223
- );
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
+ }
1224
1604
  }
1225
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;
1226
1613
  }
1227
- this.counters.l1Hits++;
1228
- this.opts.onHit?.(cacheKey, 'l1');
1229
- if (this.opts.frozen) deepFreeze(l1Hit.value);
1230
- span.setAttribute('cache.hit', 'l1').end();
1231
- return l1Hit.value as T;
1232
1614
  }
1233
1615
 
1234
1616
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
@@ -1239,23 +1621,53 @@ export class CacheService {
1239
1621
  if (!this._redisDisabled) {
1240
1622
  try {
1241
1623
  const client = await this.getRedis();
1242
- const raw = await client.get(k);
1243
- this.cb.onSuccess();
1244
- if (raw) {
1245
- // ── Fix 1: offload decryption to worker thread for large payloads ──
1246
- let decrypted: string;
1247
- if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
1248
- decrypted = await this._workerPool.decrypt(raw);
1249
- } else {
1250
- 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;
1251
1670
  }
1252
- const parsed = JSON.parse(decrypted) as T;
1253
- this.l1.set(k, parsed, ttlMs, priority);
1254
- this.counters.l2Hits++;
1255
- this.opts.onHit?.(cacheKey, 'l2');
1256
- this.logger.debug('L2 hit (Redis)', { cacheKey });
1257
- span.setAttribute('cache.hit', 'l2').end();
1258
- return parsed;
1259
1671
  }
1260
1672
  } catch (err) {
1261
1673
  this.cb.onFailure();
@@ -1267,18 +1679,36 @@ export class CacheService {
1267
1679
  if (!this._diskDisabled) {
1268
1680
  const diskHit = this.disk.load(k);
1269
1681
  if (diskHit !== null) {
1270
- const promoted = this.l1.importEntries(
1271
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
1272
- this.opts.forbiddenSnapshotPrefixes,
1273
- );
1274
- if (promoted > 0) {
1275
- const l1Check = this.l1.get(k);
1276
- if (l1Check !== null) {
1277
- this.counters.diskHits++;
1278
- this.opts.onHit?.(cacheKey, 'disk');
1279
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
1280
- span.setAttribute('cache.hit', 'disk').end();
1281
- 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
+ }
1282
1712
  }
1283
1713
  }
1284
1714
  }
@@ -1307,9 +1737,6 @@ export class CacheService {
1307
1737
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
1308
1738
  let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
1309
1739
 
1310
- // Adaptive TTL: record this fetch duration and override the caller-supplied
1311
- // TTL once ≥ 5 samples are available for the key.
1312
- // Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
1313
1740
  if (this.latencyTracker && data != null) {
1314
1741
  this.latencyTracker.record(k, delta);
1315
1742
  const p95 = this.latencyTracker.p95(k);
@@ -1325,21 +1752,39 @@ export class CacheService {
1325
1752
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
1326
1753
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1327
1754
 
1328
- this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1329
- 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);
1330
1768
 
1331
1769
  if (!this._redisDisabled) {
1332
1770
  try {
1333
1771
  const client = await this.getRedis();
1334
1772
  const serialized = JSON.stringify(data);
1335
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1336
- let toStore: string;
1337
- if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
1338
- 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();
1339
1785
  } else {
1340
- toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1786
+ await client.setex(k, ttlSec, toStore);
1341
1787
  }
1342
- await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
1343
1788
  this.cb.onSuccess();
1344
1789
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1345
1790
  } catch {
@@ -1350,7 +1795,10 @@ export class CacheService {
1350
1795
  this.logger.debug('Cached L1', { cacheKey });
1351
1796
  }
1352
1797
 
1353
- 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;
1354
1802
  } finally {
1355
1803
  this.inflight.delete(k);
1356
1804
  span.end();
@@ -1361,6 +1809,28 @@ export class CacheService {
1361
1809
  return fetchPromise;
1362
1810
  }
1363
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
+
1364
1834
  private async _revalidate<T>(
1365
1835
  cacheKey: string,
1366
1836
  fetchFn: () => Promise<T>,
@@ -1377,20 +1847,36 @@ export class CacheService {
1377
1847
  // Keep the latency tracker current during SWR background revalidations too
1378
1848
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
1379
1849
 
1380
- 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);
1381
1860
 
1382
1861
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
1383
1862
  try {
1384
1863
  const client = await this.getRedis();
1385
1864
  const s = JSON.stringify(data);
1386
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1387
- let stored: string;
1388
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
1389
- 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();
1390
1877
  } else {
1391
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1878
+ await client.setex(cacheKey, ttlSec, stored);
1392
1879
  }
1393
- await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
1394
1880
  } catch { /* ok */ }
1395
1881
  }
1396
1882
  this.logger.debug('SWR: revalidation complete', { cacheKey });
@@ -1419,9 +1905,20 @@ export class CacheService {
1419
1905
  const p = priority ?? inferPriority(cacheKey);
1420
1906
  const k = this.nk(cacheKey);
1421
1907
  this.counters.sets++;
1422
- this.l1.set(k, data, ttlMs, p);
1423
1908
 
1424
- 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);
1425
1922
 
1426
1923
  // Register dependency patterns: when any key matching a pattern is deleted,
1427
1924
  // this key (k) is automatically cascaded.
@@ -1438,14 +1935,21 @@ export class CacheService {
1438
1935
  try {
1439
1936
  const client = await this.getRedis();
1440
1937
  const s = JSON.stringify(data);
1441
- // ── Fix 1: offload encryption to worker thread for large payloads ──
1442
- let stored: string;
1443
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
1444
- 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();
1445
1950
  } else {
1446
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1951
+ await client.setex(k, ttlSec, stored);
1447
1952
  }
1448
- await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
1449
1953
  this.cb.onSuccess();
1450
1954
  } catch (err) {
1451
1955
  this.cb.onFailure();
@@ -1564,7 +2068,7 @@ export class CacheService {
1564
2068
  );
1565
2069
  }
1566
2070
  const now = Date.now();
1567
- const ttlMs = (ttlSeconds ?? 60) * 1_000;
2071
+ const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1_000;
1568
2072
  const entry = this._l1Counters.get(k);
1569
2073
  if (entry && entry.expiresAt > now) {
1570
2074
  entry.value++;
@@ -1612,6 +2116,7 @@ export class CacheService {
1612
2116
  if (!this._diskDisabled) this.disk.clear();
1613
2117
  this._l1Counters.clear();
1614
2118
  this.tagIndex.clear();
2119
+ this.tagVersions.clear();
1615
2120
  }
1616
2121
 
1617
2122
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -1664,9 +2169,10 @@ export class CacheService {
1664
2169
  * for (const key of cache.keys()) console.log(key);
1665
2170
  */
1666
2171
  *keys(): Generator<string> {
1667
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2172
+ const prefix = this._namespace ? this._namespace + ':' : '';
1668
2173
  for (const key of this.l1.liveKeys()) {
1669
- yield prefixLen > 0 ? key.slice(prefixLen) : key;
2174
+ if (prefix && !key.startsWith(prefix)) continue;
2175
+ yield prefix ? key.slice(prefix.length) : key;
1670
2176
  }
1671
2177
  }
1672
2178
 
@@ -1678,8 +2184,15 @@ export class CacheService {
1678
2184
  * for (const val of cache.values<User>()) console.log(val.id);
1679
2185
  */
1680
2186
  *values<T = unknown>(): Generator<T> {
1681
- // yield* delegates directly into liveValues(), collapsing one generator frame.
1682
- 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
+ }
1683
2196
  }
1684
2197
 
1685
2198
  /**
@@ -1690,10 +2203,10 @@ export class CacheService {
1690
2203
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
1691
2204
  */
1692
2205
  *entries<T = unknown>(): Generator<[string, T]> {
1693
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2206
+ const prefix = this._namespace ? this._namespace + ':' : '';
1694
2207
  for (const [key, entry] of this.l1.liveEntries()) {
1695
- const k = prefixLen > 0 ? key.slice(prefixLen) : key;
1696
- 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];
1697
2210
  }
1698
2211
  }
1699
2212
 
@@ -1761,6 +2274,77 @@ export class CacheService {
1761
2274
  return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
1762
2275
  }
1763
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
+
1764
2348
  /**
1765
2349
  * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1766
2350
  * Preserves input ordering. Uses inflight coalescing per key.
@@ -1776,7 +2360,7 @@ export class CacheService {
1776
2360
  ttl: number | ((key: string) => number) = 300,
1777
2361
  priority?: CachePriority,
1778
2362
  ): Promise<(T | undefined)[]> {
1779
- const result: (T | undefined)[] = new Array(keys.length);
2363
+ const result: (T | undefined)[] = Array.from({ length: keys.length });
1780
2364
  const missIndexes: number[] = [];
1781
2365
  const missKeys: string[] = [];
1782
2366
 
@@ -1808,15 +2392,7 @@ export class CacheService {
1808
2392
  const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
1809
2393
  const idx = missIndexes[j];
1810
2394
  if (raw) {
1811
- let parsed: T;
1812
- if (this.enc.isEnabled) {
1813
- const decrypted = (this._workerPool && raw.length > this.opts.workerThresholdBytes)
1814
- ? await this._workerPool.decrypt(raw)
1815
- : this.enc.decrypt(raw);
1816
- parsed = JSON.parse(decrypted) as T;
1817
- } else {
1818
- parsed = JSON.parse(raw) as T;
1819
- }
2395
+ const parsed = await this._decryptAndDeserialize<T>(raw);
1820
2396
  const k = nsKeys[j];
1821
2397
  const p = priority ?? inferPriority(missKeys[j]);
1822
2398
  this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
@@ -1971,13 +2547,12 @@ export class CacheService {
1971
2547
  const [err, raw] = results[i];
1972
2548
  if (err || raw == null) continue;
1973
2549
  try {
1974
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1975
- const parsed = JSON.parse(decrypted) as unknown;
2550
+ const parsed = await this._decryptAndDeserialize<unknown>(raw);
1976
2551
  // Use a 10-minute TTL as a reasonable default; the real TTL is not
1977
2552
  // returned by GET (use PTTL to be precise, but that doubles round-trips).
1978
2553
  const remainingMs = 10 * 60 * 1_000;
1979
2554
  this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
1980
- loaded++;;
2555
+ loaded++;
1981
2556
  } catch { /* skip malformed entries */ }
1982
2557
  }
1983
2558
  void now; // suppress unused warning
@@ -2002,6 +2577,26 @@ export class CacheService {
2002
2577
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
2003
2578
  */
2004
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
+
2005
2600
  const tagKey = this.nk(`_tag_:${tag}`);
2006
2601
  const members = this.tagIndex.get(tagKey) ?? new Set<string>();
2007
2602
 
@@ -2044,6 +2639,33 @@ export class CacheService {
2044
2639
  if (tags.length === 0) return;
2045
2640
  if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
2046
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
+
2047
2669
  // In-process: collect all member keys across all tags and remove from L1 + disk
2048
2670
  const tagKeys: string[] = [];
2049
2671
  const allMembers = new Set<string>();
@@ -2083,6 +2705,13 @@ export class CacheService {
2083
2705
  }
2084
2706
  }
2085
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
+
2086
2715
  /**
2087
2716
  * Measure L1 / disk / Redis latency.
2088
2717
  * Useful for health checks and dashboards.
@@ -2198,6 +2827,148 @@ export class CacheService {
2198
2827
  return true;
2199
2828
  }
2200
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
+
2201
2972
  // ── Hot key introspection ─────────────────────────────────────────────
2202
2973
 
2203
2974
  /**
@@ -2231,25 +3002,29 @@ export class CacheService {
2231
3002
  */
2232
3003
  private _matchesGlob(key: string, pattern: string): boolean {
2233
3004
  if (!pattern.includes('*')) return key === pattern;
2234
- const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
2235
- return re.test(key);
3005
+ return getGlobRegex(pattern).test(key);
2236
3006
  }
2237
3007
 
2238
3008
  /**
2239
3009
  * When an exact key `deletedKey` is removed, cascade to every dependent key
2240
3010
  * that was registered via `dependsOn` and whose source pattern matches.
3011
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
2241
3012
  */
2242
- 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
+
2243
3017
  for (const [pattern, dependents] of this.dependencyIndex) {
2244
3018
  if (!this._matchesGlob(deletedKey, pattern)) continue;
2245
3019
  for (const dep of dependents) {
2246
- if (dep === deletedKey) continue; // no self-cascade
3020
+ if (visited.has(dep)) continue;
2247
3021
  this.l1.delete(dep);
2248
3022
  if (!this._diskDisabled) this.disk.delete(dep);
2249
3023
  void this.publishInvalidation('del', dep);
2250
3024
  this.logger.debug('Dependency cascade: invalidated dependent key', {
2251
3025
  trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
2252
3026
  });
3027
+ this._cascadeDependencies(dep, visited);
2253
3028
  }
2254
3029
  }
2255
3030
  }
@@ -2302,9 +3077,13 @@ export class CacheService {
2302
3077
 
2303
3078
  backplane: {
2304
3079
  enabled: this.opts.invalidationBackplane && !this._redisDisabled,
3080
+ mode: this.opts.backplaneMode,
2305
3081
  sent: c.invSent,
2306
3082
  received: c.invReceived,
2307
3083
  skipped: c.invSkipped,
3084
+ streamEntriesReceived: c.streamEntriesReceived,
3085
+ streamReplays: c.streamReplays,
3086
+ streamGaps: c.streamGaps,
2308
3087
  },
2309
3088
 
2310
3089
  l2CircuitBreaker: {
@@ -2401,8 +3180,22 @@ export class CacheService {
2401
3180
 
2402
3181
  // ── Lifecycle ────────────────────────────────────────────────────────────
2403
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
+
2404
3196
  /** Close Redis connections and stop all background timers. */
2405
3197
  async destroy(): Promise<void> {
3198
+ this._destroyed = true;
2406
3199
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
2407
3200
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2408
3201
  if (this.oomInterval) clearInterval(this.oomInterval);
@@ -2417,9 +3210,13 @@ export class CacheService {
2417
3210
  this._workerPool = null;
2418
3211
  }
2419
3212
  if (this.subClient) {
2420
- try { await this.subClient.quit(); } catch { /* ok */ }
3213
+ try { this.subClient.disconnect(); } catch { /* ok */ }
2421
3214
  this.subClient = null;
2422
3215
  }
3216
+ if (this.streamClient) {
3217
+ try { this.streamClient.disconnect(); } catch { /* ok */ }
3218
+ this.streamClient = null;
3219
+ }
2423
3220
  if (this.redis) {
2424
3221
  try { await this.redis.disconnect(); } catch { /* ok */ }
2425
3222
  this.redis = null;