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
@@ -10,8 +10,9 @@
10
10
  */
11
11
 
12
12
  import type { IRemoteSnapshotAdapter } from './remote-snapshot';
13
+ import { discardSnapshotResponse, readSnapshotResponse, snapshotRequest, type SnapshotRequestOptions, type SnapshotTransferOptions } from './utils/snapshot-transfer.js';
13
14
 
14
- export interface SigV4SnapshotAdapterOptions {
15
+ export interface SigV4SnapshotAdapterOptions extends SnapshotTransferOptions {
15
16
  /** S3 or Cloudflare R2 bucket name */
16
17
  bucket: string;
17
18
  /** Object key / filename for the snapshot (e.g. 'production-l1.snap') */
@@ -77,8 +78,10 @@ export class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
77
78
  private readonly sessionToken?: string;
78
79
  private readonly forcePathStyle: boolean;
79
80
  private readonly fetchImpl: typeof globalThis.fetch;
81
+ private readonly transfer: SnapshotTransferOptions;
80
82
 
81
83
  constructor(options: SigV4SnapshotAdapterOptions) {
84
+ this.transfer = { maxBytes: options.maxBytes, timeoutMs: options.timeoutMs };
82
85
  this.bucket = options.bucket;
83
86
  this.key = options.key.replace(/^\/+/, '');
84
87
  this.region = options.region ?? (options.endpoint?.includes('r2.cloudflarestorage.com') ? 'auto' : 'us-east-1');
@@ -197,37 +200,44 @@ export class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
197
200
  return { headers: finalHeaders, url };
198
201
  }
199
202
 
200
- async get(): Promise<Buffer | null> {
201
- const { headers, url } = await this._buildHeaders('GET');
203
+ async get(request?: SnapshotRequestOptions): Promise<Buffer | null> {
204
+ return snapshotRequest(this.transfer, request, async (signal, maxBytes) => {
205
+ const { headers, url } = await this._buildHeaders('GET');
206
+ signal.throwIfAborted();
207
+
208
+ const res = await this.fetchImpl(url.toString(), {
209
+ method: 'GET',
210
+ headers,
211
+ signal,
212
+ });
213
+
214
+ if (res.status === 404) { discardSnapshotResponse(res); return null; }
215
+ if (!res.ok) {
216
+ discardSnapshotResponse(res);
217
+ throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}`);
218
+ }
202
219
 
203
- const res = await this.fetchImpl(url.toString(), {
204
- method: 'GET',
205
- headers,
220
+ return readSnapshotResponse(res, signal, maxBytes);
206
221
  });
207
-
208
- if (res.status === 404) return null;
209
- if (!res.ok) {
210
- const errBody = await res.text().catch(() => '');
211
- throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
212
- }
213
-
214
- const ab = await res.arrayBuffer();
215
- return Buffer.from(ab);
216
222
  }
217
223
 
218
- async put(data: Buffer): Promise<void> {
219
- const { headers, url } = await this._buildHeaders('PUT', data);
220
-
221
- const res = await this.fetchImpl(url.toString(), {
222
- method: 'PUT',
223
- headers,
224
- body: data as unknown as BodyInit,
224
+ async put(data: Buffer, request?: SnapshotRequestOptions): Promise<void> {
225
+ return snapshotRequest(this.transfer, request, async (signal) => {
226
+ const { headers, url } = await this._buildHeaders('PUT', data);
227
+ signal.throwIfAborted();
228
+
229
+ const res = await this.fetchImpl(url.toString(), {
230
+ method: 'PUT',
231
+ headers,
232
+ body: data as unknown as BodyInit,
233
+ signal,
234
+ });
235
+
236
+ discardSnapshotResponse(res);
237
+ if (!res.ok) {
238
+ throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}`);
239
+ }
225
240
  });
226
-
227
- if (!res.ok) {
228
- const errBody = await res.text().catch(() => '');
229
- throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
230
- }
231
241
  }
232
242
  }
