tricache 1.0.2 → 2.0.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 (101) hide show
  1. package/README.md +78 -90
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/{cache-service-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -1,4 +1,4 @@
1
- import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-BA4pz1A0.cjs';
1
+ import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-F8vRWMrE.cjs';
2
2
 
3
3
  /**
4
4
  * TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
@@ -218,6 +218,14 @@ declare class ProcessTerminationBus {
218
218
  }
219
219
  declare function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOptions>): CacheOptions;
220
220
  declare class CacheService {
221
+ private readonly _originWork;
222
+ private readonly _backgroundWork;
223
+ private readonly _originCapacityLimiter;
224
+ private readonly _dependencyBudget;
225
+ private readonly _dependencyReleases;
226
+ private readonly _dependencyExpirations;
227
+ private readonly _lifecycle;
228
+ private readonly _singletonConfig;
221
229
  private readonly logger;
222
230
  private readonly enc;
223
231
  private readonly codec;
@@ -230,6 +238,11 @@ declare class CacheService {
230
238
  private readonly opts;
231
239
  /** Pre-computed once — opts.namespace never changes after construction. */
232
240
  private readonly _namespace;
241
+ private readonly _namespacePrefix;
242
+ private readonly _dataPrefix;
243
+ private readonly _tagSetPrefix;
244
+ private readonly _tagVersionPrefix;
245
+ private readonly _lockPrefix;
233
246
  private readonly prefixLen;
234
247
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
235
248
  private readonly _redisDisabled;
@@ -244,6 +257,8 @@ declare class CacheService {
244
257
  private readonly keyTags;
245
258
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
246
259
  private readonly tagVersions;
260
+ /** Share active generation reads only; retain at most the tag-cache ceiling. */
261
+ private readonly _tagVersionRefreshes;
247
262
  private _tagRefreshEpoch;
248
263
  /**
249
264
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
@@ -252,6 +267,8 @@ declare class CacheService {
252
267
  private readonly dependencyIndex;
253
268
  /** Reverse index of namespaced dependent key → source glob patterns */
254
269
  private readonly keyDependencies;
270
+ /** Active writers retain their dependency edges even before admission or after eviction. */
271
+ private readonly _pendingDependencies;
255
272
  private readonly _cgroupMemoryLimit;
256
273
  private redis;
257
274
  private redisConnecting;
@@ -277,13 +294,30 @@ declare class CacheService {
277
294
  private _lastStreamId;
278
295
  private _restoredSnapshot;
279
296
  private _backplaneAvailable;
297
+ private _backplaneUnavailableReason;
298
+ private _backplaneUnavailableSince;
299
+ private _backplaneStateSince;
300
+ private _lastBackplaneHeartbeatAt;
301
+ private _backplaneHeartbeatInterval;
302
+ private _backplaneHeartbeat;
303
+ private _heartbeatPublishInFlight;
304
+ private _backplaneSubscriptionReady;
305
+ private _backplaneTransportEpoch;
306
+ private _retryBackplaneSubscription;
307
+ private _preparedBackplaneClient;
308
+ private _invalidationReadEpoch;
280
309
  private _otelCleanup;
281
310
  private _streamRecovering;
282
311
  private readonly _backplaneDisposers;
283
312
  private _destroyed;
284
313
  private readonly _pendingDiskDeletes;
314
+ /** Active invalidations fence cold Redis reads until their asynchronous deletion settles. */
315
+ private readonly _pendingRedisInvalidations;
285
316
  private _globalEpoch;
286
317
  private _pendingSpillCount;
318
+ private readonly _pendingSpills;
319
+ /** Strict reads trust only revisions spilled in this consumer epoch; bounded independently of disk size. */
320
+ private readonly _protectedSpillRevisions;
287
321
  private _suppressSpills;
288
322
  private _diskCleanupScheduled;
289
323
  private readonly _keyMutationEpochs;
@@ -298,6 +332,8 @@ declare class CacheService {
298
332
  private _addPatternTombstone;
299
333
  private _isTombstonedByPattern;
300
334
  private _assertActive;
335
+ private _beginRedisInvalidation;
336
+ private _isRedisReadInvalidated;
301
337
  private _bumpKeyMutation;
302
338
  private _getKeyMutationEpoch;
303
339
  /** Capture a commit fence before asynchronous computation outside the cache. */
@@ -307,11 +343,16 @@ declare class CacheService {
307
343
  private _fenceInvalidation;
308
344
  private _invalidateDiskKey;
309
345
  private _scheduleDiskCleanup;
346
+ private _reserveDependencies;
310
347
  private _registerDependencies;
348
+ private _trackPendingDependencies;
311
349
  private _rememberTags;
312
350
  private _restoreEntryMetadata;
313
351
  private _removeKeyTags;
314
352
  private _removeKeyDependencies;
353
+ private _clearDependencyMetadata;
354
+ private _notifyReadObserver;
355
+ private _runOrigin;
315
356
  private _handleL1Eviction;
316
357
  private _removePatternFromIndices;
317
358
  private _sweepExpiredMetadata;
@@ -360,7 +401,6 @@ declare class CacheService {
360
401
  * meaningful configuration divergence worth flagging (security/correctness
361
402
  * relevant — not cosmetic, e.g. log level).
362
403
  */
363
- private static readonly DIVERGENT_KEYS;
364
404
  /** Returns the names of options that differ between `a` and the live `b`. */
365
405
  private static optionsDiff;
366
406
  /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
@@ -380,15 +420,25 @@ declare class CacheService {
380
420
  /** Derive the globalThis key for a given set of options. */
381
421
  private static globalKey;
382
422
  /**
383
- * Prepend the configured namespace to a raw cache key.
384
- * Returns the key unchanged when namespace is empty.
423
+ * Encode the namespace, data domain, and raw key as an unambiguous v3 key.
385
424
  *
386
- * This is the only place the namespace prefix is applied — callers always
387
- * receive and provide un-prefixed keys in the public API.
425
+ * Callers always receive and provide logical keys in the public API.
388
426
  */
389
427
  private nk;
390
- /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
391
- private unnk;
428
+ private tagIndexKey;
429
+ private tagIndexPrefix;
430
+ private tagVersionKey;
431
+ private tagVersionPrefix;
432
+ private lockKey;
433
+ private undk;
434
+ /**
435
+ * Validate a snapshot write timestamp before age/skew arithmetic.
436
+ *
437
+ * NaN and non-numeric values previously made every comparison false, so a
438
+ * malformed timestamp skipped both the future-skew and maximum-age gates.
439
+ * Missing or invalid values are rejected outright rather than treated as 0.
440
+ */
441
+ private _snapshotWrittenAt;
392
442
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
393
443
  private _jitterTtl;
394
444
  /** Shared no-op span for the common case where no tracer is configured.
@@ -398,6 +448,20 @@ declare class CacheService {
398
448
  private _startSpan;
399
449
  private createDedicatedRedisClient;
400
450
  private _listenBackplane;
451
+ private _strictInvalidationReadProtectionEnabled;
452
+ private _setBackplaneUnavailable;
453
+ private _flushLocalCacheAfterInvalidationRecovery;
454
+ private _setBackplaneAvailable;
455
+ private _rejectCachedRead;
456
+ private _ensureCachedReadAllowed;
457
+ /** Shared admission/commit/response fence. Health checks must also evaluate elapsed deadlines. */
458
+ private _cachedReadAllowed;
459
+ private _checkBackplaneDeadline;
460
+ private _startBackplaneHeartbeat;
461
+ private _publishBackplaneHeartbeat;
462
+ private _acceptBackplaneHeartbeat;
463
+ private _protectedConsumerDisconnected;
464
+ private _initProtectedPubSub;
401
465
  private initBackplane;
402
466
  private _resetAfterStreamGap;
403
467
  private _startStreamConsumer;
@@ -409,8 +473,17 @@ declare class CacheService {
409
473
  * number. Invalid entries are logged and dropped — never applied.
410
474
  */
411
475
  /** @internal Exposed for testing. */
412
- _processStreamEntry(fields: string[]): void;
476
+ _processStreamEntry(fields: string[], deferHeartbeat?: (src: unknown, nonce: unknown) => void): void;
413
477
  private _applyInvalidationEvent;
478
+ /**
479
+ * Parse an optional tag version from either transport.
480
+ *
481
+ * Pub/Sub previously forwarded any numeric value (including `1.5`) while
482
+ * Streams rejected non-integers, so the two transports disagreed on the same
483
+ * logical payload. Both now share this validation: absent means "no version",
484
+ * and anything present must be a non-negative safe integer.
485
+ */
486
+ private _parseTagVersion;
414
487
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
415
488
  _handleBackplaneMessage(message: string): void;
416
489
  private publishInvalidation;
@@ -428,9 +501,10 @@ declare class CacheService {
428
501
  private _setLocalTagVersion;
429
502
  private _isGenerationalEntryStale;
430
503
  private _deleteRedisKeys;
431
- private _parseGenerationalRedisHash;
504
+ private _parseRedisHash;
432
505
  private _readRedisEntry;
433
506
  private _getTagVersion;
507
+ private _refreshTagVersion;
434
508
  private _readRedisBatch;
435
509
  private _promoteRedisEntry;
436
510
  private _readDiskEntry;
@@ -441,6 +515,7 @@ declare class CacheService {
441
515
  * Serialize payload for L2 Redis storage applying compression and encryption as configured.
442
516
  * Offloads to worker thread if pool is active and payload exceeds threshold.
443
517
  */
518
+ private _redisContext;
444
519
  private _serializeAndEncrypt;
445
520
  /**
446
521
  * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
@@ -459,8 +534,12 @@ declare class CacheService {
459
534
  * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
460
535
  * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
461
536
  * process.exit() being called before the snapshot is physically written to disk.
537
+ *
538
+ * @returns `true` when a snapshot was written (or when there was nothing to write),
539
+ * `false` when the write failed. Callers that report shutdown success must
540
+ * check this value.
462
541
  */
463
- writeSnapshot(altPath?: string): void;
542
+ writeSnapshot(altPath?: string): boolean;
464
543
  /**
465
544
  * Loads cold-start snapshot from disk into L1 memory.
466
545
  * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
@@ -499,7 +578,7 @@ declare class CacheService {
499
578
  * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
500
579
  * Caches negative lookups to avoid repeated DB hits for missing keys.
501
580
  */
502
- get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
581
+ get<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, ttlSeconds?: number, opts?: {
503
582
  priority?: CachePriority;
504
583
  swr?: number;
505
584
  refreshAhead?: number;
@@ -525,6 +604,7 @@ declare class CacheService {
525
604
  * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
526
605
  */
527
606
  flushSnapshotOnShutdown(timeoutMs?: number): Promise<boolean>;
607
+ private _drainPendingDiskWork;
528
608
  /**
529
609
  * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
530
610
  */
@@ -546,16 +626,19 @@ declare class CacheService {
546
626
  * tags: ['users'],
547
627
  * });
548
628
  */
549
- wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
629
+ wrap<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, options?: WrapOptions): Promise<T>;
550
630
  private _revalidate;
551
631
  /** Explicitly write a value into L1 (+ L2 in production). */
552
632
  set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
553
633
  tags?: string[];
554
634
  dependsOn?: string[];
555
635
  }): Promise<void>;
636
+ private _set;
556
637
  /**
557
- * Register tags for a cache key in the in-process index and (if Redis is enabled) in
558
- * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
638
+ * Retain remote discovery through the entry's hard deadline plus cleanup grace.
639
+ * Each atomic registration initializes new sets and only extends expiring sets;
640
+ * existing persistent sets retain their unknown member lifetimes. Local metadata
641
+ * is maintained at admission/retention changes. Redis failure remains best effort.
559
642
  */
560
643
  private _registerTags;
561
644
  /**
@@ -569,8 +652,12 @@ declare class CacheService {
569
652
  /**
570
653
  * Distributed counter.
571
654
  *
572
- * When Redis is active, atomically increments the key via `INCR` and returns
573
- * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
655
+ * When Redis is active, one single-key script increments and applies missing
656
+ * expiry, returning the new fleet-wide value. A positive TTL starts a fixed
657
+ * window only when no expiry exists; subsequent increments do not extend it.
658
+ * Omitted/zero TTL creates a permanent counter and preserves existing expiry.
659
+ * Positive fractional seconds round up to milliseconds. Invalid TTLs reject
660
+ * before mutation. On a Redis error it increments `counters.errors`
574
661
  * and, by default, fails OPEN — returning `0` so a caller's
575
662
  * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
576
663
  * `failClosed: true` to re-throw the error instead, enforcing the limit even
@@ -667,12 +754,14 @@ declare class CacheService {
667
754
  * const fresh = cache.getIfFresh('user:123');
668
755
  * if (fresh !== null) return fresh; // serve from L1, no network hop
669
756
  */
757
+ private _isLocallyInvalidated;
670
758
  getIfFresh<T = unknown>(cacheKey: string): T | null;
759
+ private _prepareWriteValue;
671
760
  private _prepareReadValue;
672
761
  /**
673
- * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
762
+ * Origin-free read across L1, optional disk, and Redis without invoking a fetcher.
674
763
  * Returns the cached value if found and valid, or `null` if absent / expired.
675
- * Does not write dummy entries on misses or trigger side-effects.
764
+ * Promotes hits and updates metrics/access policy; it can perform stale cleanup.
676
765
  *
677
766
  * @example
678
767
  * const val = await cache.peek<User>('user:123');
@@ -687,7 +776,7 @@ declare class CacheService {
687
776
  * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
688
777
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
689
778
  */
690
- mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
779
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[], signal?: AbortSignal) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
691
780
  /**
692
781
  * Returns a Promise that resolves once the cache is fully initialised and any
693
782
  * startup warming configured via `warmKeys` has completed.
@@ -847,6 +936,7 @@ declare class CacheService {
847
936
  bloom: {
848
937
  checks: number;
849
938
  falsePositives: number;
939
+ absentChecks: number;
850
940
  };
851
941
  compression: {
852
942
  compressed: number;
@@ -922,9 +1012,20 @@ declare class CacheService {
922
1012
  /**
923
1013
  * When an exact key `deletedKey` is removed, cascade to every dependent key
924
1014
  * that was registered via `dependsOn` and whose source pattern matches.
925
- * Transitive dependencies are traversed with cycle protection via a visited Set.
1015
+ * Collect the complete closure before mutating indices, including current pending
1016
+ * writers. Fence all affected work synchronously; callers release Redis read
1017
+ * fences only after remote deletion has settled.
926
1018
  */
927
1019
  private _cascadeDependencies;
1020
+ private _cascadeDependenciesForPattern;
1021
+ private _cascadeDependencyClosure;
1022
+ /** Whether two `*`-only globs can match at least one common string. */
1023
+ private _globPatternsIntersect;
1024
+ private _publishPatternAndKeyInvalidations;
1025
+ /** Attempt every publication even when an awaited transport rejects one key. */
1026
+ private _publishKeyInvalidations;
1027
+ /** A peer's 'del' can accompany a set: remove dependent Redis values, never the source. */
1028
+ private _completeBackplaneCascade;
928
1029
  /** Return a full metrics snapshot. */
929
1030
  metrics(): CacheMetrics;
930
1031
  /** Return auto-pipelining metrics, or null if pipelining is disabled. */
@@ -0,0 +1,14 @@
1
+ import {
2
+ CacheService,
3
+ INDEFINITE_TTL_SECONDS,
4
+ ProcessTerminationBus,
5
+ deepMergeOptions
6
+ } from "./chunk-MB3DMVWN.js";
7
+ import "./chunk-EJXG7WO6.js";
8
+ import "./chunk-KV7KISK2.js";
9
+ export {
10
+ CacheService,
11
+ INDEFINITE_TTL_SECONDS,
12
+ ProcessTerminationBus,
13
+ deepMergeOptions
14
+ };
@@ -1,4 +1,4 @@
1
- import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-BA4pz1A0.js';
1
+ import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-F8vRWMrE.js';
2
2
 
3
3
  /**
4
4
  * TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
@@ -218,6 +218,14 @@ declare class ProcessTerminationBus {
218
218
  }
219
219
  declare function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOptions>): CacheOptions;
220
220
  declare class CacheService {
221
+ private readonly _originWork;
222
+ private readonly _backgroundWork;
223
+ private readonly _originCapacityLimiter;
224
+ private readonly _dependencyBudget;
225
+ private readonly _dependencyReleases;
226
+ private readonly _dependencyExpirations;
227
+ private readonly _lifecycle;
228
+ private readonly _singletonConfig;
221
229
  private readonly logger;
222
230
  private readonly enc;
223
231
  private readonly codec;
@@ -230,6 +238,11 @@ declare class CacheService {
230
238
  private readonly opts;
231
239
  /** Pre-computed once — opts.namespace never changes after construction. */
232
240
  private readonly _namespace;
241
+ private readonly _namespacePrefix;
242
+ private readonly _dataPrefix;
243
+ private readonly _tagSetPrefix;
244
+ private readonly _tagVersionPrefix;
245
+ private readonly _lockPrefix;
233
246
  private readonly prefixLen;
234
247
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
235
248
  private readonly _redisDisabled;
@@ -244,6 +257,8 @@ declare class CacheService {
244
257
  private readonly keyTags;
245
258
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
246
259
  private readonly tagVersions;
260
+ /** Share active generation reads only; retain at most the tag-cache ceiling. */
261
+ private readonly _tagVersionRefreshes;
247
262
  private _tagRefreshEpoch;
248
263
  /**
249
264
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
@@ -252,6 +267,8 @@ declare class CacheService {
252
267
  private readonly dependencyIndex;
253
268
  /** Reverse index of namespaced dependent key → source glob patterns */
254
269
  private readonly keyDependencies;
270
+ /** Active writers retain their dependency edges even before admission or after eviction. */
271
+ private readonly _pendingDependencies;
255
272
  private readonly _cgroupMemoryLimit;
256
273
  private redis;
257
274
  private redisConnecting;
@@ -277,13 +294,30 @@ declare class CacheService {
277
294
  private _lastStreamId;
278
295
  private _restoredSnapshot;
279
296
  private _backplaneAvailable;
297
+ private _backplaneUnavailableReason;
298
+ private _backplaneUnavailableSince;
299
+ private _backplaneStateSince;
300
+ private _lastBackplaneHeartbeatAt;
301
+ private _backplaneHeartbeatInterval;
302
+ private _backplaneHeartbeat;
303
+ private _heartbeatPublishInFlight;
304
+ private _backplaneSubscriptionReady;
305
+ private _backplaneTransportEpoch;
306
+ private _retryBackplaneSubscription;
307
+ private _preparedBackplaneClient;
308
+ private _invalidationReadEpoch;
280
309
  private _otelCleanup;
281
310
  private _streamRecovering;
282
311
  private readonly _backplaneDisposers;
283
312
  private _destroyed;
284
313
  private readonly _pendingDiskDeletes;
314
+ /** Active invalidations fence cold Redis reads until their asynchronous deletion settles. */
315
+ private readonly _pendingRedisInvalidations;
285
316
  private _globalEpoch;
286
317
  private _pendingSpillCount;
318
+ private readonly _pendingSpills;
319
+ /** Strict reads trust only revisions spilled in this consumer epoch; bounded independently of disk size. */
320
+ private readonly _protectedSpillRevisions;
287
321
  private _suppressSpills;
288
322
  private _diskCleanupScheduled;
289
323
  private readonly _keyMutationEpochs;
@@ -298,6 +332,8 @@ declare class CacheService {
298
332
  private _addPatternTombstone;
299
333
  private _isTombstonedByPattern;
300
334
  private _assertActive;
335
+ private _beginRedisInvalidation;
336
+ private _isRedisReadInvalidated;
301
337
  private _bumpKeyMutation;
302
338
  private _getKeyMutationEpoch;
303
339
  /** Capture a commit fence before asynchronous computation outside the cache. */
@@ -307,11 +343,16 @@ declare class CacheService {
307
343
  private _fenceInvalidation;
308
344
  private _invalidateDiskKey;
309
345
  private _scheduleDiskCleanup;
346
+ private _reserveDependencies;
310
347
  private _registerDependencies;
348
+ private _trackPendingDependencies;
311
349
  private _rememberTags;
312
350
  private _restoreEntryMetadata;
313
351
  private _removeKeyTags;
314
352
  private _removeKeyDependencies;
353
+ private _clearDependencyMetadata;
354
+ private _notifyReadObserver;
355
+ private _runOrigin;
315
356
  private _handleL1Eviction;
316
357
  private _removePatternFromIndices;
317
358
  private _sweepExpiredMetadata;
@@ -360,7 +401,6 @@ declare class CacheService {
360
401
  * meaningful configuration divergence worth flagging (security/correctness
361
402
  * relevant — not cosmetic, e.g. log level).
362
403
  */
363
- private static readonly DIVERGENT_KEYS;
364
404
  /** Returns the names of options that differ between `a` and the live `b`. */
365
405
  private static optionsDiff;
366
406
  /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
@@ -380,15 +420,25 @@ declare class CacheService {
380
420
  /** Derive the globalThis key for a given set of options. */
381
421
  private static globalKey;
382
422
  /**
383
- * Prepend the configured namespace to a raw cache key.
384
- * Returns the key unchanged when namespace is empty.
423
+ * Encode the namespace, data domain, and raw key as an unambiguous v3 key.
385
424
  *
386
- * This is the only place the namespace prefix is applied — callers always
387
- * receive and provide un-prefixed keys in the public API.
425
+ * Callers always receive and provide logical keys in the public API.
388
426
  */
389
427
  private nk;
390
- /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
391
- private unnk;
428
+ private tagIndexKey;
429
+ private tagIndexPrefix;
430
+ private tagVersionKey;
431
+ private tagVersionPrefix;
432
+ private lockKey;
433
+ private undk;
434
+ /**
435
+ * Validate a snapshot write timestamp before age/skew arithmetic.
436
+ *
437
+ * NaN and non-numeric values previously made every comparison false, so a
438
+ * malformed timestamp skipped both the future-skew and maximum-age gates.
439
+ * Missing or invalid values are rejected outright rather than treated as 0.
440
+ */
441
+ private _snapshotWrittenAt;
392
442
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
393
443
  private _jitterTtl;
394
444
  /** Shared no-op span for the common case where no tracer is configured.
@@ -398,6 +448,20 @@ declare class CacheService {
398
448
  private _startSpan;
399
449
  private createDedicatedRedisClient;
400
450
  private _listenBackplane;
451
+ private _strictInvalidationReadProtectionEnabled;
452
+ private _setBackplaneUnavailable;
453
+ private _flushLocalCacheAfterInvalidationRecovery;
454
+ private _setBackplaneAvailable;
455
+ private _rejectCachedRead;
456
+ private _ensureCachedReadAllowed;
457
+ /** Shared admission/commit/response fence. Health checks must also evaluate elapsed deadlines. */
458
+ private _cachedReadAllowed;
459
+ private _checkBackplaneDeadline;
460
+ private _startBackplaneHeartbeat;
461
+ private _publishBackplaneHeartbeat;
462
+ private _acceptBackplaneHeartbeat;
463
+ private _protectedConsumerDisconnected;
464
+ private _initProtectedPubSub;
401
465
  private initBackplane;
402
466
  private _resetAfterStreamGap;
403
467
  private _startStreamConsumer;
@@ -409,8 +473,17 @@ declare class CacheService {
409
473
  * number. Invalid entries are logged and dropped — never applied.
410
474
  */
411
475
  /** @internal Exposed for testing. */
412
- _processStreamEntry(fields: string[]): void;
476
+ _processStreamEntry(fields: string[], deferHeartbeat?: (src: unknown, nonce: unknown) => void): void;
413
477
  private _applyInvalidationEvent;
478
+ /**
479
+ * Parse an optional tag version from either transport.
480
+ *
481
+ * Pub/Sub previously forwarded any numeric value (including `1.5`) while
482
+ * Streams rejected non-integers, so the two transports disagreed on the same
483
+ * logical payload. Both now share this validation: absent means "no version",
484
+ * and anything present must be a non-negative safe integer.
485
+ */
486
+ private _parseTagVersion;
414
487
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
415
488
  _handleBackplaneMessage(message: string): void;
416
489
  private publishInvalidation;
@@ -428,9 +501,10 @@ declare class CacheService {
428
501
  private _setLocalTagVersion;
429
502
  private _isGenerationalEntryStale;
430
503
  private _deleteRedisKeys;
431
- private _parseGenerationalRedisHash;
504
+ private _parseRedisHash;
432
505
  private _readRedisEntry;
433
506
  private _getTagVersion;
507
+ private _refreshTagVersion;
434
508
  private _readRedisBatch;
435
509
  private _promoteRedisEntry;
436
510
  private _readDiskEntry;
@@ -441,6 +515,7 @@ declare class CacheService {
441
515
  * Serialize payload for L2 Redis storage applying compression and encryption as configured.
442
516
  * Offloads to worker thread if pool is active and payload exceeds threshold.
443
517
  */
518
+ private _redisContext;
444
519
  private _serializeAndEncrypt;
445
520
  /**
446
521
  * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
@@ -459,8 +534,12 @@ declare class CacheService {
459
534
  * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
460
535
  * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
461
536
  * process.exit() being called before the snapshot is physically written to disk.
537
+ *
538
+ * @returns `true` when a snapshot was written (or when there was nothing to write),
539
+ * `false` when the write failed. Callers that report shutdown success must
540
+ * check this value.
462
541
  */
463
- writeSnapshot(altPath?: string): void;
542
+ writeSnapshot(altPath?: string): boolean;
464
543
  /**
465
544
  * Loads cold-start snapshot from disk into L1 memory.
466
545
  * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
@@ -499,7 +578,7 @@ declare class CacheService {
499
578
  * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
500
579
  * Caches negative lookups to avoid repeated DB hits for missing keys.
501
580
  */
502
- get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
581
+ get<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, ttlSeconds?: number, opts?: {
503
582
  priority?: CachePriority;
504
583
  swr?: number;
505
584
  refreshAhead?: number;
@@ -525,6 +604,7 @@ declare class CacheService {
525
604
  * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
526
605
  */
527
606
  flushSnapshotOnShutdown(timeoutMs?: number): Promise<boolean>;
607
+ private _drainPendingDiskWork;
528
608
  /**
529
609
  * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
530
610
  */
@@ -546,16 +626,19 @@ declare class CacheService {
546
626
  * tags: ['users'],
547
627
  * });
548
628
  */
549
- wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
629
+ wrap<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, options?: WrapOptions): Promise<T>;
550
630
  private _revalidate;
551
631
  /** Explicitly write a value into L1 (+ L2 in production). */
552
632
  set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
553
633
  tags?: string[];
554
634
  dependsOn?: string[];
555
635
  }): Promise<void>;
636
+ private _set;
556
637
  /**
557
- * Register tags for a cache key in the in-process index and (if Redis is enabled) in
558
- * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
638
+ * Retain remote discovery through the entry's hard deadline plus cleanup grace.
639
+ * Each atomic registration initializes new sets and only extends expiring sets;
640
+ * existing persistent sets retain their unknown member lifetimes. Local metadata
641
+ * is maintained at admission/retention changes. Redis failure remains best effort.
559
642
  */
560
643
  private _registerTags;
561
644
  /**
@@ -569,8 +652,12 @@ declare class CacheService {
569
652
  /**
570
653
  * Distributed counter.
571
654
  *
572
- * When Redis is active, atomically increments the key via `INCR` and returns
573
- * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
655
+ * When Redis is active, one single-key script increments and applies missing
656
+ * expiry, returning the new fleet-wide value. A positive TTL starts a fixed
657
+ * window only when no expiry exists; subsequent increments do not extend it.
658
+ * Omitted/zero TTL creates a permanent counter and preserves existing expiry.
659
+ * Positive fractional seconds round up to milliseconds. Invalid TTLs reject
660
+ * before mutation. On a Redis error it increments `counters.errors`
574
661
  * and, by default, fails OPEN — returning `0` so a caller's
575
662
  * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
576
663
  * `failClosed: true` to re-throw the error instead, enforcing the limit even
@@ -667,12 +754,14 @@ declare class CacheService {
667
754
  * const fresh = cache.getIfFresh('user:123');
668
755
  * if (fresh !== null) return fresh; // serve from L1, no network hop
669
756
  */
757
+ private _isLocallyInvalidated;
670
758
  getIfFresh<T = unknown>(cacheKey: string): T | null;
759
+ private _prepareWriteValue;
671
760
  private _prepareReadValue;
672
761
  /**
673
- * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
762
+ * Origin-free read across L1, optional disk, and Redis without invoking a fetcher.
674
763
  * Returns the cached value if found and valid, or `null` if absent / expired.
675
- * Does not write dummy entries on misses or trigger side-effects.
764
+ * Promotes hits and updates metrics/access policy; it can perform stale cleanup.
676
765
  *
677
766
  * @example
678
767
  * const val = await cache.peek<User>('user:123');
@@ -687,7 +776,7 @@ declare class CacheService {
687
776
  * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
688
777
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
689
778
  */
690
- mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
779
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[], signal?: AbortSignal) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
691
780
  /**
692
781
  * Returns a Promise that resolves once the cache is fully initialised and any
693
782
  * startup warming configured via `warmKeys` has completed.
@@ -847,6 +936,7 @@ declare class CacheService {
847
936
  bloom: {
848
937
  checks: number;
849
938
  falsePositives: number;
939
+ absentChecks: number;
850
940
  };
851
941
  compression: {
852
942
  compressed: number;
@@ -922,9 +1012,20 @@ declare class CacheService {
922
1012
  /**
923
1013
  * When an exact key `deletedKey` is removed, cascade to every dependent key
924
1014
  * that was registered via `dependsOn` and whose source pattern matches.
925
- * Transitive dependencies are traversed with cycle protection via a visited Set.
1015
+ * Collect the complete closure before mutating indices, including current pending
1016
+ * writers. Fence all affected work synchronously; callers release Redis read
1017
+ * fences only after remote deletion has settled.
926
1018
  */
927
1019
  private _cascadeDependencies;
1020
+ private _cascadeDependenciesForPattern;
1021
+ private _cascadeDependencyClosure;
1022
+ /** Whether two `*`-only globs can match at least one common string. */
1023
+ private _globPatternsIntersect;
1024
+ private _publishPatternAndKeyInvalidations;
1025
+ /** Attempt every publication even when an awaited transport rejects one key. */
1026
+ private _publishKeyInvalidations;
1027
+ /** A peer's 'del' can accompany a set: remove dependent Redis values, never the source. */
1028
+ private _completeBackplaneCascade;
928
1029
  /** Return a full metrics snapshot. */
929
1030
  metrics(): CacheMetrics;
930
1031
  /** Return auto-pipelining metrics, or null if pipelining is disabled. */