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
@@ -14,6 +14,7 @@ const MIN_CF_KV_TTL = 60; // Cloudflare KV requires expirationTtl >= 60s
14
14
  * TTLs in a lightweight timestamp envelope and validating expiry on read.
15
15
  */
16
16
  export class CloudflareKVAdapter implements IEdgeRemoteStorage {
17
+ readonly tagConsistency = 'eventual' as const;
17
18
  private readonly kv: CloudflareKVNamespace;
18
19
 
19
20
  constructor(kv: CloudflareKVNamespace) {
@@ -77,21 +78,23 @@ export class CloudflareKVAdapter implements IEdgeRemoteStorage {
77
78
  await Promise.all(keys.map(k => this.set(k, entries[k], ttlSeconds)));
78
79
  }
79
80
 
80
- async clear(prefix?: string): Promise<void> {
81
- if (!this.kv.list) return;
82
-
81
+ async *scanKeys(prefix: string): AsyncIterable<string> {
82
+ if (!this.kv.list) throw new Error('Workers KV binding does not support list');
83
83
  let cursor: string | undefined;
84
84
  do {
85
- const res = await this.kv.list({ prefix, cursor });
86
- if (res.keys.length > 0) {
87
- await Promise.all(res.keys.map(item => this.kv.delete(item.name)));
88
- }
85
+ const res = await this.kv.list({ prefix, cursor, limit: 256 });
86
+ for (const item of res.keys) if (item.name.startsWith(prefix)) yield item.name;
89
87
  cursor = res.list_complete ? undefined : res.cursor;
88
+ if (!res.list_complete && !cursor) throw new Error('Workers KV list omitted its continuation cursor');
90
89
  } while (cursor);
91
90
  }
92
91
 
92
+ async clear(prefix = ''): Promise<void> {
93
+ for await (const key of this.scanKeys(prefix)) await this.kv.delete(key);
94
+ }
95
+
93
96
  async incrementTagVersion(tag: string): Promise<number> {
94
- const key = `tag_ver:${tag}`;
97
+ const key = tag;
95
98
  const raw = await this.kv.get(key);
96
99
  const prev = raw ? parseInt(raw, 10) || 0 : 0;
97
100
  const nextVer = Math.max(prev + 1, Date.now());
@@ -100,7 +103,7 @@ export class CloudflareKVAdapter implements IEdgeRemoteStorage {
100
103
  }
101
104
 
102
105
  async getTagVersion(tag: string): Promise<number> {
103
- const raw = await this.kv.get(`tag_ver:${tag}`);
106
+ const raw = await this.kv.get(tag);
104
107
  return raw ? parseInt(raw, 10) || 1 : 1;
105
108
  }
106
109
 
@@ -7,9 +7,11 @@ import type { IEdgeRemoteStorage, UpstashRedisOptions } from '../types';
7
7
  * Communicates over HTTPS REST with zero native socket dependencies.
8
8
  */
9
9
  export class UpstashRedisAdapter implements IEdgeRemoteStorage {
10
+ readonly tagConsistency = 'atomic' as const;
10
11
  private readonly baseUrl: string;
11
12
  private readonly token: string;
12
13
  private readonly customFetch: typeof globalThis.fetch;
14
+ private readonly dangerouslyFlushDatabase: boolean;
13
15
 
14
16
  constructor(options: UpstashRedisOptions) {
15
17
  if (!options?.url || !options?.token) {
@@ -18,6 +20,7 @@ export class UpstashRedisAdapter implements IEdgeRemoteStorage {
18
20
  this.baseUrl = options.url.replace(/\/+$/, '');
19
21
  this.token = options.token;
20
22
  this.customFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
23
+ this.dangerouslyFlushDatabase = options.dangerouslyFlushDatabase ?? false;
21
24
  }
22
25
 
23
26
  private async _executeCommand<T = unknown>(command: unknown[]): Promise<T> {
@@ -107,32 +110,45 @@ export class UpstashRedisAdapter implements IEdgeRemoteStorage {
107
110
  }
108
111
  }
109
112
 
113
+ async *scanKeys(prefix: string): AsyncIterable<string> {
114
+ const pattern = prefix.replaceAll('\\', '\\\\').replaceAll('*', '\\*')
115
+ .replaceAll('?', '\\?').replaceAll('[', '\\[').replaceAll(']', '\\]') + '*';
116
+ let cursor = '0';
117
+ do {
118
+ const result = await this._executeCommand<[string, string[]]>(['SCAN', cursor, 'MATCH', pattern, 'COUNT', 256]);
119
+ if (!Array.isArray(result) || !Array.isArray(result[1])) throw new Error('Invalid Upstash SCAN response');
120
+ cursor = String(result[0]);
121
+ for (const key of result[1]) if (key.startsWith(prefix)) yield key;
122
+ } while (cursor !== '0');
123
+ }
124
+
110
125
  async clear(prefix?: string): Promise<void> {
111
- if (prefix) {
112
- const pattern = prefix.endsWith('*') ? prefix : `${prefix}*`;
113
- const keys = await this._executeCommand<string[]>(['KEYS', pattern]);
114
- if (Array.isArray(keys) && keys.length > 0) {
115
- await this._executeCommand(['DEL', ...keys]);
116
- }
117
- } else {
126
+ if (!prefix) {
127
+ if (!this.dangerouslyFlushDatabase) throw new Error('Unscoped Upstash clear requires dangerouslyFlushDatabase: true');
118
128
  await this._executeCommand(['FLUSHDB']);
129
+ return;
130
+ }
131
+ let keys: string[] = [];
132
+ for await (const key of this.scanKeys(prefix)) {
133
+ keys.push(key);
134
+ if (keys.length === 256) { await this._executeCommand(['DEL', ...keys]); keys = []; }
119
135
  }
136
+ if (keys.length) await this._executeCommand(['DEL', ...keys]);
120
137
  }
121
138
 
122
139
  async incrementTagVersion(tag: string): Promise<number> {
123
- const res = await this._executeCommand<number>(['INCR', `tag_ver:${tag}`]);
140
+ const res = await this._executeCommand<number>(['INCR', tag]);
124
141
  return typeof res === 'number' ? res : 1;
125
142
  }
126
143
 
127
144
  async getTagVersion(tag: string): Promise<number> {
128
- const res = await this._executeCommand<string | null>(['GET', `tag_ver:${tag}`]);
145
+ const res = await this._executeCommand<string | null>(['GET', tag]);
129
146
  return res ? parseInt(res, 10) || 1 : 1;
130
147
  }
131
148
 
132
149
  async batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
133
150
  if (tags.length === 0) return {};
134
- const keys = tags.map(t => `tag_ver:${t}`);
135
- const res = await this.mget(keys);
151
+ const res = await this.mget(tags);
136
152
  const result: Record<string, number> = {};
137
153
  for (let i = 0; i < tags.length; i++) {
138
154
  const raw = res[i];
package/src/edge/cache.ts CHANGED
@@ -14,6 +14,7 @@ import { WebCryptoEncryption } from './crypto';
14
14
  import { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
15
15
  import { Murmur3BloomFilter } from './utils/murmur3';
16
16
  import { isWildcardTag, matchesTagPattern, isChildTag } from '../utils/tag-matcher';
17
+ import { namespaceDomainPrefix, namespaceKeyPrefix } from '../utils/namespace-key';
17
18
 
18
19
  interface EdgeL1Entry<T = unknown> {
19
20
  value: T;
@@ -44,6 +45,9 @@ export class EdgeCacheService {
44
45
  private readonly maxBytes: number;
45
46
  private readonly defaultTtl: number;
46
47
  private readonly namespace: string;
48
+ private readonly namespacePrefix: string;
49
+ private readonly dataPrefix: string;
50
+ private readonly tagVersionPrefix: string;
47
51
  private readonly remoteStorage: IEdgeRemoteStorage | null;
48
52
  private readonly enc: WebCryptoEncryption;
49
53
  private readonly tracer: ICacheTracer | null;
@@ -73,6 +77,9 @@ export class EdgeCacheService {
73
77
  this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024; // 32 MB
74
78
  this.defaultTtl = options?.defaultTtlSeconds ?? 300;
75
79
  this.namespace = options?.namespace?.trim() ?? '';
80
+ this.namespacePrefix = namespaceKeyPrefix(this.namespace);
81
+ this.dataPrefix = namespaceDomainPrefix(this.namespace, 'data');
82
+ this.tagVersionPrefix = namespaceDomainPrefix(this.namespace, 'tag-version');
76
83
  this.remoteStorage = options?.remoteStorage ?? null;
77
84
  this.tracer = options?.tracer ?? null;
78
85
  this.enc = new WebCryptoEncryption(options?.encryption);
@@ -101,7 +108,11 @@ export class EdgeCacheService {
101
108
  }
102
109
 
103
110
  private nk(key: string): string {
104
- return this.namespace ? `${this.namespace}:${key}` : key;
111
+ return `${this.dataPrefix}${key}`;
112
+ }
113
+
114
+ private tagVersionKey(tag: string): string {
115
+ return `${this.tagVersionPrefix}${tag}`;
105
116
  }
106
117
 
107
118
  private _estimateBytes(key: string, serialized: string): number {
@@ -148,6 +159,9 @@ export class EdgeCacheService {
148
159
  tags: options?.tags ? [...new Set(options.tags)] : undefined, tagVersions: versions };
149
160
  this.storeL1(namespaced, entry);
150
161
  if (this.remoteStorage) {
162
+ // Independent immutable markers never overwrite a concurrent generation.
163
+ const registry = namespaceDomainPrefix(this.namespace, 'tag-registry');
164
+ for (const tag of entry.tags ?? []) await this.remoteStorage.set(`${registry}${tag}`, '1');
151
165
  const envelope = JSON.stringify({ __t_edge: 2, __t_val: value, __t_tv: versions, __t_exp: entry.expiresAt,
152
166
  __t_stale: entry.staleUntil, __t_tags: entry.tags });
153
167
  const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
@@ -231,9 +245,9 @@ export class EdgeCacheService {
231
245
  if (this.remoteStorage) {
232
246
  try {
233
247
  if (typeof this.remoteStorage.getTagVersion === 'function') {
234
- version = await this.remoteStorage.getTagVersion(this.nk(tag));
248
+ version = await this.remoteStorage.getTagVersion(this.tagVersionKey(tag));
235
249
  } else {
236
- const raw = await this.remoteStorage.get(this.nk(`tag_ver:${tag}`));
250
+ const raw = await this.remoteStorage.get(this.tagVersionKey(tag));
237
251
  version = raw ? parseInt(raw, 10) || 1 : 1;
238
252
  }
239
253
  } catch {
@@ -263,11 +277,11 @@ export class EdgeCacheService {
263
277
  if (missingTags.length > 0 && this.remoteStorage) {
264
278
  try {
265
279
  if (typeof this.remoteStorage.batchGetTagVersions === 'function') {
266
- const nsTags = missingTags.map(t => this.nk(t));
280
+ const nsTags = missingTags.map(t => this.tagVersionKey(t));
267
281
  const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
268
282
  for (let i = 0; i < missingTags.length; i++) {
269
283
  const t = missingTags[i];
270
- const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
284
+ const v = remoteVersions[this.tagVersionKey(t)] ?? 1;
271
285
  result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
272
286
  this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
273
287
  }
@@ -555,11 +569,11 @@ export class EdgeCacheService {
555
569
  if (this.remoteStorage) {
556
570
  try {
557
571
  if (typeof this.remoteStorage.incrementTagVersion === 'function') {
558
- newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
559
- if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
572
+ newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
573
+ if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
560
574
  newVer = Math.max(previous + 1, newVer);
561
575
  } else {
562
- const key = this.nk(`tag_ver:${tag}`);
576
+ const key = this.tagVersionKey(tag);
563
577
  const current = await this._getTagVersion(tag);
564
578
  newVer = Math.max(current + 1, Date.now());
565
579
  await this.remoteStorage.set(key, String(newVer));
@@ -598,6 +612,9 @@ export class EdgeCacheService {
598
612
  const isPattern = isWildcardTag(tag);
599
613
  const shouldCascade = Boolean(opts?.cascade);
600
614
  if (isPattern || shouldCascade) {
615
+ if (this.remoteStorage && !this.remoteStorage.scanKeys) {
616
+ throw new Error('Remote wildcard/cascade tag invalidation requires an adapter with scanKeys');
617
+ }
601
618
  const matched = new Set<string>();
602
619
  const tagMatches = (t: string) => {
603
620
  if (t === tag) return true;
@@ -611,6 +628,14 @@ export class EdgeCacheService {
611
628
  for (const t of this.tagVersionCache.keys()) {
612
629
  if (tagMatches(t)) matched.add(t);
613
630
  }
631
+ if (this.remoteStorage?.scanKeys) {
632
+ const registry = namespaceDomainPrefix(this.namespace, 'tag-registry');
633
+ for await (const key of this.remoteStorage.scanKeys(registry)) {
634
+ if (!key.startsWith(registry)) continue;
635
+ const concrete = key.slice(registry.length);
636
+ if (tagMatches(concrete)) matched.add(concrete);
637
+ }
638
+ }
614
639
  if (shouldCascade && !isPattern) matched.add(tag);
615
640
  for (const t of matched) {
616
641
  await this._invalidateConcreteTag(t);
@@ -644,7 +669,7 @@ export class EdgeCacheService {
644
669
  this.bloomFilter.reset();
645
670
  }
646
671
  if (this.remoteStorage) {
647
- await this.remoteStorage.clear?.(this.namespace ? this.namespace + ':' : undefined);
672
+ await this.remoteStorage.clear?.(this.dataPrefix);
648
673
  }
649
674
  this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
650
675
  await this._invalidateConcreteTag(NAMESPACE_TAG);
@@ -720,9 +745,8 @@ export class EdgeCacheService {
720
745
 
721
746
  for (const [nsKey, entry] of this.l1.entries()) {
722
747
  if (entry.expiresAt > now || entry.staleUntil > now) {
723
- const cleanKey = this.namespace && nsKey.startsWith(this.namespace + ':')
724
- ? nsKey.slice(this.namespace.length + 1)
725
- : nsKey;
748
+ if (!nsKey.startsWith(this.dataPrefix)) continue;
749
+ const cleanKey = nsKey.slice(this.dataPrefix.length);
726
750
 
727
751
  entries.push({
728
752
  key: cleanKey,
@@ -736,7 +760,8 @@ export class EdgeCacheService {
736
760
  }
737
761
 
738
762
  const payload: EdgeSnapshotPayload = {
739
- version: 1,
763
+ version: 3,
764
+ namespace: this.namespacePrefix,
740
765
  writtenAt: now,
741
766
  entries,
742
767
  };
@@ -812,7 +837,8 @@ export class EdgeCacheService {
812
837
  return 0; // Malformed JSON -> fallback cold
813
838
  }
814
839
 
815
- if (!payload || payload.version !== 1 || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
840
+ if (!payload || payload.version !== 3 || payload.namespace !== this.namespacePrefix ||
841
+ !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
816
842
  return 0;
817
843
  }
818
844
 
@@ -835,13 +861,29 @@ export class EdgeCacheService {
835
861
 
836
862
  let imported = 0;
837
863
  for (const item of payload.entries) {
864
+ // Malformed entries are skipped individually and never mutate resident
865
+ // state. Validation happens before the size estimate, which previously
866
+ // threw on a missing value after earlier entries had already imported.
838
867
  if (!item || typeof item.key !== 'string') continue;
839
- // Skip if completely expired
868
+ if (!Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
840
869
  if (item.expiresAt <= now && item.staleUntil <= now) continue;
870
+ if (item.value === undefined) continue;
871
+ if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.some(tag => typeof tag !== 'string'))) continue;
872
+ if (item.tagVersions !== undefined &&
873
+ (typeof item.tagVersions !== 'object' || item.tagVersions === null || Array.isArray(item.tagVersions) ||
874
+ Object.values(item.tagVersions).some(version => !Number.isFinite(version)))) continue;
875
+
876
+ let serialized: string;
877
+ try {
878
+ const encoded = JSON.stringify(item.value);
879
+ if (typeof encoded !== 'string') continue;
880
+ serialized = encoded;
881
+ } catch {
882
+ continue; // Unencodable values (cycles, BigInt) are skipped, not fatal.
883
+ }
841
884
 
842
885
  const nsKey = this.nk(item.key);
843
- if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey) || !Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
844
- const serialized = JSON.stringify(item.value);
886
+ if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey)) continue;
845
887
  const bytes = this._estimateBytes(nsKey, serialized);
846
888
  if (bytes > this.maxBytes || this.maxKeys === 0) continue;
847
889
 
package/src/edge/types.ts CHANGED
@@ -22,13 +22,19 @@ export interface IEdgeRemoteStorage {
22
22
  /** Optional clear by prefix or all keys. */
23
23
  clear?(prefix?: string): Promise<void>;
24
24
 
25
- /** Optional atomic or monotonic tag version increment for generational tag invalidation. */
25
+ /** Enumerate complete keys under a literal prefix in bounded pages. Required for remote wildcard tags. */
26
+ scanKeys?(prefix: string): AsyncIterable<string>;
27
+
28
+ /** Counter semantics; Workers KV is eventually consistent, not an atomic authority. */
29
+ readonly tagConsistency?: 'atomic' | 'eventual';
30
+
31
+ /** Optional atomic or monotonic tag increment. The service supplies the complete typed storage key; adapters must use it unchanged. */
26
32
  incrementTagVersion?(tag: string): Promise<number>;
27
33
 
28
- /** Optional tag version retrieval. */
34
+ /** Optional tag version retrieval by complete typed storage key. */
29
35
  getTagVersion?(tag: string): Promise<number>;
30
36
 
31
- /** Optional batch tag version retrieval. */
37
+ /** Optional batch tag retrieval; result keys must match the complete supplied storage keys. */
32
38
  batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
33
39
  }
34
40
 
@@ -84,7 +90,7 @@ export interface EdgeCacheOptions {
84
90
  mode?: 'aes-256-gcm' | 'aes-128-gcm';
85
91
  };
86
92
 
87
- /** Multi-tenant key namespace prefix. */
93
+ /** Namespace encoded into a v3 storage keyspace with disjoint data/tag domains. Upgrades start cold; coordinate writers. Use a separate namespace from Node, whose value format differs. */
88
94
  namespace?: string;
89
95
 
90
96
  /** OpenTelemetry-compatible tracer for distributed tracing. */
@@ -125,6 +131,8 @@ export interface UpstashRedisOptions {
125
131
 
126
132
  /** Optional custom fetch implementation (defaults to globalThis.fetch). */
127
133
  fetch?: typeof globalThis.fetch;
134
+ /** Allow an explicit unscoped clear() to execute FLUSHDB. Default: false. */
135
+ dangerouslyFlushDatabase?: boolean;
128
136
  }
129
137
 
130
138
  /**
@@ -151,7 +159,7 @@ export interface CloudflareDOStorage {
151
159
  put<T = unknown>(entries: Record<string, T>): Promise<void>;
152
160
  delete(key: string): Promise<boolean>;
153
161
  delete(keys: string[]): Promise<number>;
154
- list?<T = unknown>(options?: { prefix?: string; limit?: number }): Promise<Map<string, T>>;
162
+ list?<T = unknown>(options?: { prefix?: string; limit?: number; startAfter?: string }): Promise<Map<string, T>>;
155
163
  }
156
164
 
157
165
  /**
@@ -220,6 +228,8 @@ export interface EdgeExportSnapshotOptions {
220
228
  */
221
229
  export interface EdgeSnapshotPayload {
222
230
  version: number;
231
+ /** Encoded storage namespace identity, not the raw namespace option. */
232
+ namespace: string;
223
233
  writtenAt: number;
224
234
  entries: Array<{
225
235
  key: string;
package/src/encryption.ts CHANGED
@@ -57,6 +57,8 @@ const TAG_BYTES = 16; // 128-bit auth tag
57
57
  // ── Redis prefixes ────────────────────────────────────────────────────────────
58
58
  const PREFIX_256 = 'enc:v1:'; // AES-256-GCM (legacy-compatible)
59
59
  const PREFIX_128 = 'a128:v1:'; // AES-128-GCM
60
+ const PREFIX_BOUND_256 = 'enc:v2:'; // GCM with caller-supplied authenticated context
61
+ const PREFIX_BOUND_128 = 'a128:v2:';
60
62
  const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
61
63
 
62
64
  // ── Binary magic headers (8 bytes each) ──────────────────────────────────────
@@ -64,6 +66,8 @@ const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
64
66
  const MAGIC_256 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x45, 0x4e, 0x43]);
65
67
  /** "TRIC1128" — AES-128-GCM disk blob */
66
68
  const MAGIC_128 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x31, 0x32, 0x38]);
69
+ const MAGIC_BOUND_256 = Buffer.from('TRIC2ENC');
70
+ const MAGIC_BOUND_128 = Buffer.from('TRIC2128');
67
71
  /** "TRIC1XOR" — XOR-obfuscated disk blob */
68
72
  const MAGIC_XOR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x58, 0x4f, 0x52]);
69
73
  /** "TRIC1CTR" — AES-128-CTR disk blob */
@@ -86,6 +90,7 @@ export class CacheEncryption {
86
90
  private _mode: EncryptionMode;
87
91
  /** Fail-closed on invalid key material when opted in via constructor opts. */
88
92
  private readonly _strictKeyValidation: boolean;
93
+ private readonly _allowLegacyPlaintextRead: boolean;
89
94
  private _prevKey: Buffer | null = null;
90
95
  private _prevKeyObj: KeyObject | null = null;
91
96
  private _prevMode: EncryptionMode = 'aes-256-gcm';
@@ -172,7 +177,7 @@ export class CacheEncryption {
172
177
  mode: EncryptionMode = 'aes-256-gcm',
173
178
  previousKeyBase64?: string,
174
179
  previousMode?: EncryptionMode,
175
- opts?: { strictKeyValidation?: boolean },
180
+ opts?: { strictKeyValidation?: boolean; allowLegacyPlaintextRead?: boolean },
176
181
  ) {
177
182
  const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
178
183
  ? loggerOrMode
@@ -181,6 +186,7 @@ export class CacheEncryption {
181
186
  ? loggerOrMode
182
187
  : mode;
183
188
  this._strictKeyValidation = opts?.strictKeyValidation ?? false;
189
+ this._allowLegacyPlaintextRead = opts?.allowLegacyPlaintextRead ?? true;
184
190
 
185
191
  this._mode = resolvedMode;
186
192
  if (keyBase64 === undefined || keyBase64 === null) {
@@ -277,12 +283,14 @@ export class CacheEncryption {
277
283
  mode: EncryptionMode;
278
284
  prevKeyBase64: string | undefined;
279
285
  prevMode: EncryptionMode;
286
+ allowLegacyPlaintextRead: boolean;
280
287
  } {
281
288
  return {
282
289
  keyBase64: this._key ? this._key.toString('base64') : '',
283
290
  mode: this._mode,
284
291
  prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
285
292
  prevMode: this._prevMode,
293
+ allowLegacyPlaintextRead: this._allowLegacyPlaintextRead,
286
294
  };
287
295
  }
288
296
 
@@ -336,7 +344,7 @@ export class CacheEncryption {
336
344
  * Returns a mode-prefixed base64 string when a key is configured;
337
345
  * otherwise returns the original string unchanged (backward-compatible).
338
346
  */
339
- encrypt(plaintext: string): string {
347
+ encrypt(plaintext: string, context?: string): string {
340
348
  if (!this._key) return plaintext;
341
349
  if (this._mode === 'xor') {
342
350
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -355,9 +363,12 @@ export class CacheEncryption {
355
363
  return PREFIX_CTR + out.toString('base64');
356
364
  }
357
365
  const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
358
- const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
366
+ const prefix = context === undefined
367
+ ? (this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256)
368
+ : (this._mode === 'aes-128-gcm' ? PREFIX_BOUND_128 : PREFIX_BOUND_256);
359
369
  const iv = this._nextIV();
360
370
  const c = createCipheriv(algo, this._keyObj!, iv);
371
+ if (context !== undefined) c.setAAD(Buffer.from(context, 'utf8'));
361
372
  const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
362
373
  c.final(); // finalise — makes auth tag available
363
374
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -372,20 +383,31 @@ export class CacheEncryption {
372
383
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
373
384
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
374
385
  */
375
- decrypt(value: string): string {
386
+ assertReadPolicy(value: string | Buffer, context?: string): void {
387
+ if (!this.isEnabled || this._allowLegacyPlaintextRead || !this._mode.endsWith('-gcm')) return;
388
+ if (context === undefined) throw new Error('Authenticated cache read requires context');
389
+ if (typeof value === 'string') {
390
+ if (value.startsWith('ecp:v1:')) return this.assertReadPolicy(Buffer.from(value.slice(7), 'base64'), context);
391
+ if (value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128)) return;
392
+ } else if (value.subarray(0, 8).equals(MAGIC_BOUND_256) || value.subarray(0, 8).equals(MAGIC_BOUND_128)) return;
393
+ throw new Error('Legacy or plaintext cache value rejected; opt in to allowLegacyPlaintextRead for migration');
394
+ }
395
+
396
+ decrypt(value: string, context?: string): string {
397
+ this.assertReadPolicy(value, context);
376
398
  try {
377
- return this._decryptWithKey(value, this._key, this._keyObj);
399
+ return this._decryptWithKey(value, this._key, this._keyObj, context);
378
400
  } catch (primaryErr) {
379
401
  if (this._prevKey) {
380
402
  try {
381
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
403
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, context);
382
404
  } catch { /* ignore — fall through to re-throw primary */ }
383
405
  }
384
406
  throw primaryErr;
385
407
  }
386
408
  }
387
409
 
388
- private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
410
+ private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null, context?: string): string {
389
411
  if (value.startsWith(PREFIX_XOR)) {
390
412
  if (!key) throw new Error('Cannot decrypt: encryption key is not set');
391
413
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -407,17 +429,20 @@ export class CacheEncryption {
407
429
  const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
408
430
  return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
409
431
  }
410
- const is256 = value.startsWith(PREFIX_256);
411
- const is128 = value.startsWith(PREFIX_128);
432
+ const bound = value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128);
433
+ const is256 = value.startsWith(PREFIX_256) || value.startsWith(PREFIX_BOUND_256);
434
+ const is128 = value.startsWith(PREFIX_128) || value.startsWith(PREFIX_BOUND_128);
412
435
  if (!is256 && !is128) return value;
413
436
  if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
414
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
437
+ if (bound && context === undefined) throw new Error('Encrypted value requires authenticated context');
438
+ const prefix = bound ? (is128 ? PREFIX_BOUND_128 : PREFIX_BOUND_256) : (is128 ? PREFIX_128 : PREFIX_256);
415
439
  const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
416
440
  const combined = Buffer.from(value.slice(prefix.length), 'base64');
417
441
  const iv = combined.subarray(0, IV_BYTES);
418
442
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
419
443
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
420
444
  const d = createDecipheriv(algo, keyObj, iv);
445
+ if (bound) d.setAAD(Buffer.from(context!, 'utf8'));
421
446
  d.setAuthTag(tag);
422
447
  const plain = d.update(ct); // GCM: final() emits no bytes
423
448
  d.final(); // verifies auth tag — throws on tamper
@@ -427,7 +452,7 @@ export class CacheEncryption {
427
452
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
428
453
 
429
454
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
430
- encryptBuffer(data: Buffer): Buffer {
455
+ encryptBuffer(data: Buffer, context?: string): Buffer {
431
456
  if (!this._key) return data;
432
457
  if (this._mode === 'xor') {
433
458
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -450,10 +475,13 @@ export class CacheEncryption {
450
475
  if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
451
476
  return out;
452
477
  }
453
- const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
478
+ const magic = context === undefined
479
+ ? (this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256)
480
+ : (this._mode === 'aes-128-gcm' ? MAGIC_BOUND_128 : MAGIC_BOUND_256);
454
481
  const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
455
482
  const iv = this._nextIV();
456
483
  const c = createCipheriv(algo, this._keyObj!, iv);
484
+ if (context !== undefined) c.setAAD(Buffer.from(context, 'utf8'));
457
485
  const enc = c.update(data); // GCM: final() emits no bytes
458
486
  c.final(); // finalise — makes auth tag available
459
487
  // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
@@ -470,20 +498,21 @@ export class CacheEncryption {
470
498
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
471
499
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
472
500
  */
473
- decryptBuffer(data: Buffer): Buffer {
501
+ decryptBuffer(data: Buffer, context?: string): Buffer {
502
+ this.assertReadPolicy(data, context);
474
503
  try {
475
- return this._decryptBufferWithKey(data, this._key, this._keyObj);
504
+ return this._decryptBufferWithKey(data, this._key, this._keyObj, context);
476
505
  } catch (primaryErr) {
477
506
  if (this._prevKey) {
478
507
  try {
479
- return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
508
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj, context);
480
509
  } catch { /* ignore — re-throw primary */ }
481
510
  }
482
511
  throw primaryErr;
483
512
  }
484
513
  }
485
514
 
486
- private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
515
+ private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null, context?: string): Buffer {
487
516
  if (data.length < MAGIC_LEN) return data;
488
517
  const magic = data.subarray(0, MAGIC_LEN);
489
518
 
@@ -506,15 +535,18 @@ export class CacheEncryption {
506
535
  const fin = d.final(); // CTR: almost always empty — captured defensively
507
536
  return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
508
537
  }
509
- const is256 = magic.equals(MAGIC_256);
510
- const is128 = magic.equals(MAGIC_128);
538
+ const bound = magic.equals(MAGIC_BOUND_256) || magic.equals(MAGIC_BOUND_128);
539
+ const is256 = magic.equals(MAGIC_256) || magic.equals(MAGIC_BOUND_256);
540
+ const is128 = magic.equals(MAGIC_128) || magic.equals(MAGIC_BOUND_128);
511
541
  if (!is256 && !is128) return data;
512
542
  if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
543
+ if (bound && context === undefined) throw new Error('Encrypted buffer requires authenticated context');
513
544
  const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
514
545
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
515
546
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
516
547
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
517
548
  const d = createDecipheriv(algo, keyObj, iv);
549
+ if (bound) d.setAAD(Buffer.from(context!, 'utf8'));
518
550
  d.setAuthTag(tag);
519
551
  const plain = d.update(ct); // GCM: final() emits no bytes
520
552
  d.final(); // verifies auth tag — throws on tamper
package/src/env.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  declare module 'lz4js' {
2
2
  const lz4js: {
3
3
  compress: (buf: Uint8Array | Buffer) => Uint8Array;
4
- decompress: (buf: Uint8Array | Buffer) => Uint8Array;
4
+ decompress: (buf: Uint8Array | Buffer, maxSize?: number) => Uint8Array;
5
5
  };
6
6
  export default lz4js;
7
7
  }
package/src/errors.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Thrown when the opt-in read gate lacks fresh invalidation consumer proof. */
2
+ export class CacheInvalidationUnavailableError extends Error {
3
+ readonly reason: string;
4
+ readonly detectedAt: number | null;
5
+
6
+ constructor(reason: string, detectedAt: number | null) {
7
+ super(`TriCacheError: cached reads are unavailable because invalidation is not ready (${reason})`);
8
+ this.name = 'CacheInvalidationUnavailableError';
9
+ this.reason = reason;
10
+ this.detectedAt = detectedAt;
11
+ }
12
+ }
package/src/http/utils.ts CHANGED
@@ -78,7 +78,13 @@ export function buildDeterministicKey(req: any, options?: KeyDerivationOptions):
78
78
  }
79
79
  }
80
80
 
81
+ // Forwarded headers require an application-owned trusted-proxy policy.
82
+ const authority = readHttpHeader(req.headers, ':authority') ?? readHttpHeader(req.headers, 'host');
83
+ if (authority != null && (typeof authority !== 'string' || /[\s/\\?#@]/.test(authority))) {
84
+ throw new TypeError('HTTP cache authority must be a single valid host header');
85
+ }
81
86
  let key = `http:${method}:${path}`;
87
+ if (authority) key += `|host:${encodeURIComponent(authority.toLowerCase())}`;
82
88
  if (queryString) {
83
89
  key += `?${queryString}`;
84
90
  }
package/src/index.ts CHANGED
@@ -50,6 +50,8 @@ export {
50
50
  type RemoteSnapshotOptions,
51
51
  type HttpSnapshotAdapterOptions,
52
52
  type SigV4SnapshotAdapterOptions,
53
+ type SnapshotTransferOptions,
54
+ type SnapshotRequestOptions,
53
55
  } from './remote-snapshot';
54
56
  export {
55
57
  createHttpMeshRelay,
@@ -155,3 +157,7 @@ export {
155
157
  type IIpcCacheProvider,
156
158
  } from './ipc-telemetry';
157
159
 
160
+ export { CacheCapacityError } from './utils/work-limits.js';
161
+ export { CacheInvalidationUnavailableError } from './errors.js';
162
+ export { OriginCapacityLimiter } from './origin-capacity.js';
163
+ export type { OriginCapacityOptions, OriginRunOptions, OriginCapacityMetrics } from './origin-capacity.js';
@@ -258,7 +258,11 @@ export class TierLatencyWatchdog {
258
258
  this.canaryInFlight = false;
259
259
 
260
260
  if (success && elapsedMs < this.minDiskBypassMs) {
261
- // Canary succeeded and was fast: Recover cleanly
261
+ // Retire old disk samples so a later Redis observation cannot retrip us.
262
+ this.diskRing.fill(0);
263
+ this.diskIdx = 0;
264
+ this.diskCount = 0;
265
+ this.cachedDiskP95 = 0;
262
266
  this.stage = 0;
263
267
  this.bypassedUntilMonotonic = 0;
264
268
  this.recordDisk(elapsedMs);