tricache 0.7.1 → 0.8.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 (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,182 @@
1
+ import {
2
+ base64ToUint8Array,
3
+ uint8ArrayToBase64,
4
+ utf8ToUint8Array,
5
+ uint8ArrayToUtf8,
6
+ } from './utils/base64';
7
+
8
+ export type WebCryptoMode = 'aes-256-gcm' | 'aes-128-gcm';
9
+
10
+ const PREFIX_256 = 'enc:v1:';
11
+ const PREFIX_128 = 'a128:v1:';
12
+ const IV_LEN = 12;
13
+ const TAG_LEN = 16;
14
+ const HEADER_LEN = IV_LEN + TAG_LEN; // 28 bytes
15
+
16
+ export interface WebCryptoOptions {
17
+ keyBase64: string;
18
+ prevKeyBase64?: string;
19
+ mode?: WebCryptoMode;
20
+ }
21
+
22
+ /**
23
+ * Pure Web Crypto API implementation of TriCache AEAD encryption.
24
+ * Compatible with Cloudflare Workers, Fastly Compute, Vercel Edge, Deno, and modern browsers.
25
+ *
26
+ * Interoperates with Node.js `CacheEncryption` by reordering Web Crypto's trailing tag
27
+ * into TriCache's standard wire envelope:
28
+ * Envelope = IV[12] || Tag[16] || Ciphertext[N]
29
+ */
30
+ export class WebCryptoEncryption {
31
+ readonly isEnabled: boolean;
32
+ private readonly mode: WebCryptoMode;
33
+ private keyPromise: Promise<CryptoKey> | null = null;
34
+ private prevKeyPromise: Promise<CryptoKey> | null = null;
35
+
36
+ constructor(options?: WebCryptoOptions) {
37
+ if (!options?.keyBase64) {
38
+ this.isEnabled = false;
39
+ this.mode = 'aes-256-gcm';
40
+ return;
41
+ }
42
+
43
+ this.isEnabled = true;
44
+ this.mode = options.mode ?? 'aes-256-gcm';
45
+
46
+ const expectedBytes = this.mode === 'aes-256-gcm' ? 32 : 16;
47
+ const rawKey = base64ToUint8Array(options.keyBase64);
48
+ if (rawKey.length !== expectedBytes) {
49
+ throw new Error(
50
+ `WebCryptoEncryption: key length mismatch for ${this.mode}. Expected ${expectedBytes} bytes, received ${rawKey.length} bytes.`,
51
+ );
52
+ }
53
+
54
+ this.keyPromise = this._importKey(rawKey);
55
+
56
+ if (options.prevKeyBase64) {
57
+ const rawPrevKey = base64ToUint8Array(options.prevKeyBase64);
58
+ if (rawPrevKey.length === expectedBytes) {
59
+ this.prevKeyPromise = this._importKey(rawPrevKey);
60
+ }
61
+ }
62
+ }
63
+
64
+ private async _importKey(rawBytes: Uint8Array): Promise<CryptoKey> {
65
+ const cryptoSubtle = globalThis.crypto?.subtle;
66
+ if (!cryptoSubtle) {
67
+ throw new Error('WebCryptoEncryption: globalThis.crypto.subtle is not available in this environment.');
68
+ }
69
+ // Web Crypto requires raw ArrayBuffer
70
+ const keyBuf = rawBytes.buffer.slice(rawBytes.byteOffset, rawBytes.byteOffset + rawBytes.byteLength) as ArrayBuffer;
71
+ return cryptoSubtle.importKey(
72
+ 'raw',
73
+ keyBuf,
74
+ { name: 'AES-GCM' },
75
+ false,
76
+ ['encrypt', 'decrypt'],
77
+ );
78
+ }
79
+
80
+ /**
81
+ * Encrypts a plaintext string into a TriCache standard wire envelope.
82
+ * Format: `enc:v1:<base64(IV[12] | Tag[16] | Ciphertext)>`
83
+ */
84
+ async encrypt(plaintext: string): Promise<string> {
85
+ if (!this.isEnabled || !this.keyPromise) return plaintext;
86
+
87
+ const cryptoObj = globalThis.crypto;
88
+ const key = await this.keyPromise;
89
+ const iv = cryptoObj.getRandomValues(new Uint8Array(IV_LEN));
90
+ const plaintextBytes = utf8ToUint8Array(plaintext);
91
+
92
+ // Web Crypto outputs: Ciphertext || Tag[16]
93
+ const encryptedBuf = await cryptoObj.subtle.encrypt(
94
+ {
95
+ name: 'AES-GCM',
96
+ iv: iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength) as ArrayBuffer,
97
+ tagLength: 128,
98
+ },
99
+ key,
100
+ plaintextBytes.buffer.slice(plaintextBytes.byteOffset, plaintextBytes.byteOffset + plaintextBytes.byteLength) as ArrayBuffer,
101
+ );
102
+
103
+ const encryptedBytes = new Uint8Array(encryptedBuf);
104
+ const ctLen = encryptedBytes.length - TAG_LEN;
105
+ const ciphertext = encryptedBytes.subarray(0, ctLen);
106
+ const tag = encryptedBytes.subarray(ctLen);
107
+
108
+ // Reorder to TriCache wire layout: IV[12] || Tag[16] || Ciphertext[N]
109
+ const envelope = new Uint8Array(HEADER_LEN + ctLen);
110
+ envelope.set(iv, 0);
111
+ envelope.set(tag, IV_LEN);
112
+ envelope.set(ciphertext, HEADER_LEN);
113
+
114
+ const prefix = this.mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
115
+ return prefix + uint8ArrayToBase64(envelope);
116
+ }
117
+
118
+ /**
119
+ * Decrypts a TriCache standard wire envelope into plaintext.
120
+ * Handles envelopes created by both WebCryptoEncryption and Node.js CacheEncryption.
121
+ */
122
+ async decrypt(envelopeStr: string): Promise<string> {
123
+ if (!this.isEnabled || !this.keyPromise) return envelopeStr;
124
+
125
+ let base64Data: string;
126
+ if (envelopeStr.startsWith(PREFIX_256)) {
127
+ base64Data = envelopeStr.slice(PREFIX_256.length);
128
+ } else if (envelopeStr.startsWith(PREFIX_128)) {
129
+ base64Data = envelopeStr.slice(PREFIX_128.length);
130
+ } else {
131
+ // Unencrypted or unrecognized prefix
132
+ return envelopeStr;
133
+ }
134
+
135
+ const envelopeBytes = base64ToUint8Array(base64Data);
136
+ if (envelopeBytes.length < HEADER_LEN) {
137
+ throw new Error(`WebCryptoEncryption: malformed envelope, length ${envelopeBytes.length} < header ${HEADER_LEN}`);
138
+ }
139
+
140
+ try {
141
+ const activeKey = await this.keyPromise;
142
+ return await this._decryptWithKey(activeKey, envelopeBytes);
143
+ } catch (primaryErr) {
144
+ if (this.prevKeyPromise) {
145
+ try {
146
+ const prevKey = await this.prevKeyPromise;
147
+ return await this._decryptWithKey(prevKey, envelopeBytes);
148
+ } catch {
149
+ // Re-throw primary error on key rotation failure
150
+ }
151
+ }
152
+ throw primaryErr;
153
+ }
154
+ }
155
+
156
+ private async _decryptWithKey(key: CryptoKey, envelopeBytes: Uint8Array): Promise<string> {
157
+ const cryptoSubtle = globalThis.crypto.subtle;
158
+ const iv = envelopeBytes.subarray(0, IV_LEN);
159
+ const tag = envelopeBytes.subarray(IV_LEN, HEADER_LEN);
160
+ const ciphertext = envelopeBytes.subarray(HEADER_LEN);
161
+
162
+ // Web Crypto decrypt expects: Ciphertext || Tag[16]
163
+ const webCryptoInput = new Uint8Array(ciphertext.length + TAG_LEN);
164
+ webCryptoInput.set(ciphertext, 0);
165
+ webCryptoInput.set(tag, ciphertext.length);
166
+
167
+ const ivBuf = iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength) as ArrayBuffer;
168
+ const dataBuf = webCryptoInput.buffer.slice(webCryptoInput.byteOffset, webCryptoInput.byteOffset + webCryptoInput.byteLength) as ArrayBuffer;
169
+
170
+ const decryptedBuf = await cryptoSubtle.decrypt(
171
+ {
172
+ name: 'AES-GCM',
173
+ iv: ivBuf,
174
+ tagLength: 128,
175
+ },
176
+ key,
177
+ dataBuf,
178
+ );
179
+
180
+ return uint8ArrayToUtf8(new Uint8Array(decryptedBuf));
181
+ }
182
+ }
@@ -0,0 +1,203 @@
1
+ import type { EdgeCacheService } from './cache.js';
2
+
3
+ export interface HonoEdgeCacheOptions {
4
+ /** EdgeCacheService instance. If omitted, requires explicit cache passing. */
5
+ cache?: EdgeCacheService | any;
6
+ /** Custom key generator. Defaults to deterministic method + URL + sorted query string. */
7
+ keyGenerator?: (c: any) => string;
8
+ /** Optional list of header names to include in the cache key. */
9
+ headerWhitelist?: string[];
10
+ /** Whether to generate and evaluate weak ETags. Default: true. */
11
+ etag?: boolean;
12
+ /** TTL in seconds. Default: 300. */
13
+ ttl?: number;
14
+ /** Stale-While-Revalidate window in seconds. Default: undefined. */
15
+ swr?: number;
16
+ /** Cache tags for invalidation. */
17
+ tags?: string[] | ((c: any) => string[]);
18
+ /** Predicate to skip caching dynamically. */
19
+ skipCache?: (c: any) => boolean;
20
+ }
21
+
22
+ export interface CachedEdgeHttpResponse {
23
+ body: string;
24
+ contentType: string;
25
+ etag?: string;
26
+ status: number;
27
+ }
28
+
29
+ /**
30
+ * Computes a weak ETag using Web Crypto API (crypto.subtle) without importing Node.js modules.
31
+ */
32
+ export async function computeEdgeETag(text: string): Promise<string> {
33
+ try {
34
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
35
+ const encoder = new TextEncoder();
36
+ const data = encoder.encode(text);
37
+ const hashBuf = await crypto.subtle.digest('SHA-1', data);
38
+ const hashArr = Array.from(new Uint8Array(hashBuf));
39
+ const hashHex = hashArr.map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16);
40
+ return `W/"${text.length.toString(16)}-${hashHex}"`;
41
+ }
42
+ } catch {
43
+ // Fallback if subtle crypto is unavailable in test environment
44
+ }
45
+
46
+ let h = 0;
47
+ for (let i = 0; i < text.length; i++) {
48
+ h = (Math.imul(31, h) + text.charCodeAt(i)) | 0;
49
+ }
50
+ return `W/"${text.length.toString(16)}-${Math.abs(h).toString(16)}"`;
51
+ }
52
+
53
+ /**
54
+ * Generates a deterministic cache key from standard Web Request / Hono context.
55
+ */
56
+ export function buildEdgeDeterministicKey(c: any, options?: { keyGenerator?: (c: any) => string; headerWhitelist?: string[] }): string {
57
+ if (options?.keyGenerator) {
58
+ return options.keyGenerator(c);
59
+ }
60
+
61
+ const req = c.req;
62
+ const method = (req.method || 'GET').toUpperCase();
63
+ const rawUrl = req.url || '/';
64
+
65
+ const qIdx = rawUrl.indexOf('?');
66
+ const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
67
+ let queryString = '';
68
+
69
+ if (qIdx >= 0) {
70
+ const rawQuery = rawUrl.slice(qIdx + 1);
71
+ try {
72
+ const params = new URLSearchParams(rawQuery);
73
+ params.sort();
74
+ queryString = params.toString();
75
+ } catch {
76
+ queryString = rawQuery;
77
+ }
78
+ }
79
+
80
+ let key = `edge:http:${method}:${path}`;
81
+ if (queryString) {
82
+ key += `?${queryString}`;
83
+ }
84
+
85
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.header) {
86
+ const sortedHeaders = [...options.headerWhitelist].sort();
87
+ for (const h of sortedHeaders) {
88
+ const val = req.header(h);
89
+ if (val !== undefined && val !== null && val !== '') {
90
+ key += `|h:${h.toLowerCase()}=${val}`;
91
+ }
92
+ }
93
+ }
94
+
95
+ return key;
96
+ }
97
+
98
+ /**
99
+ * Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
100
+ *
101
+ * Operates strictly with Web Request/Response and Web Crypto APIs.
102
+ *
103
+ * @example
104
+ * import { Hono } from 'hono';
105
+ * import { EdgeCacheService, honoEdgeCache } from 'tricache/edge';
106
+ *
107
+ * const app = new Hono();
108
+ * const cache = new EdgeCacheService({ maxKeys: 10_000 });
109
+ *
110
+ * app.get('/api/feed', honoEdgeCache({ cache, ttl: 60 }), async (c) => {
111
+ * return c.json({ status: 'ok', timestamp: Date.now() });
112
+ * });
113
+ */
114
+ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
115
+ const {
116
+ cache,
117
+ etag = true,
118
+ ttl = 300,
119
+ swr,
120
+ tags,
121
+ skipCache,
122
+ keyGenerator,
123
+ headerWhitelist,
124
+ } = options;
125
+
126
+ return async (c: any, next: () => Promise<void>) => {
127
+ const method = c.req.method;
128
+ if (method !== 'GET' && method !== 'HEAD') {
129
+ return await next();
130
+ }
131
+
132
+ if (skipCache && skipCache(c)) {
133
+ return await next();
134
+ }
135
+
136
+ const cc = c.req.header?.('cache-control') || c.req.header?.('Cache-Control');
137
+ if (typeof cc === 'string') {
138
+ const lower = cc.toLowerCase();
139
+ if (lower.includes('no-cache') || lower.includes('no-store')) {
140
+ return await next();
141
+ }
142
+ }
143
+
144
+ if (!cache) {
145
+ // If no cache instance passed, proceed without caching
146
+ return await next();
147
+ }
148
+
149
+ const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
150
+ const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
151
+ const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
152
+
153
+ const cached = await cache.get(
154
+ key,
155
+ async () => {
156
+ await next();
157
+ const res = c.res;
158
+ if (!res) {
159
+ return null;
160
+ }
161
+
162
+ const clone = res.clone();
163
+ const text = await clone.text();
164
+ const statusCode = res.status ?? 200;
165
+ const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
166
+ const contentType = res.headers.get('content-type') || 'text/plain; charset=utf-8';
167
+
168
+ return {
169
+ body: text,
170
+ contentType,
171
+ etag: bodyEtag,
172
+ status: statusCode,
173
+ };
174
+ },
175
+ ttl,
176
+ {
177
+ swr,
178
+ tags: resolvedTags,
179
+ ctx: c.executionCtx,
180
+ }
181
+ );
182
+
183
+ if (!cached) {
184
+ return;
185
+ }
186
+
187
+ // Status gate: never cache error responses
188
+ if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
189
+ await cache.delete?.(key);
190
+ return;
191
+ }
192
+
193
+ if (cached.etag && ifNoneMatch === cached.etag) {
194
+ return c.body(null, 304, { ETag: cached.etag });
195
+ }
196
+
197
+ const headers: Record<string, string> = {};
198
+ if (cached.etag) headers['ETag'] = cached.etag;
199
+ if (cached.contentType) headers['Content-Type'] = cached.contentType;
200
+
201
+ return c.body(cached.body, cached.status ?? 200, headers);
202
+ };
203
+ }
@@ -0,0 +1,37 @@
1
+ export { EdgeCacheService } from './cache';
2
+ export { WebCryptoEncryption, type WebCryptoOptions, type WebCryptoMode } from './crypto';
3
+ export { UpstashRedisAdapter } from './adapters/upstash';
4
+ export { CloudflareKVAdapter } from './adapters/cloudflare-kv';
5
+ export { CloudflareDOStorageAdapter } from './adapters/cloudflare-do';
6
+ export {
7
+ uint8ArrayToBase64,
8
+ base64ToUint8Array,
9
+ utf8ToUint8Array,
10
+ uint8ArrayToUtf8,
11
+ } from './utils/base64';
12
+ export { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
13
+ export { Murmur3BloomFilter, murmur3_32, type BloomFilterStats } from './utils/murmur3';
14
+ export type {
15
+ IEdgeRemoteStorage,
16
+ IEdgeBloomFilter,
17
+ EdgeCacheOptions,
18
+ EdgeGetOptions,
19
+ UpstashRedisOptions,
20
+ CloudflareKVNamespace,
21
+ CloudflareDOStorage,
22
+ CloudflareR2Bucket,
23
+ CloudflareR2Object,
24
+ EdgeSnapshotSource,
25
+ EdgeHydrateOptions,
26
+ EdgeExportSnapshotOptions,
27
+ EdgeSnapshotPayload,
28
+ } from './types';
29
+
30
+ export {
31
+ honoEdgeCache,
32
+ computeEdgeETag,
33
+ buildEdgeDeterministicKey,
34
+ type HonoEdgeCacheOptions,
35
+ type CachedEdgeHttpResponse,
36
+ } from './hono';
37
+
@@ -0,0 +1,230 @@
1
+ import type { ICacheTracer } from '../types';
2
+
3
+ /**
4
+ * Pluggable asynchronous key-value storage adapter for Edge runtimes (L2 tier).
5
+ */
6
+ export interface IEdgeRemoteStorage {
7
+ /** Fetch a stored value by key. Returns null on miss. */
8
+ get(key: string): Promise<string | null>;
9
+
10
+ /** Store a value with an optional TTL in seconds. */
11
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
12
+
13
+ /** Delete a key. */
14
+ delete(key: string): Promise<void>;
15
+
16
+ /** Optional batch read. Returns array matching keys order (null for missing). */
17
+ mget?(keys: string[]): Promise<(string | null)[]>;
18
+
19
+ /** Optional batch write. */
20
+ mset?(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
21
+
22
+ /** Optional clear by prefix or all keys. */
23
+ clear?(prefix?: string): Promise<void>;
24
+
25
+ /** Optional atomic or monotonic tag version increment for generational tag invalidation. */
26
+ incrementTagVersion?(tag: string): Promise<number>;
27
+
28
+ /** Optional tag version retrieval. */
29
+ getTagVersion?(tag: string): Promise<number>;
30
+
31
+ /** Optional batch tag version retrieval. */
32
+ batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
33
+ }
34
+
35
+ /**
36
+ * Options for cache read operations in Edge environments.
37
+ */
38
+ export interface EdgeGetOptions {
39
+ /** Cache tags associated with this entry for bulk invalidation. */
40
+ tags?: string[];
41
+
42
+ /**
43
+ * Stale-While-Revalidate window in seconds.
44
+ * If entry is older than TTL but within (TTL + swr), stale data is returned
45
+ * immediately while a background fetcher runs to refresh the cache.
46
+ */
47
+ swr?: number;
48
+
49
+ /**
50
+ * Execution context provided by Edge platforms (Cloudflare Workers, Vercel Edge).
51
+ * Critical: In edge isolates, background tasks spawned without ctx.waitUntil()
52
+ * are terminated as soon as the HTTP response terminates.
53
+ */
54
+ ctx?: {
55
+ waitUntil: (promise: Promise<unknown>) => void;
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Options for configuring the EdgeCacheService.
61
+ */
62
+ export interface EdgeCacheOptions {
63
+ /**
64
+ * Maximum number of keys held in L1 in-memory LRU. Default: 10,000.
65
+ */
66
+ maxKeys?: number;
67
+
68
+ /**
69
+ * Approximate maximum memory in bytes for L1 cache (calculated via UTF-8 length * 2).
70
+ * Default: 32 MB (33,554,432 bytes).
71
+ */
72
+ maxBytes?: number;
73
+
74
+ /** Default TTL in seconds when not specified on get/set. Default: 300 (5 min). */
75
+ defaultTtlSeconds?: number;
76
+
77
+ /** Optional remote L2 storage adapter (Upstash, Cloudflare KV, Cloudflare DO). */
78
+ remoteStorage?: IEdgeRemoteStorage;
79
+
80
+ /** Optional at-rest encryption configuration via Web Crypto (AES-GCM). */
81
+ encryption?: {
82
+ keyBase64: string;
83
+ prevKeyBase64?: string;
84
+ mode?: 'aes-256-gcm' | 'aes-128-gcm';
85
+ };
86
+
87
+ /** Multi-tenant key namespace prefix. */
88
+ namespace?: string;
89
+
90
+ /** OpenTelemetry-compatible tracer for distributed tracing. */
91
+ tracer?: ICacheTracer;
92
+
93
+ /**
94
+ * Optional Bloom filter to defend against remote storage penetration on guaranteed misses.
95
+ * - `true`: automatically instantiates a default `WasmBloomFilter` (or `Murmur3BloomFilter` fallback).
96
+ * - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
97
+ */
98
+ bloomFilter?: boolean | IEdgeBloomFilter;
99
+ }
100
+
101
+ /**
102
+ * Common contract for Edge-compatible Bloom filters (WASM or pure TypeScript Murmur3).
103
+ */
104
+ export interface IEdgeBloomFilter {
105
+ add(key: string): void;
106
+ mightContain(key: string): boolean;
107
+ reset(): void;
108
+ rebuild?(keys: Iterable<string>): void;
109
+ readonly insertions?: number;
110
+ readonly maxCapacity?: number;
111
+ readonly stats?: { bitsSet: number; fillFactor: number };
112
+ }
113
+
114
+ /**
115
+ * Configuration for Upstash REST Redis adapter.
116
+ */
117
+ export interface UpstashRedisOptions {
118
+ /** Upstash REST URL (e.g. "https://us1-clean-slug-12345.upstash.io"). */
119
+ url: string;
120
+
121
+ /** Upstash REST bearer token. */
122
+ token: string;
123
+
124
+ /** Optional custom fetch implementation (defaults to globalThis.fetch). */
125
+ fetch?: typeof globalThis.fetch;
126
+ }
127
+
128
+ /**
129
+ * Minimal interface representing Cloudflare Workers KVNamespace binding.
130
+ */
131
+ export interface CloudflareKVNamespace {
132
+ get(key: string, options?: { type?: 'text' | 'json' | 'arrayBuffer' | 'stream'; cacheTtl?: number }): Promise<string | null>;
133
+ put(key: string, value: string, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;
134
+ delete(key: string): Promise<void>;
135
+ list?(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<{
136
+ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>;
137
+ list_complete: boolean;
138
+ cursor?: string;
139
+ }>;
140
+ }
141
+
142
+ /**
143
+ * Minimal interface representing Cloudflare Durable Objects storage binding (state.storage).
144
+ */
145
+ export interface CloudflareDOStorage {
146
+ get<T = unknown>(key: string): Promise<T | undefined>;
147
+ get<T = unknown>(keys: string[]): Promise<Map<string, T>>;
148
+ put<T = unknown>(key: string, value: T): Promise<void>;
149
+ put<T = unknown>(entries: Record<string, T>): Promise<void>;
150
+ delete(key: string): Promise<boolean>;
151
+ delete(keys: string[]): Promise<number>;
152
+ list?<T = unknown>(options?: { prefix?: string; limit?: number }): Promise<Map<string, T>>;
153
+ }
154
+
155
+ /**
156
+ * Minimal interface representing a Cloudflare R2 object returned by R2Bucket.get().
157
+ */
158
+ export interface CloudflareR2Object {
159
+ text(): Promise<string>;
160
+ arrayBuffer(): Promise<ArrayBuffer>;
161
+ json?<T = unknown>(): Promise<T>;
162
+ }
163
+
164
+ /**
165
+ * Minimal interface representing Cloudflare R2 Bucket binding (env.MY_BUCKET).
166
+ */
167
+ export interface CloudflareR2Bucket {
168
+ get(key: string): Promise<CloudflareR2Object | null>;
169
+ put(key: string, value: string | ArrayBuffer | ArrayBufferView | Blob | ReadableStream, options?: unknown): Promise<unknown>;
170
+ delete?(key: string | string[]): Promise<void>;
171
+ }
172
+
173
+ /**
174
+ * Generic source for edge snapshot hydration (R2 bucket binding, custom loader object, raw string, or ArrayBuffer).
175
+ */
176
+ export type EdgeSnapshotSource =
177
+ | CloudflareR2Bucket
178
+ | { get(key: string): Promise<CloudflareR2Object | string | ArrayBuffer | Uint8Array | null> }
179
+ | string
180
+ | ArrayBuffer
181
+ | Uint8Array;
182
+
183
+ /**
184
+ * Configuration options for EdgeCacheService.hydrate().
185
+ */
186
+ export interface EdgeHydrateOptions {
187
+ /**
188
+ * Object key or filename in the R2 bucket. Default: 'tricache-edge.snap'
189
+ */
190
+ key?: string;
191
+
192
+ /**
193
+ * Maximum acceptable age of snapshot in milliseconds before rejecting as stale.
194
+ * Default: 7,200,000 ms (2 hours).
195
+ */
196
+ maxAgeMs?: number;
197
+
198
+ /**
199
+ * Acceptable clock skew tolerance in milliseconds for future timestamps.
200
+ * Default: 250 ms.
201
+ */
202
+ clockSkewToleranceMs?: number;
203
+ }
204
+
205
+ /**
206
+ * Configuration options for EdgeCacheService.exportSnapshot().
207
+ */
208
+ export interface EdgeExportSnapshotOptions {
209
+ /**
210
+ * Whether to encrypt the exported snapshot using the configured Web Crypto AEAD key.
211
+ * Default: true (when encryption is configured).
212
+ */
213
+ encrypt?: boolean;
214
+ }
215
+
216
+ /**
217
+ * Serialized representation of edge cache snapshot payload.
218
+ */
219
+ export interface EdgeSnapshotPayload {
220
+ version: number;
221
+ writtenAt: number;
222
+ entries: Array<{
223
+ key: string;
224
+ value: unknown;
225
+ expiresAt: number;
226
+ staleUntil: number;
227
+ tags?: string[];
228
+ tagVersions?: Record<string, number>;
229
+ }>;
230
+ }