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,5 +1,16 @@
1
1
  import { KeyObject } from 'crypto';
2
2
 
3
+ interface SnapshotTransferOptions {
4
+ /** Maximum downloaded snapshot bytes, enforced while streaming. Default: 220 MiB. */
5
+ maxBytes?: number;
6
+ /** Deadline covering the request and response body. Default: 30 seconds. */
7
+ timeoutMs?: number;
8
+ }
9
+ interface SnapshotRequestOptions {
10
+ /** Cancel transport work, for example when the owning cache is destroyed. */
11
+ signal?: AbortSignal;
12
+ }
13
+
3
14
  /**
4
15
  * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
5
16
  *
@@ -43,6 +54,7 @@ declare class CacheEncryption {
43
54
  private _mode;
44
55
  /** Fail-closed on invalid key material when opted in via constructor opts. */
45
56
  private readonly _strictKeyValidation;
57
+ private readonly _allowLegacyPlaintextRead;
46
58
  private _prevKey;
47
59
  private _prevKeyObj;
48
60
  private _prevMode;
@@ -68,6 +80,7 @@ declare class CacheEncryption {
68
80
  private _xorBuffer;
69
81
  constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode, opts?: {
70
82
  strictKeyValidation?: boolean;
83
+ allowLegacyPlaintextRead?: boolean;
71
84
  });
72
85
  get isEnabled(): boolean;
73
86
  get mode(): EncryptionMode;
@@ -82,6 +95,7 @@ declare class CacheEncryption {
82
95
  mode: EncryptionMode;
83
96
  prevKeyBase64: string | undefined;
84
97
  prevMode: EncryptionMode;
98
+ allowLegacyPlaintextRead: boolean;
85
99
  };
86
100
  /**
87
101
  * Rotate the active encryption key dynamically at runtime.
@@ -95,22 +109,23 @@ declare class CacheEncryption {
95
109
  * Returns a mode-prefixed base64 string when a key is configured;
96
110
  * otherwise returns the original string unchanged (backward-compatible).
97
111
  */
98
- encrypt(plaintext: string): string;
112
+ encrypt(plaintext: string, context?: string): string;
99
113
  /**
100
114
  * Decrypt a Redis value.
101
115
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
102
116
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
103
117
  */
104
- decrypt(value: string): string;
118
+ assertReadPolicy(value: string | Buffer, context?: string): void;
119
+ decrypt(value: string, context?: string): string;
105
120
  private _decryptWithKey;
106
121
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
107
- encryptBuffer(data: Buffer): Buffer;
122
+ encryptBuffer(data: Buffer, context?: string): Buffer;
108
123
  /**
109
124
  * Decrypt a raw Buffer from disk/snapshot.
110
125
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
111
126
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
112
127
  */
113
- decryptBuffer(data: Buffer): Buffer;
128
+ decryptBuffer(data: Buffer, context?: string): Buffer;
114
129
  private _decryptBufferWithKey;
115
130
  }