233
243
 
@@ -13,8 +13,10 @@
13
13
  */
14
14
 
15
15
  import { CacheCodec, defaultCodec } from './codec.js';
16
+ import { randomUUID } from 'node:crypto';
16
17
  import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason, WTinyLfuStats } from './types';
17
18
  import { WTinyLfuPolicy } from './wtiny-lfu.js';
19
+ import { isWriteRevision } from './utils/write-revision.js';
18
20
 
19
21
  /**
20
22
  * Packed-byte threshold above which the live JS object is NOT stored alongside the
@@ -254,6 +256,8 @@ export interface SmartMemoryCacheOptions {
254
256
  maxBytes: number;
255
257
  maxEntries: number;
256
258
  categories: Record<string, CategoryLimit>;
259
+ /** Storage-key prefix to skip when matching logical category prefixes. */
260
+ keyPrefixLength?: number;
257
261
  diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
258
262
  onEviction?: (key: string, reason: EvictionReason) => void;
259
263
  logger: ILogger;
@@ -289,6 +293,7 @@ export class SmartMemoryCache {
289
293
  // ── Observability counters ──────────────────────────────────────────────────────
290
294
  private bloomChecks = 0;
291
295
  private bloomFalsePos = 0;
296
+ private bloomAbsentChecks = 0;
292
297
  private compressions = 0; private categoryHits = new Map<string, number>();
293
298
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
294
299
  private _bloomDirtyCount = 0;
@@ -350,7 +355,7 @@ export class SmartMemoryCache {
350
355
 
351
356
  private getCategory(key: string): string {
352
357
  for (const prefix of this.categoryPrefixes) {
353
- if (key.startsWith(prefix)) return prefix;
358
+ if (key.startsWith(prefix, this.opts.keyPrefixLength ?? 0)) return prefix;
354
359
  }
355
360
  return 'default';
356
361
  }
@@ -371,7 +376,7 @@ export class SmartMemoryCache {
371
376
  this._bloomDirtyCount++;
372
377
  const deleted = this.cache.delete(key);
373
378
  if (deleted && this.opts.onEviction) {
374
- try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
379
+ try { void Promise.resolve(this.opts.onEviction(key, reason)).catch(() => {}); } catch { /* never crash cache */ }
375
380
  }
376
381
  return deleted;
377
382
  }
@@ -544,16 +549,12 @@ export class SmartMemoryCache {
544
549
 
545
550
  get(key: string): CacheHit | null {
546
551
  this.bloomChecks++;
547
- if (!this.bloom.mightContain(key)) return null;
552
+ if (!this.bloom.mightContain(key)) { this.bloomAbsentChecks++; return null; }
548
553
  const entry = this.cache.get(key);
549
- if (!entry) { this.bloomFalsePos++; return null; }
554
+ if (!entry) { this.bloomFalsePos++; this.bloomAbsentChecks++; return null; }
550
555
  const now = Date.now();
551
556
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
552
- entry.hits++;
553
- entry.lastAccess = now;
554
- // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
555
- if ((entry.hits & 3) === 0) this.sketch.increment(key);
556
- this.wtinyPolicy?.onAccess(key);
557
+ this.recordAccess(key, entry, now);
557
558
  // value is cached at write time — hot reads return the live object directly,
558
559
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
559
560
  const value = entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
@@ -570,12 +571,22 @@ export class SmartMemoryCache {
570
571
  fetchedAt: now,
571
572
  tagVersions: entry.tagVersions,
572
573
  setAt: entry.setAt,
574
+ revision: entry.revision,
573
575
  tags: entry.tags,
574
576
  dependsOn: entry.dependsOn,
575
577
  };
576
578
  return hit;
577
579
  }
578
580
 
581
+ /** Shared policy accounting for scalar and batch reads. */
582
+ recordAccess(key: string, entry: SmartCacheEntry, now = Date.now()): void {
583
+ if (this.cache.get(key) !== entry) return;
584
+ entry.hits++;
585
+ entry.lastAccess = now;
586
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
587
+ this.wtinyPolicy?.onAccess(key);
588
+ }
589
+
579
590
  set(
580
591
  key: string,
581
592
  data: unknown,
@@ -587,17 +598,39 @@ export class SmartMemoryCache {
587
598
  setAt?: number,
588
599
  tags?: string[],
589
600
  dependsOn?: string[],
601
+ revision: string = randomUUID(),
590
602
  ): boolean {
591
603
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
592
604
  // "size probe" that was discarded for large payloads (the double-pass).
593
- const packed = this.codec.encode(data);
594
- return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
605
+ return this.setPacked(key, this.codec.encode(data), data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
606
+ }
607
+
608
+ /**
609
+ * Store a value when its codec representation is already available.
610
+ * CacheService uses this to share one MessagePack encoding between L1 and
611
+ * Redis/disk writes on an origin fill. The buffer is treated as immutable.
612
+ */
613
+ setPacked(
614
+ key: string,
615
+ packed: Buffer,
616
+ data: unknown,
617
+ ttlMs: number,
618
+ priority: CachePriority = 2 /* NORMAL */,
619
+ staleAt?: number,
620
+ delta?: number,
621
+ tagVersions?: Record<string, number>,
622
+ setAt?: number,
623
+ tags?: string[],
624
+ dependsOn?: string[],
625
+ revision: string = randomUUID(),
626
+ ): boolean {
627
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
595
628
  }
596
629
 
597
630
  private storePacked(
598
631
  key: string, packed: Buffer, data: unknown, ttlMs: number, priority: CachePriority,
599
632
  staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number,
600
- tags?: string[], dependsOn?: string[],
633
+ tags?: string[], dependsOn?: string[], revision?: string,
601
634
  ): boolean {
602
635
  const size = packed.byteLength;
603
636
  this.compressions++;
@@ -643,6 +676,7 @@ export class SmartMemoryCache {
643
676
  ttlMs,
644
677
  delta,
645
678
  setAt: setAt ?? now,
679
+ revision,
646
680
  tagVersions,
647
681
  tags,
648
682
  dependsOn,
@@ -687,7 +721,7 @@ export class SmartMemoryCache {
687
721
  // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
688
722
  // For large entries, get() falls back to the unpack() path transparently.
689
723
  const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
690
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions, tags, dependsOn });
724
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, revision, tagVersions, tags, dependsOn });
691
725
  // Only add new keys to the bloom — overwrites already have their bits set.
692
726
  // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
693
727
  if (!existingEntry) this.bloom.add(key);
@@ -718,7 +752,7 @@ export class SmartMemoryCache {
718
752
  // the Set during the subsequent iteration are safe.
719
753
  if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
720
754
  const prefix = pattern.slice(0, -1);
721
- const catKeys = this.categoryKeys.get(prefix);
755
+ const catKeys = this.categoryKeys.get(prefix.slice(this.opts.keyPrefixLength ?? 0));
722
756
  if (catKeys !== undefined) return Array.from(catKeys);
723
757
  }
724
758
 
@@ -868,7 +902,7 @@ export class SmartMemoryCache {
868
902
  }
869
903
 
870
904
  /**
871
- * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
905
+ * Evict all L1 entries that were written before `cutoffMs`, at every priority.
872
906
  *
873
907
  * Called by the backplane staleness fence when the Pub/Sub subscriber
874
908
  * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
@@ -888,8 +922,6 @@ export class SmartMemoryCache {
888
922
  let evicted = 0;
889
923
  for (const [key, entry] of this.cache) {
890
924
  // Never evict live CRITICAL entries — auth tokens, active sessions, etc.
891
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
892
-
893
925
  // Prefer the explicit setAt timestamp; fall back to approximation for older entries.
894
926
  const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
895
927
 
@@ -907,8 +939,7 @@ export class SmartMemoryCache {
907
939
 
908
940
  /**
909
941
  * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
910
- * Used for concurrency-safe compare-and-delete on stale generational reads,
911
- * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
942
+ * This is a time-based eviction policy; use deleteIfRevision for write identity.
912
943
  */
913
944
  deleteIfSetBefore(key: string, cutoffMs: number): boolean {
914
945
  const entry = this.cache.get(key);
@@ -922,6 +953,11 @@ export class SmartMemoryCache {
922
953
  return false;
923
954
  }
924
955
 
956
+ /** Remove exactly the observed write, even when another write shares its timestamp. */
957
+ deleteIfRevision(key: string, revision: string): boolean {
958
+ if (!isWriteRevision(revision) || this.cache.get(key)?.revision !== revision) return false;
959
+ return this.delete(key);
960
+ }
925
961
 
926
962
 
927
963
  exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
@@ -943,6 +979,7 @@ export class SmartMemoryCache {
943
979
  for (const item of entries) {
944
980
  if (!item || typeof item.key !== 'string' || !item.entry) continue;
945
981
  const { key, entry } = item;
982
+ if (entry.revision !== undefined && !isWriteRevision(entry.revision)) continue;
946
983
  if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
947
984
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
948
985
  if (this.cache.has(key)) continue;
@@ -954,7 +991,7 @@ export class SmartMemoryCache {
954
991
  if (!data) continue;
955
992
  const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
956
993
  if (this.storePacked(key, data, value, entry.expiresAt - now, entry.priority, entry.staleAt,
957
- entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn)) {
994
+ entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn, entry.revision)) {
958
995
  const restored = this.cache.get(key)!;
959
996
  restored.expiresAt = entry.expiresAt;
960
997
  restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
@@ -1056,6 +1093,7 @@ export class SmartMemoryCache {
1056
1093
  bloom: {
1057
1094
  checks: this.bloomChecks,
1058
1095
  falsePositives: this.bloomFalsePos,
1096
+ absentChecks: this.bloomAbsentChecks,
1059
1097
  },
1060
1098
  compression: {
1061
1099
  compressed: this.compressions,
@@ -1108,11 +1146,13 @@ export class SmartMemoryCache {
1108
1146
  * Add additional milliseconds to a key's existing expiry (for stale-if-error).
1109
1147
  * Returns `false` if the key is absent or already expired.
1110
1148
  */
1111
- bumpExpiry(key: string, additionalMs: number): boolean {
1149
+ bumpExpiry(key: string, additionalMs: number, maximumExpiry = Infinity): boolean {
1112
1150
  const entry = this.cache.get(key);
1113
1151
  if (!entry) return false;
1114
1152
  if (entry.expiresAt <= Date.now()) return false;
1115
- entry.expiresAt += additionalMs;
1153
+ const next = Math.min(entry.expiresAt + additionalMs, maximumExpiry);
1154
+ if (next <= entry.expiresAt) return false;
1155
+ entry.expiresAt = next;
1116
1156
  return true;
1117
1157
  }
1118
1158
 
package/src/types.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { RemoteSnapshotOptions } from './remote-snapshot';
2
2
  import type { CrossRegionRelayOptions } from './cross-region';
3
3
  import type { CompressionAlgorithm, CustomCompressor } from './compression';
4
+ import type { OriginCapacityLimiter, OriginCapacityMetrics } from './origin-capacity';
4
5
 
5
6
  /**
6
7
  * tricache — shared types and interfaces
@@ -125,6 +126,8 @@ export interface SmartCacheEntry {
125
126
  * Optional for backward compatibility with snapshots written by older versions.
126
127
  */
127
128
  setAt?: number;
129
+ /** Opaque identity of this write, preserved across tiers and snapshots. */
130
+ revision?: string;
128
131
  /** Active tag versions at write time (used when tagStrategy === 'generational') */
129
132
  tagVersions?: Record<string, number>;
130
133
  /** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
@@ -151,6 +154,7 @@ export interface CacheHit {
151
154
  tagVersions?: Record<string, number>;
152
155
  /** Timestamp (ms) when this entry was written into memory */
153
156
  setAt?: number;
157
+ revision?: string;
154
158
  tags?: string[];
155
159
  dependsOn?: string[];
156
160
  }
@@ -172,6 +176,7 @@ export interface DiskCacheEntry {
172
176
  tagVersions?: Record<string, number>;
173
177
  /** Original write time and TTL, preserved on spill and promotion. */
174
178
  setAt?: number;
179
+ revision?: string;
175
180
  ttlMs?: number;
176
181
  delta?: number;
177
182
  tags?: string[];
@@ -191,6 +196,14 @@ export interface CacheMetrics {
191
196
  /** Milliseconds since the CacheService instance was constructed */
192
197
  uptimeMs: number;
193
198
 
199
+ /** Per-cache admission accounting; active origin work remains reserved until its physical promise settles. */
200
+ work?: {
201
+ origin: { active: number; capacity: number; rejected: number };
202
+ background: { active: number; capacity: number; rejected: number };
203
+ };
204
+ /** Process-shared physical origin budget, when an OriginCapacityLimiter is configured. */
205
+ originCapacity?: OriginCapacityMetrics;
206
+
194
207
  gets: {
195
208
  total: number;
196
209
  l1Hits: number;
@@ -220,6 +233,8 @@ export interface CacheMetrics {
220
233
  errors: number;
221
234
  /** Times a later `create(ns)` call passed options diverging from the live singleton. */
222
235
  singletonDivergences: number;
236
+ /** Cached reads rejected because strict invalidation protection was active. */
237
+ invalidationReadRejections?: number;
223
238
  };
224
239
 
225
240
  bloom: {
@@ -245,6 +260,18 @@ export interface CacheMetrics {
245
260
  backplane: {
246
261
  enabled: boolean;
247
262
  mode: 'pubsub' | 'stream';
263
+ /** True when cached values are rejected while the invalidation consumer is unavailable. */
264
+ readProtectionEnabled?: boolean;
265
+ /** Current strict-read protection state. */
266
+ readProtectionActive?: boolean;
267
+ /** Sanitized reason for the current protection state, when active. */
268
+ readProtectionReason?: string;
269
+ /** Date.now() timestamp when the current protection state began. */
270
+ readProtectionSince?: number | null;
271
+ /** Monotonic elapsed milliseconds while the read gate is closed (zero when open). */
272
+ readProtectionDurationMs?: number;
273
+ /** Configured consumer proof deadline when strict protection is enabled. */
274
+ readProtectionDeadlineMs?: number;
248
275
  /** Invalidation messages published to other instances */
249
276
  sent: number;
250
277
  /** Invalidation messages received from other instances */
@@ -371,6 +398,18 @@ export type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterp
371
398
  * All fields are optional — sensible defaults are used when omitted.
372
399
  */
373
400
  export interface CacheOptions {
401
+ /** Optional process-wide origin budget shared with other caches and direct-origin fallback. */
402
+ originCapacityLimiter?: OriginCapacityLimiter;
403
+ /** Maximum concurrent origin invocations (batch calls reserve one slot per owned key). Default: 1024. Saturated misses reject; no queue. */
404
+ maxConcurrentFetches?: number;
405
+ /** Maximum concurrent background refreshes, also subject to maxConcurrentFetches. Default: 64. */
406
+ maxBackgroundRefreshes?: number;
407
+ /** Maximum unique stored/pending dependency edges per instance. Default: 100000. */
408
+ maxDependencyEdges?: number;
409
+ /** Maximum outstanding serialization tasks, including pools draining during rotation. Default: 256. */
410
+ workerMaxPendingTasks?: number;
411
+ /** Outstanding worker input/context admission across rotation. Default: 64 MiB; not total process memory. */
412
+ workerMaxPendingBytes?: number;
374
413
  /**
375
414
  * Plug in your own logger (pino, winston, bunyan, …).
376
415
  * Defaults to a minimal console logger that only prints warn/error.
@@ -403,7 +442,7 @@ export interface CacheOptions {
403
442
  * - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
404
443
  * mathematical scan resistance and burst recency absorption.
405
444
  * - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
406
- * Default: `'wtinylfu'`
445
+ * Default: `'adaptive'`; all built-in presets explicitly select `'wtinylfu'`.
407
446
  */
408
447
  l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
409
448
 
@@ -488,7 +527,7 @@ export interface CacheOptions {
488
527
  /**
489
528
  * Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
490
529
  * Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
491
- * Default: false
530
+ * Default: true
492
531
  */
493
532
  autoPipeline?: boolean;
494
533
  /**
@@ -569,9 +608,12 @@ export interface CacheOptions {
569
608
  */
570
609
  strictKeyValidation?: boolean;
571
610
 
611
+ /** Permit legacy context-free ciphertext/plaintext reads during a deliberate migration. Default: false. */
612
+ allowLegacyPlaintextRead?: boolean;
613
+
572
614
  // ── Serialization & Codec (msgpackr) ────────────────────────────────────
573
615
  /**
574
- * Whether to call `.toJSON()` when serializing objects into binary cache buffers.
616
+ * Whether to call `.toJSON()` when serializing objects for packed buffers and Redis.
575
617
  * - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
576
618
  * - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
577
619
  * avoiding accidental API response projections on cached domain entities.
@@ -606,7 +648,7 @@ export interface CacheOptions {
606
648
  // ── Snapshot ────────────────────────────────────────────────────────────
607
649
  /**
608
650
  * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
609
- * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
651
+ * on startup. Default: os.tmpdir()/tricache-snapshot-v3-<namespace-hex>.msgpack
610
652
  */
611
653
  snapshotPath?: string;
612
654
  /**
@@ -620,24 +662,16 @@ export interface CacheOptions {
620
662
  remoteSnapshot?: RemoteSnapshotOptions;
621
663
 
622
664
  /**
623
- * Optional namespace prefix for all cache keys.
624
- *
625
- * When set, every key is transparently stored as `${namespace}:${key}` in
626
- * L1, L1.5 (disk), and L2 (Redis). This enables:
627
- * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
628
- * — tenants sharing the same Redis instance or disk dir are fully isolated.
629
- * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
630
- * - **Service-level scoping**: microservices sharing one Redis without key collisions.
631
- *
632
- * Consumers never see the prefix — `get('user:1')` behaves identically
633
- * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
634
- * scope to the namespace.
665
+ * Namespace identifier used to derive collision-free, versioned storage keys
666
+ * across L1, disk, Redis, invalidation, and snapshots. The identifier is trimmed.
667
+ * Consumers continue to use logical keys such as `get('user:1')`.
635
668
  *
636
- * The process-level singleton, disk cache directory, and cold-start snapshot
637
- * path are all scoped per namespace, so two `CacheService.create()` calls
638
- * with different namespaces return completely independent instances.
669
+ * The v3 format separates data, tag sets, tag versions, and locks. It does not
670
+ * read earlier raw/colon-prefixed or v2 entries as a fallback. Upgrades start
671
+ * cold; coordinate all writers onto v3 or isolate storage during rollout.
639
672
  *
640
- * Default: `''` (no prefix)
673
+ * Use separate Node and Edge namespaces: their value formats are not interoperable.
674
+ * Default: `''` (the default namespace, also stored under the v3 format).
641
675
  */
642
676
  namespace?: string;
643
677
 
@@ -706,6 +740,18 @@ export interface CacheOptions {
706
740
  */
707
741
  awaitInvalidationBackplane?: boolean;
708
742
 
743
+ /**
744
+ * Reject cached reads while the invalidation consumer is unavailable or has
745
+ * missed its heartbeat deadline. The caller can catch
746
+ * `CacheInvalidationUnavailableError` and use an authoritative origin route.
747
+ * This is opt-in; `false` preserves the default availability-first behavior.
748
+ * Requires active Redis/invalidation, a supported dedicated subscriber, and a
749
+ * finite positive `backplaneMaxStalenessMs` detection deadline. Reads/fills
750
+ * spanning a gate closure reject even if the consumer recovers meanwhile.
751
+ * Strict startup skips snapshot hydration and discards existing local spill.
752
+ */
753
+ rejectCachedReadsOnInvalidationLoss?: boolean;
754
+
709
755
  /**
710
756
  * If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
711
757
  * encounters a connection or runtime error during lock acquisition, preventing
@@ -860,17 +906,19 @@ export interface CacheOptions {
860
906
 
861
907
  /**
862
908
  * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
863
- * and automatically derives an optimal TTL from the p95 fetch duration:
909
+ * and derives a cost-based TTL from the p95 fetch duration:
864
910
  *
865
911
  * ```
866
- * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
912
+ * adaptedTtlMs = clamp(round(p95LatencyMs × adaptiveTtlMultiplier),
913
+ * adaptiveTtlMin × 1000, adaptiveTtlMax × 1000)
867
914
  * ```
868
915
  *
869
916
  * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
870
917
  * for a key, then the library takes over TTL management autonomously.
871
918
  *
872
- * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
873
- * their base TTL. Callers no longer need to reason about individual TTL values.
919
+ * More expensive keys receive longer derived TTLs than cheaper keys, subject
920
+ * to the configured bounds. Fetch latency does not establish data freshness:
921
+ * choose adaptiveTtlMin/Max to match your application's stale-data tolerance.
874
922
  *
875
923
  * Default: `false`.
876
924
  */
@@ -891,11 +939,13 @@ export interface CacheOptions {
891
939
  adaptiveTtlMax?: number;
892
940
 
893
941
  /**
894
- * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
942
+ * Dimensionless factor: `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlMs`
943
+ * before applying the minimum and maximum (configured in seconds).
895
944
  *
896
945
  * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
897
- * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
898
- * if you want the cache to absorb more upstream pressure.
946
+ * 4-second derived TTL, raised to 10 seconds by the default minimum.
947
+ * A 2 000 ms fetch yields 40 seconds. Increase the multiplier if you want
948
+ * the cache to absorb more upstream pressure, within your freshness bounds.
899
949
  *
900
950
  * Default: `20`.
901
951
  */
@@ -919,12 +969,11 @@ export interface CacheOptions {
919
969
 
920
970
  // ── Worker-thread serialization offload ────────────────────────────────────
921
971
  /**
922
- * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
923
- * encryption and decryption for large payloads to those threads, keeping the
924
- * V8 main event loop free for concurrent HTTP requests.
972
+ * When `true`, tricache spawns a pool of worker threads and offloads
973
+ * compression and encryption/decryption of large Redis payloads.
925
974
  *
926
- * Only takes effect when `encryptionKey` is set — plaintext payloads are never
927
- * serialized off-thread because `JSON.stringify/parse` is already fast.
975
+ * MessagePack encode/decode remains on the calling thread. Compression can
976
+ * run in workers even without encryption; custom compressors run locally.
928
977
  *
929
978
  * Default: `false`. Enable in long-running servers that write multi-megabyte
930
979
  * encrypted payloads and observe event-loop latency spikes.
@@ -955,6 +1004,9 @@ export interface CacheOptions {
955
1004
  *
956
1005
  * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
957
1006
  * Default: `5000` (5 seconds).
1007
+ * With `rejectCachedReadsOnInvalidationLoss`, this also bounds silent loss
1008
+ * detection since the send time of the last acknowledged consumer challenge.
1009
+ * Strict mode requires a finite positive value and uses monotonic elapsed time.
958
1010
  */
959
1011
  backplaneMaxStalenessMs?: number;
960
1012
 
@@ -1100,8 +1152,8 @@ export interface CacheOptions {
1100
1152
  backplaneStreamBlockMs?: number;
1101
1153
 
1102
1154
  /**
1103
- * Custom Redis Stream key name.
1104
- * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
1155
+ * Custom Redis Stream key base. TriCache adds a namespace-specific suffix so
1156
+ * streams remain isolated. The default is hash-tagged for Redis Cluster routing.
1105
1157
  */
1106
1158
  backplaneStreamKey?: string;
1107
1159
 
@@ -1136,7 +1188,11 @@ export interface WrapOptions {
1136
1188
  priority?: CachePriority;
1137
1189
  /** Semantic tags for invalidation. */
1138
1190
  tags?: string[];
1139
- /** Dependency cascade patterns (e.g. `['user:*']`). */
1191
+ /**
1192
+ * Logical source-key patterns (e.g. `['user:*']`) for transitive exact-key
1193
+ * invalidation. Discovery uses process-local entry metadata and active writers;
1194
+ * it is not a shared fleet-wide dependency index.
1195
+ */
1140
1196
  dependsOn?: string[];
1141
1197
  /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
1142
1198
  refreshAhead?: number;
@@ -1243,6 +1299,7 @@ export interface IRedisDriver {
1243
1299
  scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
1244
1300
  scanStream?(options?: { match?: string; count?: number }): any;
1245
1301
  hset?(key: string, value: Record<string, string>): Promise<unknown>;
1302
+ /** Enables tagged hash envelopes, preserving tags/deadlines on cold reads and touch(). */
1246
1303
  hgetall?(key: string): Promise<Record<string, string>>;
1247
1304
  publish?(channel: string, message: string): Promise<number>;
1248
1305
  subscribe?(...channels: string[]): Promise<unknown>;
@@ -0,0 +1,29 @@
1
+ // Opaque resources retain identity. Plain configuration containers are copied so
2
+ // mutating the caller's object later cannot rewrite the singleton's baseline.
3
+ const IDENTITY_KEYS = new Set(['redisClient', 'redisSubClient', 'originCapacityLimiter', 'logger', 'tracer', 'meter', 'adapter', 'relay']);
4
+
5
+ export function captureConfiguration(value: unknown, key = '', seen = new WeakMap<object, unknown>()): any {
6
+ if (value === null || typeof value !== 'object' || IDENTITY_KEYS.has(key)) return value;
7
+ const prototype = Object.getPrototypeOf(value);
8
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return value;
9
+ if (seen.has(value)) return seen.get(value);
10
+ const result: any = Array.isArray(value) ? [] : Object.create(null);
11
+ seen.set(value, result);
12
+ for (const field of Object.keys(value)) result[field] = captureConfiguration((value as any)[field], field, seen);
13
+ return result;
14
+ }
15
+
16
+ export function sameConfiguration(a: unknown, b: unknown, key = '', seen = new WeakMap<object, WeakSet<object>>()): boolean {
17
+ if (Object.is(a, b)) return true;
18
+ if (IDENTITY_KEYS.has(key) || a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
19
+ const plain = (value: object) => Array.isArray(value) || [null, Object.prototype].includes(Object.getPrototypeOf(value));
20
+ if (!plain(a) || !plain(b) || Array.isArray(a) !== Array.isArray(b)) return false;
21
+ if (Array.isArray(a) && a.length !== (b as unknown[]).length) return false;
22
+ const pairs = seen.get(a) ?? new WeakSet<object>();
23
+ if (pairs.has(b)) return true;
24
+ pairs.add(b);
25
+ seen.set(a, pairs);
26
+ const keys = Object.keys(a).sort(), other = Object.keys(b).sort();
27
+ return keys.length === other.length && keys.every((field, index) => field === other[index] &&
28
+ sameConfiguration((a as any)[field], (b as any)[field], field, seen));
29
+ }