116
131
  interface EnvelopeEncryptionOptions {
@@ -144,16 +159,17 @@ declare class EnvelopeEncryption {
144
159
  * Enables stateless containers (Kubernetes, AWS ECS/Fargate, Google Cloud Run, Fly.io)
145
160
  * to persist and hydrate L1 cache snapshots from remote object storage (S3, GCS, R2, Azure, MinIO, or HTTP).
146
161
  */
162
+
147
163
  interface IRemoteSnapshotAdapter {
148
164
  /**
149
165
  * Read the latest snapshot blob from remote storage.
150
166
  * Returns null if no snapshot exists yet (e.g. 404 Not Found / first deploy).
151
167
  */
152
- get(): Promise<Buffer | Uint8Array | null>;
168
+ get(options?: SnapshotRequestOptions): Promise<Buffer | Uint8Array | null>;
153
169
  /**
154
170
  * Write the snapshot blob to remote storage.
155
171
  */
156
- put(data: Buffer): Promise<void>;
172
+ put(data: Buffer, options?: SnapshotRequestOptions): Promise<void>;
157
173
  }
158
174
 
159
175
  interface RemoteSnapshotOptions {
@@ -184,7 +200,7 @@ interface RemoteSnapshotOptions {
184
200
  */
185
201
  envelope?: EnvelopeEncryptionOptions;
186
202
  }
187
- interface HttpSnapshotAdapterOptions {
203
+ interface HttpSnapshotAdapterOptions extends SnapshotTransferOptions {
188
204
  /**
189
205
  * URL to fetch the snapshot from (e.g. S3 presigned GET URL or internal blob service).
190
206
  */
@@ -230,7 +246,7 @@ interface CrossRegionInvalidationEvent {
230
246
  tagVersion?: number;
231
247
  /** Timestamp when the event was created */
232
248
  timestamp: number;
233
- /** Optional namespace of the origin cache */
249
+ /** Exact trimmed namespace of the origin cache. Omitted means the default namespace. */
234
250
  namespace?: string;
235
251
  /** Optional W3C traceparent header for distributed context propagation */
236
252
  traceparent?: string;
@@ -327,7 +343,8 @@ type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
327
343
  interface CustomCompressor {
328
344
  name: string;
329
345
  compress: (buf: Buffer) => Buffer;
330
- decompress: (buf: Buffer) => Buffer;
346
+ /** Honor maxOutputBytes during allocation; the returned size is also checked. */
347
+ decompress: (buf: Buffer, maxOutputBytes?: number) => Buffer;
331
348
  }
332
349
  /**
333
350
  * Initializes the WebAssembly Zstandard codec.
@@ -335,6 +352,45 @@ interface CustomCompressor {
335
352
  */
336
353
  declare function initZstd(): Promise<any>;
337
354
 
355
+ interface OriginCapacityOptions {
356
+ /** Per-process physical work budget. Batch fills reserve one slot per unique owned key. */
357
+ maxConcurrent: number;
358
+ }
359
+ interface OriginRunOptions {
360
+ signal?: AbortSignal;
361
+ /** Caller deadline in milliseconds; zero rejects before starting work. */
362
+ timeoutMs?: number;
363
+ /** Conservative work cost; defaults to one. No queue or implicit retry. */
364
+ weight?: number;
365
+ }
366
+ interface OriginCapacityMetrics {
367
+ active: number;
368
+ capacity: number;
369
+ rejected: number;
370
+ started: number;
371
+ completed: number;
372
+ cancelled: number;
373
+ timedOut: number;
374
+ closed: boolean;
375
+ }
376
+ /** Share one instance across cache loaders and the direct-origin route for the same origin. */
377
+ declare class OriginCapacityLimiter {
378
+ private readonly work;
379
+ private readonly pending;
380
+ private closed;
381
+ private started;
382
+ private completed;
383
+ private cancelled;
384
+ private timedOut;
385
+ constructor(options: OriginCapacityOptions);
386
+ run<T>(origin: (signal: AbortSignal) => T | PromiseLike<T>, options?: OriginRunOptions): Promise<T>;
387
+ /** Reject new work and signal active origins. Ignored cancellation still occupies capacity. */
388
+ close(): void;
389
+ metrics(): OriginCapacityMetrics;
390
+ /** Export once per shared origin budget, separately from per-namespace cache series. */
391
+ toPrometheusText(prefix?: string): string;
392
+ }
393
+
338
394
  /**
339
395
  * tricache — shared types and interfaces
340
396
  */
@@ -437,6 +493,8 @@ interface SmartCacheEntry {
437
493
  * Optional for backward compatibility with snapshots written by older versions.
438
494
  */
439
495
  setAt?: number;
496
+ /** Opaque identity of this write, preserved across tiers and snapshots. */
497
+ revision?: string;
440
498
  /** Active tag versions at write time (used when tagStrategy === 'generational') */
441
499
  tagVersions?: Record<string, number>;
442
500
  /** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
@@ -462,6 +520,7 @@ interface CacheHit {
462
520
  tagVersions?: Record<string, number>;
463
521
  /** Timestamp (ms) when this entry was written into memory */
464
522
  setAt?: number;
523
+ revision?: string;
465
524
  tags?: string[];
466
525
  dependsOn?: string[];
467
526
  }
@@ -480,6 +539,7 @@ interface DiskCacheEntry {
480
539
  tagVersions?: Record<string, number>;
481
540
  /** Original write time and TTL, preserved on spill and promotion. */
482
541
  setAt?: number;
542
+ revision?: string;
483
543
  ttlMs?: number;
484
544
  delta?: number;
485
545
  tags?: string[];
@@ -495,6 +555,21 @@ interface CacheMetrics {
495
555
  namespace: string;
496
556
  /** Milliseconds since the CacheService instance was constructed */
497
557
  uptimeMs: number;
558
+ /** Per-cache admission accounting; active origin work remains reserved until its physical promise settles. */
559
+ work?: {
560
+ origin: {
561
+ active: number;
562
+ capacity: number;
563
+ rejected: number;
564
+ };
565
+ background: {
566
+ active: number;
567
+ capacity: number;
568
+ rejected: number;
569
+ };
570
+ };
571
+ /** Process-shared physical origin budget, when an OriginCapacityLimiter is configured. */
572
+ originCapacity?: OriginCapacityMetrics;
498
573
  gets: {
499
574
  total: number;
500
575
  l1Hits: number;
@@ -528,6 +603,8 @@ interface CacheMetrics {
528
603
  errors: number;
529
604
  /** Times a later `create(ns)` call passed options diverging from the live singleton. */
530
605
  singletonDivergences: number;
606
+ /** Cached reads rejected because strict invalidation protection was active. */
607
+ invalidationReadRejections?: number;
531
608
  };
532
609
  bloom: {
533
610
  /** Total bloom-filter checks (get() calls that passed prefix filter) */
@@ -550,6 +627,18 @@ interface CacheMetrics {
550
627
  backplane: {
551
628
  enabled: boolean;
552
629
  mode: 'pubsub' | 'stream';
630
+ /** True when cached values are rejected while the invalidation consumer is unavailable. */
631
+ readProtectionEnabled?: boolean;
632
+ /** Current strict-read protection state. */
633
+ readProtectionActive?: boolean;
634
+ /** Sanitized reason for the current protection state, when active. */
635
+ readProtectionReason?: string;
636
+ /** Date.now() timestamp when the current protection state began. */
637
+ readProtectionSince?: number | null;
638
+ /** Monotonic elapsed milliseconds while the read gate is closed (zero when open). */
639
+ readProtectionDurationMs?: number;
640
+ /** Configured consumer proof deadline when strict protection is enabled. */
641
+ readProtectionDeadlineMs?: number;
553
642
  /** Invalidation messages published to other instances */
554
643
  sent: number;
555
644
  /** Invalidation messages received from other instances */
@@ -671,6 +760,18 @@ type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-ha
671
760
  * All fields are optional — sensible defaults are used when omitted.
672
761
  */
673
762
  interface CacheOptions {
763
+ /** Optional process-wide origin budget shared with other caches and direct-origin fallback. */
764
+ originCapacityLimiter?: OriginCapacityLimiter;
765
+ /** Maximum concurrent origin invocations (batch calls reserve one slot per owned key). Default: 1024. Saturated misses reject; no queue. */
766
+ maxConcurrentFetches?: number;
767
+ /** Maximum concurrent background refreshes, also subject to maxConcurrentFetches. Default: 64. */
768
+ maxBackgroundRefreshes?: number;
769
+ /** Maximum unique stored/pending dependency edges per instance. Default: 100000. */
770
+ maxDependencyEdges?: number;
771
+ /** Maximum outstanding serialization tasks, including pools draining during rotation. Default: 256. */
772
+ workerMaxPendingTasks?: number;
773
+ /** Outstanding worker input/context admission across rotation. Default: 64 MiB; not total process memory. */
774
+ workerMaxPendingBytes?: number;
674
775
  /**
675
776
  * Plug in your own logger (pino, winston, bunyan, …).
676
777
  * Defaults to a minimal console logger that only prints warn/error.
@@ -701,7 +802,7 @@ interface CacheOptions {
701
802
  * - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
702
803
  * mathematical scan resistance and burst recency absorption.
703
804
  * - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
704
- * Default: `'wtinylfu'`
805
+ * Default: `'adaptive'`; all built-in presets explicitly select `'wtinylfu'`.
705
806
  */
706
807
  l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
707
808
  /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
@@ -782,7 +883,7 @@ interface CacheOptions {
782
883
  /**
783
884
  * Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
784
885
  * Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
785
- * Default: false
886
+ * Default: true
786
887
  */
787
888
  autoPipeline?: boolean;
788
889
  /**
@@ -858,8 +959,10 @@ interface CacheOptions {
858
959
  * Has no effect when no key is configured at all (encryption stays off, by design).
859
960
  */
860
961
  strictKeyValidation?: boolean;
962
+ /** Permit legacy context-free ciphertext/plaintext reads during a deliberate migration. Default: false. */
963
+ allowLegacyPlaintextRead?: boolean;
861
964
  /**
862
- * Whether to call `.toJSON()` when serializing objects into binary cache buffers.
965
+ * Whether to call `.toJSON()` when serializing objects for packed buffers and Redis.
863
966
  * - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
864
967
  * - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
865
968
  * avoiding accidental API response projections on cached domain entities.
@@ -888,7 +991,7 @@ interface CacheOptions {
888
991
  compressionThresholdBytes?: number;
889
992
  /**
890
993
  * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
891
- * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
994
+ * on startup. Default: os.tmpdir()/tricache-snapshot-v3-<namespace-hex>.msgpack
892
995
  */
893
996
  snapshotPath?: string;
894
997
  /**
@@ -901,24 +1004,16 @@ interface CacheOptions {
901
1004
  */
902
1005
  remoteSnapshot?: RemoteSnapshotOptions;
903
1006
  /**
904
- * Optional namespace prefix for all cache keys.
905
- *
906
- * When set, every key is transparently stored as `${namespace}:${key}` in
907
- * L1, L1.5 (disk), and L2 (Redis). This enables:
908
- * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
909
- * — tenants sharing the same Redis instance or disk dir are fully isolated.
910
- * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
911
- * - **Service-level scoping**: microservices sharing one Redis without key collisions.
1007
+ * Namespace identifier used to derive collision-free, versioned storage keys
1008
+ * across L1, disk, Redis, invalidation, and snapshots. The identifier is trimmed.
1009
+ * Consumers continue to use logical keys such as `get('user:1')`.
912
1010
  *
913
- * Consumers never see the prefix — `get('user:1')` behaves identically
914
- * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
915
- * scope to the namespace.
1011
+ * The v3 format separates data, tag sets, tag versions, and locks. It does not
1012
+ * read earlier raw/colon-prefixed or v2 entries as a fallback. Upgrades start
1013
+ * cold; coordinate all writers onto v3 or isolate storage during rollout.
916
1014
  *
917
- * The process-level singleton, disk cache directory, and cold-start snapshot
918
- * path are all scoped per namespace, so two `CacheService.create()` calls
919
- * with different namespaces return completely independent instances.
920
- *
921
- * Default: `''` (no prefix)
1015
+ * Use separate Node and Edge namespaces: their value formats are not interoperable.
1016
+ * Default: `''` (the default namespace, also stored under the v3 format).
922
1017
  */
923
1018
  namespace?: string;
924
1019
  /**
@@ -978,6 +1073,17 @@ interface CacheOptions {
978
1073
  * Default: `false` (asynchronous fire-and-forget for minimal caller latency).
979
1074
  */
980
1075
  awaitInvalidationBackplane?: boolean;
1076
+ /**
1077
+ * Reject cached reads while the invalidation consumer is unavailable or has
1078
+ * missed its heartbeat deadline. The caller can catch
1079
+ * `CacheInvalidationUnavailableError` and use an authoritative origin route.
1080
+ * This is opt-in; `false` preserves the default availability-first behavior.
1081
+ * Requires active Redis/invalidation, a supported dedicated subscriber, and a
1082
+ * finite positive `backplaneMaxStalenessMs` detection deadline. Reads/fills
1083
+ * spanning a gate closure reject even if the consumer recovers meanwhile.
1084
+ * Strict startup skips snapshot hydration and discards existing local spill.
1085
+ */
1086
+ rejectCachedReadsOnInvalidationLoss?: boolean;
981
1087
  /**
982
1088
  * If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
983
1089
  * encounters a connection or runtime error during lock acquisition, preventing
@@ -1113,17 +1219,19 @@ interface CacheOptions {
1113
1219
  frozen?: boolean;
1114
1220
  /**
1115
1221
  * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
1116
- * and automatically derives an optimal TTL from the p95 fetch duration:
1222
+ * and derives a cost-based TTL from the p95 fetch duration:
1117
1223
  *
1118
1224
  * ```
1119
- * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
1225
+ * adaptedTtlMs = clamp(round(p95LatencyMs × adaptiveTtlMultiplier),
1226
+ * adaptiveTtlMin × 1000, adaptiveTtlMax × 1000)
1120
1227
  * ```
1121
1228
  *
1122
1229
  * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
1123
1230
  * for a key, then the library takes over TTL management autonomously.
1124
1231
  *
1125
- * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
1126
- * their base TTL. Callers no longer need to reason about individual TTL values.
1232
+ * More expensive keys receive longer derived TTLs than cheaper keys, subject
1233
+ * to the configured bounds. Fetch latency does not establish data freshness:
1234
+ * choose adaptiveTtlMin/Max to match your application's stale-data tolerance.
1127
1235
  *
1128
1236
  * Default: `false`.
1129
1237
  */
@@ -1141,11 +1249,13 @@ interface CacheOptions {
1141
1249
  */
1142
1250
  adaptiveTtlMax?: number;
1143
1251
  /**
1144
- * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
1252
+ * Dimensionless factor: `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlMs`
1253
+ * before applying the minimum and maximum (configured in seconds).
1145
1254
  *
1146
1255
  * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
1147
- * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
1148
- * if you want the cache to absorb more upstream pressure.
1256
+ * 4-second derived TTL, raised to 10 seconds by the default minimum.
1257
+ * A 2 000 ms fetch yields 40 seconds. Increase the multiplier if you want
1258
+ * the cache to absorb more upstream pressure, within your freshness bounds.
1149
1259
  *
1150
1260
  * Default: `20`.
1151
1261
  */
@@ -1165,12 +1275,11 @@ interface CacheOptions {
1165
1275
  */
1166
1276
  adaptiveTtlMaxKeys?: number;
1167
1277
  /**
1168
- * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
1169
- * encryption and decryption for large payloads to those threads, keeping the
1170
- * V8 main event loop free for concurrent HTTP requests.
1278
+ * When `true`, tricache spawns a pool of worker threads and offloads
1279
+ * compression and encryption/decryption of large Redis payloads.
1171
1280
  *
1172
- * Only takes effect when `encryptionKey` is set — plaintext payloads are never
1173
- * serialized off-thread because `JSON.stringify/parse` is already fast.
1281
+ * MessagePack encode/decode remains on the calling thread. Compression can
1282
+ * run in workers even without encryption; custom compressors run locally.
1174
1283
  *
1175
1284
  * Default: `false`. Enable in long-running servers that write multi-megabyte
1176
1285
  * encrypted payloads and observe event-loop latency spikes.
@@ -1199,6 +1308,9 @@ interface CacheOptions {
1199
1308
  *
1200
1309
  * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
1201
1310
  * Default: `5000` (5 seconds).
1311
+ * With `rejectCachedReadsOnInvalidationLoss`, this also bounds silent loss
1312
+ * detection since the send time of the last acknowledged consumer challenge.
1313
+ * Strict mode requires a finite positive value and uses monotonic elapsed time.
1202
1314
  */
1203
1315
  backplaneMaxStalenessMs?: number;
1204
1316
  /**
@@ -1334,8 +1446,8 @@ interface CacheOptions {
1334
1446
  */
1335
1447
  backplaneStreamBlockMs?: number;
1336
1448
  /**
1337
- * Custom Redis Stream key name.
1338
- * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
1449
+ * Custom Redis Stream key base. TriCache adds a namespace-specific suffix so
1450
+ * streams remain isolated. The default is hash-tagged for Redis Cluster routing.
1339
1451
  */
1340
1452
  backplaneStreamKey?: string;
1341
1453
  /**
@@ -1367,7 +1479,11 @@ interface WrapOptions {
1367
1479
  priority?: CachePriority;
1368
1480
  /** Semantic tags for invalidation. */
1369
1481
  tags?: string[];
1370
- /** Dependency cascade patterns (e.g. `['user:*']`). */
1482
+ /**
1483
+ * Logical source-key patterns (e.g. `['user:*']`) for transitive exact-key
1484
+ * invalidation. Discovery uses process-local entry metadata and active writers;
1485
+ * it is not a shared fleet-wide dependency index.
1486
+ */
1371
1487
  dependsOn?: string[];
1372
1488
  /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
1373
1489
  refreshAhead?: number;
@@ -1475,6 +1591,7 @@ interface IRedisDriver {
1475
1591
  count?: number;
1476
1592
  }): any;
1477
1593
  hset?(key: string, value: Record<string, string>): Promise<unknown>;
1594
+ /** Enables tagged hash envelopes, preserving tags/deadlines on cold reads and touch(). */
1478
1595
  hgetall?(key: string): Promise<Record<string, string>>;
1479
1596
  publish?(channel: string, message: string): Promise<number>;
1480
1597
  subscribe?(...channels: string[]): Promise<unknown>;
@@ -1516,4 +1633,4 @@ interface WTinyLfuStats {
1516
1633
  promotions: number;
1517
1634
  }
1518
1635
 
1519
- export { type ICacheObservableGauge as A, type ICacheSpan as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type ICacheSpanLink as F, type ICrossRegionRelay as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, type WebhookRequestLike as J, type WebhookResponseLike as K, type LockOptions as L, consoleLogger as M, createCrossRegionWebhookHandler as N, createCustomCrossRegionRelay as O, createCustomSnapshotAdapter as P, createHttpMeshRelay as Q, type RemoteSnapshotOptions as R, type SmartCacheEntry as S, createHttpSnapshotAdapter as T, createMemoryCrossRegionRelay as U, createMemorySnapshotAdapter as V, type WrapOptions as W, initZstd as X, type InvalidateTagOptions as a, type CacheMetrics as b, type CacheHealthStatus as c, type CachePresetType as d, type CrossRegionInvalidationEvent as e, CachePriority as f, type CachePingResult as g, type WTinyLfuStats as h, type ILogger as i, type IRemoteSnapshotAdapter as j, type CategoryLimit as k, type EvictionReason as l, type CacheHit as m, CacheEncryption as n, type CompressionAlgorithm as o, type DiskCacheEntry as p, type IRedisDriver as q, type IRedisPipeline as r, type CrossRegionRelayOptions as s, type CustomCompressor as t, EnvelopeEncryption as u, type EnvelopeEncryptionOptions as v, type HttpSnapshotAdapterOptions as w, type ICacheBatchObservableCallback as x, type ICacheCounter as y, type ICacheMeter as z };
1636
+ export { createMemoryCrossRegionRelay as $, type ICacheCounter as A, type ICacheMeter as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type ICacheObservableGauge as F, type ICacheSpan as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, type ICacheSpanLink as J, type ICrossRegionRelay as K, type LockOptions as L, type OriginCapacityMetrics as M, type OriginCapacityOptions as N, OriginCapacityLimiter as O, type OriginRunOptions as P, type WebhookRequestLike as Q, type RemoteSnapshotOptions as R, type SnapshotTransferOptions as S, type WebhookResponseLike as T, consoleLogger as U, createCrossRegionWebhookHandler as V, type WrapOptions as W, createCustomCrossRegionRelay as X, createCustomSnapshotAdapter as Y, createHttpMeshRelay as Z, createHttpSnapshotAdapter as _, type InvalidateTagOptions as a, createMemorySnapshotAdapter as a0, initZstd as a1, type CacheMetrics as b, type CacheHealthStatus as c, type CachePresetType as d, type CrossRegionInvalidationEvent as e, CachePriority as f, type CachePingResult as g, type WTinyLfuStats as h, type ILogger as i, type IRemoteSnapshotAdapter as j, type SnapshotRequestOptions as k, type CategoryLimit as l, type SmartCacheEntry as m, type EvictionReason as n, type CacheHit as o, CacheEncryption as p, type CompressionAlgorithm as q, type DiskCacheEntry as r, type IRedisDriver as s, type IRedisPipeline as t, type CrossRegionRelayOptions as u, type CustomCompressor as v, EnvelopeEncryption as w, type EnvelopeEncryptionOptions as x, type HttpSnapshotAdapterOptions as y, type ICacheBatchObservableCallback as z };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "1.0.2",
4
- "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
3
+ "version": "2.0.0",
4
+ "description": "Node.js caching with bounded memory, Redis/Valkey sharing, tag invalidation, stale-while-revalidate, per-process request coalescing, framework adapters, and optional local disk spill.",
5
5
  "keywords": [
6
6
  "cache",
7
7
  "redis",
@@ -204,12 +204,31 @@
204
204
  "lint": "oxlint src tests scripts",
205
205
  "test": "vitest run",
206
206
  "test:integration": "vitest run --config vitest.integration.config.ts",
207
+ "test:shutdown-docker": "node scripts/run-shutdown-probes.mjs",
208
+ "test:storage-docker": "node scripts/run-storage-permission-probes.mjs",
209
+ "test:recovery-docker": "node scripts/run-redis-recovery-probes.mjs",
210
+ "test:rollout-docker": "node scripts/run-redis-recovery-probes.mjs --rollout",
207
211
  "test:watch": "vitest",
208
212
  "check:package": "node scripts/check-package.mjs",
209
213
  "check:release-version": "node scripts/check-release-version.mjs",
214
+ "check:production-start": "node scripts/check-production-start.mjs",
215
+ "check:rehearsal-runner": "node --test tests/rehearsal-runner.test.mjs tests/m3-protocol.test.mjs",
216
+ "check:m3-rehearsal": "node --test tests/m3-rehearsal.test.mjs tests/service-telemetry.test.mjs tests/production-service.test.mjs",
217
+ "check:spill-crash": "node scripts/check-spill-crash.mjs",
218
+ "check:edge-provider": "node scripts/check-edge-provider.mjs",
210
219
  "bench": "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts",
211
220
  "bench:roi": "tsx bench/cloud-roi-simulation.ts",
212
221
  "bench:compression": "tsx bench/compression.bench.ts",
222
+ "bench:compare": "tsx bench/compare/runner.ts",
223
+ "bench:compare:smoke": "tsx bench/compare/runner.ts --quick",
224
+ "bench:tag-refresh": "node bench/tag-refresh/run.mjs",
225
+ "bench:public-trace": "tsx bench/public-trace/run-baseline.ts",
226
+ "bench:public-trace:l1": "node --import tsx/esm bench/public-trace/run-l1.ts",
227
+ "bench:public-trace:admission": "node --import tsx/esm bench/public-trace/run-admission-probe.ts",
228
+ "bench:public-trace:calibrate-admission": "node --import tsx/esm bench/public-trace/run-admission-calibration.ts",
229
+ "bench:public-trace:entry-policy": "node --import tsx/esm bench/public-trace/run-entry-policy.ts",
230
+ "bench:outage": "node bench/compare/outage-runner.ts",
231
+ "lint:bench": "oxlint bench/compare bench/tag-refresh bench/public-trace",
213
232
  "docs:dev": "vitepress dev docs",
214
233
  "docs:build": "vitepress build docs",
215
234
  "docs:preview": "vitepress preview docs",
@@ -2,6 +2,19 @@ import type { IRedisDriver, IRedisPipeline } from '../types';
2
2
  import { Cluster } from 'ioredis';
3
3
  import { redisHashSlot } from '../utils/redis-slot';
4
4
 
5
+ const LUA_TIMED_STRING_READ = `-- tricache: atomic timed string read
6
+ local value = redis.call('GET', KEYS[1])
7
+ return {value, redis.call('PTTL', KEYS[1])}`;
8
+
9
+ const LUA_TIMED_READ = `-- tricache: atomic typed timed read
10
+ local kind = redis.call('TYPE', KEYS[1]).ok
11
+ if kind == 'string' then
12
+ return {kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1])}
13
+ elseif kind == 'hash' then
14
+ return {kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1])}
15
+ end
16
+ return {'none', false, -2}`;
17
+
5
18
  export interface AutoPipelinerOptions {
6
19
  /** Maximum number of operations to coalesce before forcing an immediate pipeline dispatch. Default: 100 */
7
20
  maxBatchSize?: number;
@@ -54,7 +67,36 @@ interface PendingReadOp {
54
67
  reject: (err: Error) => void;
55
68
  }
56
69
 
57
- /** Read value + PTTL in one atomic, single-key transaction where the driver supports it. */
70
+ function parseTimedReadResult(result: unknown): TimedRedisValue {
71
+ if (!Array.isArray(result) || result.length !== 3) throw new Error('Invalid atomic Redis read result');
72
+ const kind = result[0];
73
+ const ttlMs = Number(result[2]);
74
+ if ((kind !== 'string' && kind !== 'hash' && kind !== 'none') || !Number.isFinite(ttlMs)) {
75
+ throw new Error('Invalid atomic Redis read result');
76
+ }
77
+ if (kind === 'none') return { raw: null, ttlMs: -2 };
78
+ if (kind === 'string') {
79
+ const raw = result[1] === false || result[1] === null ? null : String(result[1]);
80
+ return { raw, ttlMs };
81
+ }
82
+ const payload = result[1];
83
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) throw new Error('Invalid atomic Redis hash result');
84
+ return {
85
+ raw: Object.fromEntries(Array.from({ length: payload.length / 2 }, (_, index) => [
86
+ String(payload[index * 2]), String(payload[index * 2 + 1]),
87
+ ])),
88
+ ttlMs,
89
+ };
90
+ }
91
+
92
+ function parseTimedStringReadResult(result: unknown): TimedRedisValue {
93
+ if (!Array.isArray(result) || result.length !== 2 || !Number.isFinite(Number(result[1]))) {
94
+ throw new Error('Invalid atomic Redis string read result');
95
+ }
96
+ return { raw: result[0] === false || result[0] === null ? null : String(result[0]), ttlMs: Number(result[1]) };
97
+ }
98
+
99
+ /** Read value + PTTL in one atomic, single-key Redis operation where supported. */
58
100
  export async function readRedisValue(client: any, key: string, hash = false): Promise<TimedRedisValue> {
59
101
  if (typeof client.pttl === 'function' && typeof client.multi === 'function') {
60
102
  const transaction = client.multi();
@@ -81,8 +123,8 @@ type PendingOp = PendingGetOp | PendingSetexOp | PendingSetpxOp | PendingDelOp |
81
123
  * Automatically combines individual Redis commands dispatched during the same synchronous
82
124
  * tick of the Node.js event loop into a single `pipeline()` network round-trip.
83
125
  *
84
- * Uses `queueMicrotask` exclusively (never `setImmediate` or timers) to ensure ZERO
85
- * artificial latency penalty (0ms overhead) while slashing network syscalls under high concurrency.
126
+ * Uses `queueMicrotask` rather than a batching timer. Scheduling and command
127
+ * execution still have a cost; timed reads remain atomic within each batch.
86
128
  */
87
129
  export class AutoPipeliner {
88
130
  public readonly maxBatchSize: number;
@@ -129,7 +171,7 @@ export class AutoPipeliner {
129
171
  return readRedisValue(this.client, key, hash);
130
172
  }
131
173
  const probe = typeof this.client.pipeline === 'function' ? this.client.pipeline() : this.client.multi();
132
- if (typeof probe.pttl !== 'function' || (hash && typeof probe.hgetall !== 'function')) {
174
+ if (typeof probe.eval !== 'function') {
133
175
  return readRedisValue(this.client, key, hash);
134
176
  }
135
177
  return new Promise<TimedRedisValue>((resolve, reject) => this.enqueue({ type: 'read', key, hash, resolve, reject }));
@@ -237,10 +279,7 @@ export class AutoPipeliner {
237
279
  case 'setpx': pipe.set(op.key, op.value, 'PX', op.milliseconds); break;
238
280
  case 'del': pipe.del(...op.keys); break;
239
281
  case 'read':
240
- if (op.hash) pipe.hgetall!(op.key);
241
- else pipe.get(op.key);
242
- pipe.pttl!(op.key);
243
- commandCount++;
282
+ pipe.eval!(op.hash ? LUA_TIMED_READ : LUA_TIMED_STRING_READ, 1, op.key);
244
283
  break;
245
284
  }
246
285
  }
@@ -268,9 +307,11 @@ export class AutoPipeliner {
268
307
  op.reject(err instanceof Error ? err : new Error(String(err)));
269
308
  } else {
270
309
  if (op.type === 'read') {
271
- const ttlResult = results[indexes[i] + 1];
272
- if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error('Missing Redis PTTL result'));
273
- else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
310
+ try {
311
+ op.resolve(op.hash ? parseTimedReadResult(val) : parseTimedStringReadResult(val));
312
+ } catch (error) {
313
+ op.reject(error instanceof Error ? error : new Error(String(error)));
314
+ }
274
315
  } else if (op.type === 'get') {
275
316
  op.resolve(val != null ? String(val) : null);
276
317
  } else if (op.type === 'del') {