tricache 1.0.1 → 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 (127) hide show
  1. package/README.md +89 -93
  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-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
package/dist/index.js CHANGED
@@ -1,23 +1,8 @@
1
- import {
2
- NodeRedisAdapter,
3
- SigV4SnapshotAdapter,
4
- createCrossRegionWebhookHandler,
5
- createCustomCrossRegionRelay,
6
- createCustomSnapshotAdapter,
7
- createHttpMeshRelay,
8
- createHttpSnapshotAdapter,
9
- createMemoryCrossRegionRelay,
10
- createMemorySnapshotAdapter,
11
- createNodeRedisAdapter,
12
- createR2SnapshotAdapter,
13
- createS3SnapshotAdapter,
14
- createSigV4SnapshotAdapter,
15
- formatTraceParent,
16
- parseTraceParent
17
- } from "./chunk-3I5L7K6I.js";
18
1
  import {
19
2
  AutoPipeliner,
3
+ CacheCapacityError,
20
4
  CacheCodec,
5
+ CacheInvalidationUnavailableError,
21
6
  CacheService,
22
7
  DEFAULT_AUTONOMOUS_L1_CEILING_BYTES,
23
8
  DiskTier,
@@ -30,6 +15,11 @@ import {
30
15
  TinyLfuSketch,
31
16
  WTinyLfuCache,
32
17
  WTinyLfuPolicy,
18
+ WorkLimit,
19
+ createCrossRegionWebhookHandler,
20
+ createCustomCrossRegionRelay,
21
+ createHttpMeshRelay,
22
+ createMemoryCrossRegionRelay,
33
23
  deepMergeOptions,
34
24
  defaultCodec,
35
25
  findActiveSockets,
@@ -37,26 +27,27 @@ import {
37
27
  formatDuration,
38
28
  formatNumber,
39
29
  getV8HeapLimit,
30
+ positiveLimit,
40
31
  readCgroupMemoryLimit,
41
32
  renderProgressBar,
42
33
  renderTopDashboard,
43
34
  resolveAutonomousL1MaxBytes,
44
35
  resolveDefaultDiskDir,
45
36
  resolveIpcSocketPath
46
- } from "./chunk-JYQFQJNJ.js";
37
+ } from "./chunk-MB3DMVWN.js";
47
38
  import {
48
39
  CacheEncryption,
49
40
  CachePriority,
50
41
  EnvelopeEncryption,
51
42
  consoleLogger,
52
43
  initZstd
53
- } from "./chunk-UBWLPKTI.js";
44
+ } from "./chunk-EJXG7WO6.js";
54
45
  import {
55
46
  createNextDashboardHandlers,
56
47
  handleDashboardRequest,
57
48
  startDashboardServer,
58
49
  tricacheDashboard
59
- } from "./chunk-7RV5ZVBB.js";
50
+ } from "./chunk-JNSLMK4Q.js";
60
51
  import {
61
52
  Murmur3BloomFilter,
62
53
  murmur3_32
@@ -67,11 +58,876 @@ import {
67
58
  isChildTag,
68
59
  isWildcardTag,
69
60
  matchesTagPattern
70
- } from "./chunk-2AJKEQMZ.js";
61
+ } from "./chunk-KV7KISK2.js";
62
+
63
+ // src/utils/snapshot-transfer.ts
64
+ async function snapshotRequest(options, request, work) {
65
+ const maxBytes = positiveLimit(options.maxBytes, 220 * 1024 * 1024, "maxBytes");
66
+ const timeoutMs = positiveLimit(options.timeoutMs, 3e4, "timeoutMs");
67
+ const controller = new AbortController();
68
+ const abort = () => controller.abort(request?.signal?.reason);
69
+ request?.signal?.addEventListener("abort", abort, { once: true });
70
+ if (request?.signal?.aborted) abort();
71
+ const timer = setTimeout(() => controller.abort(new Error("Snapshot request timed out")), timeoutMs);
72
+ let stopWaiting;
73
+ const cancelled = new Promise((_resolve, reject) => {
74
+ stopWaiting = () => reject(controller.signal.reason);
75
+ controller.signal.addEventListener("abort", stopWaiting, { once: true });
76
+ });
77
+ try {
78
+ controller.signal.throwIfAborted();
79
+ return await Promise.race([work(controller.signal, maxBytes), cancelled]);
80
+ } finally {
81
+ clearTimeout(timer);
82
+ request?.signal?.removeEventListener("abort", abort);
83
+ controller.signal.removeEventListener("abort", stopWaiting);
84
+ }
85
+ }
86
+ function discardSnapshotResponse(response) {
87
+ void response.body?.cancel().catch(() => {
88
+ });
89
+ }
90
+ async function readSnapshotResponse(response, signal, maxBytes) {
91
+ const advertised = response.headers.get("content-length");
92
+ if (advertised !== null && Number(advertised) > maxBytes) {
93
+ discardSnapshotResponse(response);
94
+ throw new Error("Snapshot exceeds size limit");
95
+ }
96
+ if (signal.aborted) {
97
+ discardSnapshotResponse(response);
98
+ signal.throwIfAborted();
99
+ }
100
+ if (!response.body) return Buffer.alloc(0);
101
+ const reader = response.body.getReader();
102
+ const cancel = () => {
103
+ void reader.cancel(signal.reason).catch(() => {
104
+ });
105
+ };
106
+ signal.addEventListener("abort", cancel, { once: true });
107
+ const chunks = [];
108
+ let size = 0;
109
+ try {
110
+ while (true) {
111
+ signal.throwIfAborted();
112
+ const { done, value } = await reader.read();
113
+ signal.throwIfAborted();
114
+ if (done) break;
115
+ size += value.byteLength;
116
+ if (size > maxBytes) throw new Error("Snapshot exceeds size limit");
117
+ chunks.push(Buffer.from(value));
118
+ }
119
+ return Buffer.concat(chunks, size);
120
+ } catch (error) {
121
+ void reader.cancel(error).catch(() => {
122
+ });
123
+ throw error;
124
+ } finally {
125
+ signal.removeEventListener("abort", cancel);
126
+ reader.releaseLock();
127
+ }
128
+ }
129
+
130
+ // src/sigv4-snapshot-adapter.ts
131
+ var EMPTY_STRING_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
132
+ async function sha256Hex(data) {
133
+ const buf = typeof data === "string" ? new TextEncoder().encode(data) : data;
134
+ const digest = await crypto.subtle.digest("SHA-256", buf);
135
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
136
+ }
137
+ async function hmac(key, data) {
138
+ let cryptoKey;
139
+ if (key instanceof CryptoKey) {
140
+ cryptoKey = key;
141
+ } else {
142
+ const rawBuf = key instanceof Uint8Array ? key.buffer.slice(key.byteOffset, key.byteOffset + key.byteLength) : key;
143
+ cryptoKey = await crypto.subtle.importKey(
144
+ "raw",
145
+ rawBuf,
146
+ { name: "HMAC", hash: "SHA-256" },
147
+ false,
148
+ ["sign"]
149
+ );
150
+ }
151
+ return await crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(data));
152
+ }
153
+ function encodeRfc3986(str) {
154
+ return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
155
+ }
156
+ function encodePath(path) {
157
+ return path.split("/").map(encodeRfc3986).join("/");
158
+ }
159
+ var SigV4SnapshotAdapter = class {
160
+ bucket;
161
+ key;
162
+ region;
163
+ endpoint;
164
+ accessKeyId;
165
+ secretAccessKey;
166
+ sessionToken;
167
+ forcePathStyle;
168
+ fetchImpl;
169
+ transfer;
170
+ constructor(options) {
171
+ this.transfer = { maxBytes: options.maxBytes, timeoutMs: options.timeoutMs };
172
+ this.bucket = options.bucket;
173
+ this.key = options.key.replace(/^\/+/, "");
174
+ this.region = options.region ?? (options.endpoint?.includes("r2.cloudflarestorage.com") ? "auto" : "us-east-1");
175
+ this.endpoint = options.endpoint;
176
+ const accessKey = options.accessKeyId ?? (typeof process !== "undefined" ? process.env?.AWS_ACCESS_KEY_ID : void 0);
177
+ const secretKey = options.secretAccessKey ?? (typeof process !== "undefined" ? process.env?.AWS_SECRET_ACCESS_KEY : void 0);
178
+ const token = options.sessionToken ?? (typeof process !== "undefined" ? process.env?.AWS_SESSION_TOKEN : void 0);
179
+ if (!accessKey || !secretKey) {
180
+ throw new Error(
181
+ "SigV4SnapshotAdapter: AWS credentials missing. Provide accessKeyId and secretAccessKey or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY."
182
+ );
183
+ }
184
+ this.accessKeyId = accessKey;
185
+ this.secretAccessKey = secretKey;
186
+ this.sessionToken = token;
187
+ this.forcePathStyle = options.forcePathStyle ?? Boolean(options.endpoint);
188
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
189
+ }
190
+ _resolveTarget() {
191
+ const encodedKey = encodePath(this.key);
192
+ if (this.endpoint) {
193
+ const base = new URL(this.endpoint);
194
+ const basePath = base.pathname.replace(/\/+$/, "");
195
+ if (this.forcePathStyle) {
196
+ const canonicalUri2 = `${basePath}/${encodeRfc3986(this.bucket)}/${encodedKey}`;
197
+ const url2 = new URL(canonicalUri2, base.origin);
198
+ return { url: url2, canonicalUri: canonicalUri2, host: url2.host };
199
+ } else {
200
+ const host2 = `${this.bucket}.${base.host}`;
201
+ const canonicalUri2 = `${basePath}/${encodedKey}`;
202
+ const url2 = new URL(canonicalUri2, `${base.protocol}//${host2}`);
203
+ return { url: url2, canonicalUri: canonicalUri2, host: host2 };
204
+ }
205
+ }
206
+ if (this.forcePathStyle) {
207
+ const host2 = this.region === "us-east-1" ? "s3.amazonaws.com" : `s3.${this.region}.amazonaws.com`;
208
+ const canonicalUri2 = `/${encodeRfc3986(this.bucket)}/${encodedKey}`;
209
+ const url2 = new URL(`https://${host2}${canonicalUri2}`);
210
+ return { url: url2, canonicalUri: canonicalUri2, host: host2 };
211
+ }
212
+ const host = this.region === "us-east-1" ? `${this.bucket}.s3.amazonaws.com` : `${this.bucket}.s3.${this.region}.amazonaws.com`;
213
+ const canonicalUri = `/${encodedKey}`;
214
+ const url = new URL(`https://${host}${canonicalUri}`);
215
+ return { url, canonicalUri, host };
216
+ }
217
+ async _buildHeaders(method, body) {
218
+ const { url, canonicalUri, host } = this._resolveTarget();
219
+ const now = /* @__PURE__ */ new Date();
220
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
221
+ const dateStamp = amzDate.slice(0, 8);
222
+ const service = "s3";
223
+ const payloadHash = body ? await sha256Hex(body) : EMPTY_STRING_SHA256;
224
+ const headersToSign = {
225
+ host,
226
+ "x-amz-content-sha256": payloadHash,
227
+ "x-amz-date": amzDate
228
+ };
229
+ if (this.sessionToken) {
230
+ headersToSign["x-amz-security-token"] = this.sessionToken;
231
+ }
232
+ if (body) {
233
+ headersToSign["content-type"] = "application/octet-stream";
234
+ }
235
+ const sortedHeaderKeys = Object.keys(headersToSign).sort();
236
+ const canonicalHeaders = sortedHeaderKeys.map((k) => `${k}:${headersToSign[k]}
237
+ `).join("");
238
+ const signedHeaders = sortedHeaderKeys.join(";");
239
+ const canonicalRequest = [
240
+ method,
241
+ canonicalUri,
242
+ "",
243
+ // canonical query string
244
+ canonicalHeaders,
245
+ signedHeaders,
246
+ payloadHash
247
+ ].join("\n");
248
+ const credentialScope = `${dateStamp}/${this.region}/${service}/aws4_request`;
249
+ const stringToSign = [
250
+ "AWS4-HMAC-SHA256",
251
+ amzDate,
252
+ credentialScope,
253
+ await sha256Hex(canonicalRequest)
254
+ ].join("\n");
255
+ const kDate = await hmac(new TextEncoder().encode(`AWS4${this.secretAccessKey}`), dateStamp);
256
+ const kRegion = await hmac(kDate, this.region);
257
+ const kService = await hmac(kRegion, service);
258
+ const kSigning = await hmac(kService, "aws4_request");
259
+ const signatureBytes = await hmac(kSigning, stringToSign);
260
+ const signature = Array.from(new Uint8Array(signatureBytes)).map((b) => b.toString(16).padStart(2, "0")).join("");
261
+ const authHeader = `AWS4-HMAC-SHA256 Credential=${this.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
262
+ const finalHeaders = {
263
+ ...headersToSign,
264
+ Authorization: authHeader
265
+ };
266
+ return { headers: finalHeaders, url };
267
+ }
268
+ async get(request) {
269
+ return snapshotRequest(this.transfer, request, async (signal, maxBytes) => {
270
+ const { headers, url } = await this._buildHeaders("GET");
271
+ signal.throwIfAborted();
272
+ const res = await this.fetchImpl(url.toString(), {
273
+ method: "GET",
274
+ headers,
275
+ signal
276
+ });
277
+ if (res.status === 404) {
278
+ discardSnapshotResponse(res);
279
+ return null;
280
+ }
281
+ if (!res.ok) {
282
+ discardSnapshotResponse(res);
283
+ throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}`);
284
+ }
285
+ return readSnapshotResponse(res, signal, maxBytes);
286
+ });
287
+ }
288
+ async put(data, request) {
289
+ return snapshotRequest(this.transfer, request, async (signal) => {
290
+ const { headers, url } = await this._buildHeaders("PUT", data);
291
+ signal.throwIfAborted();
292
+ const res = await this.fetchImpl(url.toString(), {
293
+ method: "PUT",
294
+ headers,
295
+ body: data,
296
+ signal
297
+ });
298
+ discardSnapshotResponse(res);
299
+ if (!res.ok) {
300
+ throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}`);
301
+ }
302
+ });
303
+ }
304
+ };
305
+ function createSigV4SnapshotAdapter(options) {
306
+ return new SigV4SnapshotAdapter(options);
307
+ }
308
+ function createS3SnapshotAdapter(options) {
309
+ return createSigV4SnapshotAdapter(options);
310
+ }
311
+ function createR2SnapshotAdapter(options) {
312
+ const endpoint = options.endpoint ?? (options.accountId ? `https://${options.accountId}.r2.cloudflarestorage.com` : void 0);
313
+ return createSigV4SnapshotAdapter({
314
+ ...options,
315
+ endpoint,
316
+ region: options.region ?? "auto"
317
+ });
318
+ }
319
+
320
+ // src/remote-snapshot.ts
321
+ function createHttpSnapshotAdapter(options) {
322
+ const getUrl = options.getUrl;
323
+ const putUrl = options.putUrl ?? getUrl;
324
+ const headers = options.headers ?? {};
325
+ return {
326
+ async get(request) {
327
+ return snapshotRequest(options, request, async (signal, maxBytes) => {
328
+ const res = await fetch(getUrl, {
329
+ method: "GET",
330
+ headers,
331
+ signal
332
+ });
333
+ if (res.status === 404) {
334
+ discardSnapshotResponse(res);
335
+ return null;
336
+ }
337
+ if (!res.ok) {
338
+ discardSnapshotResponse(res);
339
+ throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
340
+ }
341
+ return readSnapshotResponse(res, signal, maxBytes);
342
+ });
343
+ },
344
+ async put(data, request) {
345
+ return snapshotRequest(options, request, async (signal) => {
346
+ const res = await fetch(putUrl, {
347
+ method: "PUT",
348
+ headers: {
349
+ "Content-Type": "application/octet-stream",
350
+ ...headers
351
+ },
352
+ body: data,
353
+ signal
354
+ });
355
+ discardSnapshotResponse(res);
356
+ if (!res.ok) {
357
+ throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
358
+ }
359
+ });
360
+ }
361
+ };
362
+ }
363
+ function createCustomSnapshotAdapter(adapter) {
364
+ return adapter;
365
+ }
366
+ function createMemorySnapshotAdapter() {
367
+ let stored = null;
368
+ return {
369
+ async get() {
370
+ return stored ? Buffer.from(stored) : null;
371
+ },
372
+ async put(data) {
373
+ stored = Buffer.from(data);
374
+ },
375
+ getBuffer() {
376
+ return stored;
377
+ },
378
+ clear() {
379
+ stored = null;
380
+ }
381
+ };
382
+ }
383
+
384
+ // src/adapters/node-redis.ts
385
+ import { EventEmitter } from "events";
386
+ var NodeRedisPipelineAdapter = class {
387
+ constructor(multiInstance, transactional = true) {
388
+ this.transactional = transactional;
389
+ this.multiInstance = multiInstance;
390
+ if (typeof multiInstance.pTTL === "function" || typeof multiInstance.pttl === "function") {
391
+ this.pttl = (key) => {
392
+ this.queueCommand(typeof multiInstance.pTTL === "function" ? "pTTL" : "pttl", [key]);
393
+ return this;
394
+ };
395
+ }
396
+ if (typeof multiInstance.eval === "function" || typeof multiInstance.addCommand === "function") {
397
+ this.eval = (script, numkeys, ...args) => {
398
+ if (typeof multiInstance.eval === "function") {
399
+ this.queueCommand("eval", [script, { keys: args.slice(0, numkeys).map(String), arguments: args.slice(numkeys).map(String) }]);
400
+ } else this.queueCommand("addCommand", [["EVAL", script, String(numkeys), ...args.map(String)]]);
401
+ return this;
402
+ };
403
+ }
404
+ }
405
+ transactional;
406
+ multiInstance;
407
+ operations = [];
408
+ pttl;
409
+ eval;
410
+ queueCommand(method, args) {
411
+ if (this.transactional) this.multiInstance[method](...args);
412
+ else this.operations.push(() => this.multiInstance[method](...args));
413
+ }
414
+ get(key) {
415
+ this.queueCommand("get", [key]);
416
+ return this;
417
+ }
418
+ set(key, value, ...args) {
419
+ const opts = parseSetArgs(args);
420
+ if (opts) {
421
+ this.queueCommand("set", [key, value, opts]);
422
+ } else {
423
+ this.queueCommand("set", [key, value]);
424
+ }
425
+ return this;
426
+ }
427
+ setex(key, seconds, value) {
428
+ if (typeof this.multiInstance.setEx === "function") {
429
+ this.queueCommand("setEx", [key, seconds, value]);
430
+ } else if (typeof this.multiInstance.setex === "function") {
431
+ this.queueCommand("setex", [key, seconds, value]);
432
+ } else {
433
+ this.queueCommand("set", [key, value, { EX: seconds }]);
434
+ }
435
+ return this;
436
+ }
437
+ del(...keys) {
438
+ if (keys.length === 0) return this;
439
+ this.queueCommand("del", [keys.length === 1 ? keys[0] : keys]);
440
+ return this;
441
+ }
442
+ expire(key, seconds) {
443
+ this.queueCommand("expire", [key, seconds]);
444
+ return this;
445
+ }
446
+ incr(key) {
447
+ this.queueCommand("incr", [key]);
448
+ return this;
449
+ }
450
+ sadd(key, ...members) {
451
+ if (members.length === 0) return this;
452
+ if (typeof this.multiInstance.sAdd === "function") {
453
+ this.queueCommand("sAdd", [key, members.length === 1 ? members[0] : members]);
454
+ } else {
455
+ this.queueCommand("sadd", [key, ...members]);
456
+ }
457
+ return this;
458
+ }
459
+ smembers(key) {
460
+ if (typeof this.multiInstance.sMembers === "function") {
461
+ this.queueCommand("sMembers", [key]);
462
+ } else {
463
+ this.queueCommand("smembers", [key]);
464
+ }
465
+ return this;
466
+ }
467
+ hset(key, value) {
468
+ if (typeof this.multiInstance.hSet === "function") {
469
+ this.queueCommand("hSet", [key, value]);
470
+ } else {
471
+ this.queueCommand("hset", [key, value]);
472
+ }
473
+ return this;
474
+ }
475
+ hgetall(key) {
476
+ if (typeof this.multiInstance.hGetAll === "function") {
477
+ this.queueCommand("hGetAll", [key]);
478
+ } else {
479
+ this.queueCommand("hgetall", [key]);
480
+ }
481
+ return this;
482
+ }
483
+ async exec() {
484
+ let raw;
485
+ if (!this.transactional) {
486
+ const results = await Promise.allSettled(this.operations.splice(0).map((operation) => Promise.resolve().then(operation)));
487
+ return results.map((result) => result.status === "fulfilled" ? [null, result.value] : [result.reason instanceof Error ? result.reason : new Error(String(result.reason)), null]);
488
+ }
489
+ try {
490
+ raw = await this.multiInstance.exec();
491
+ } catch (error) {
492
+ const replies = error.replies;
493
+ if (!Array.isArray(replies)) throw error;
494
+ raw = replies;
495
+ }
496
+ if (!raw) return null;
497
+ return raw.map((item) => {
498
+ if (item instanceof Error) {
499
+ return [item, null];
500
+ }
501
+ return [null, item];
502
+ });
503
+ }
504
+ };
505
+ var NodeRedisAdapter = class _NodeRedisAdapter extends EventEmitter {
506
+ client;
507
+ connecting = null;
508
+ pttl;
509
+ constructor(client) {
510
+ super();
511
+ if (!client) {
512
+ throw new Error("NodeRedisAdapter requires an active @redis/client instance");
513
+ }
514
+ this.client = client;
515
+ if (typeof client.pTTL === "function" || typeof client.pttl === "function") {
516
+ this.pttl = (key) => (client.pTTL ?? client.pttl).call(client, key);
517
+ }
518
+ }
519
+ get isOpen() {
520
+ return this.client.isOpen !== false;
521
+ }
522
+ async connect() {
523
+ if (this.connecting) return this.connecting;
524
+ if (typeof this.client.connect === "function" && !this.client.isOpen) {
525
+ this.connecting = Promise.resolve(this.client.connect());
526
+ try {
527
+ return await this.connecting;
528
+ } finally {
529
+ this.connecting = null;
530
+ }
531
+ }
532
+ return void 0;
533
+ }
534
+ async disconnect() {
535
+ if (typeof this.client.disconnect === "function" && this.client.isOpen !== false) {
536
+ try {
537
+ await this.client.disconnect();
538
+ } catch {
539
+ }
540
+ } else if (typeof this.client.quit === "function") {
541
+ try {
542
+ await this.client.quit();
543
+ } catch {
544
+ }
545
+ }
546
+ }
547
+ async quit() {
548
+ return this.disconnect();
549
+ }
550
+ async get(key) {
551
+ return await this.client.get(key) ?? null;
552
+ }
553
+ async set(key, value, ...args) {
554
+ const opts = parseSetArgs(args);
555
+ if (opts) {
556
+ return await this.client.set(key, value, opts);
557
+ }
558
+ return await this.client.set(key, value);
559
+ }
560
+ async setex(key, seconds, value) {
561
+ if (typeof this.client.setEx === "function") {
562
+ return await this.client.setEx(key, seconds, value);
563
+ }
564
+ if (typeof this.client.setex === "function") {
565
+ return await this.client.setex(key, seconds, value);
566
+ }
567
+ return await this.client.set(key, value, { EX: seconds });
568
+ }
569
+ async del(...keys) {
570
+ if (keys.length === 0) return 0;
571
+ const res = await this.client.del(keys.length === 1 ? keys[0] : keys);
572
+ return typeof res === "number" ? res : 0;
573
+ }
574
+ async ping() {
575
+ return await this.client.ping();
576
+ }
577
+ async expire(key, seconds) {
578
+ return await this.client.expire(key, seconds);
579
+ }
580
+ async incr(key) {
581
+ return await this.client.incr(key);
582
+ }
583
+ async eval(script, numkeys, ...args) {
584
+ if (typeof this.client.sendCommand === "function") {
585
+ return await this.client.sendCommand([
586
+ "EVAL",
587
+ script,
588
+ String(numkeys),
589
+ ...args.map(String)
590
+ ]);
591
+ }
592
+ if (typeof this.client.eval === "function") {
593
+ const keys = args.slice(0, numkeys).map(String);
594
+ const scriptArgs = args.slice(numkeys).map(String);
595
+ return await this.client.eval(script, {
596
+ keys,
597
+ arguments: scriptArgs
598
+ });
599
+ }
600
+ throw new Error("Redis client does not support EVAL or sendCommand");
601
+ }
602
+ multi() {
603
+ const multiInstance = this.client.multi();
604
+ return new NodeRedisPipelineAdapter(multiInstance);
605
+ }
606
+ pipeline() {
607
+ return new NodeRedisPipelineAdapter(this.client, false);
608
+ }
609
+ async smembers(key) {
610
+ if (typeof this.client.sMembers === "function") {
611
+ return await this.client.sMembers(key);
612
+ }
613
+ if (typeof this.client.smembers === "function") {
614
+ return await this.client.smembers(key);
615
+ }
616
+ return [];
617
+ }
618
+ async sadd(key, ...members) {
619
+ if (members.length === 0) return 0;
620
+ if (typeof this.client.sAdd === "function") {
621
+ return await this.client.sAdd(key, members.length === 1 ? members[0] : members);
622
+ }
623
+ if (typeof this.client.sadd === "function") {
624
+ return await this.client.sadd(key, ...members);
625
+ }
626
+ return 0;
627
+ }
628
+ async mget(keys) {
629
+ if (keys.length === 0) return [];
630
+ if (typeof this.client.mGet === "function") {
631
+ return await this.client.mGet(keys);
632
+ }
633
+ if (typeof this.client.mget === "function") {
634
+ return await this.client.mget(keys);
635
+ }
636
+ return [];
637
+ }
638
+ async hset(key, value) {
639
+ if (typeof this.client.hSet === "function") {
640
+ return await this.client.hSet(key, value);
641
+ }
642
+ if (typeof this.client.hset === "function") {
643
+ return await this.client.hset(key, value);
644
+ }
645
+ return void 0;
646
+ }
647
+ async hgetall(key) {
648
+ if (typeof this.client.hGetAll === "function") {
649
+ return await this.client.hGetAll(key) ?? {};
650
+ }
651
+ if (typeof this.client.hgetall === "function") {
652
+ return await this.client.hgetall(key) ?? {};
653
+ }
654
+ return {};
655
+ }
656
+ async publish(channel, message) {
657
+ return await this.client.publish(channel, message);
658
+ }
659
+ async subscribe(...channels) {
660
+ if (channels.length === 0) return void 0;
661
+ await this.connect();
662
+ return await this.client.subscribe(channels, (message, channel) => this.emit("message", channel, message));
663
+ }
664
+ async unsubscribe(...channels) {
665
+ if (!channels.length || !this.isOpen) return void 0;
666
+ return this.client.unsubscribe(channels);
667
+ }
668
+ async xread(...args) {
669
+ await this.connect();
670
+ const raw = await this.client.sendCommand(["XREAD", ...args.map(String)]);
671
+ if (raw == null) return null;
672
+ if (raw instanceof Map) return [...raw.entries()];
673
+ if (!Array.isArray(raw) && typeof raw === "object") return Object.entries(raw);
674
+ return raw;
675
+ }
676
+ async xadd(...args) {
677
+ return this.client.sendCommand(["XADD", ...args.map(String)]);
678
+ }
679
+ async xrange(...args) {
680
+ return this.client.sendCommand(["XRANGE", ...args.map(String)]);
681
+ }
682
+ async xrevrange(...args) {
683
+ return this.client.sendCommand(["XREVRANGE", ...args.map(String)]);
684
+ }
685
+ scanStream(options) {
686
+ const ee = new EventEmitter();
687
+ const pattern = options?.match ?? "*";
688
+ const count = options?.count ?? 100;
689
+ queueMicrotask(async () => {
690
+ try {
691
+ if (typeof this.client.scanIterator === "function") {
692
+ const batch = [];
693
+ for await (const keys of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
694
+ batch.push(...Array.isArray(keys) ? keys : [keys]);
695
+ if (batch.length >= count) {
696
+ ee.emit("data", [...batch]);
697
+ batch.length = 0;
698
+ }
699
+ }
700
+ if (batch.length > 0) {
701
+ ee.emit("data", batch);
702
+ }
703
+ ee.emit("end");
704
+ } else if (typeof this.client.sendCommand === "function") {
705
+ let cursor = "0";
706
+ do {
707
+ const raw = await this.client.sendCommand([
708
+ "SCAN",
709
+ cursor,
710
+ "MATCH",
711
+ pattern,
712
+ "COUNT",
713
+ String(count)
714
+ ]);
715
+ cursor = String(raw[0]);
716
+ const batch = raw[1];
717
+ if (batch?.length) {
718
+ ee.emit("data", batch);
719
+ }
720
+ } while (cursor !== "0");
721
+ ee.emit("end");
722
+ } else {
723
+ ee.emit("end");
724
+ }
725
+ } catch (err) {
726
+ ee.emit("error", err);
727
+ }
728
+ });
729
+ return ee;
730
+ }
731
+ duplicate() {
732
+ if (typeof this.client.duplicate === "function") {
733
+ return new _NodeRedisAdapter(this.client.duplicate());
734
+ }
735
+ return this;
736
+ }
737
+ on(event, listener) {
738
+ if (event === "message" || event === "smessage") return super.on(event, listener);
739
+ if (typeof this.client.on === "function") {
740
+ this.client.on(event === "close" ? "end" : event, listener);
741
+ }
742
+ return this;
743
+ }
744
+ once(event, listener) {
745
+ if (event === "message" || event === "smessage") return super.once(event, listener);
746
+ if (typeof this.client.once === "function") {
747
+ this.client.once(event === "close" ? "end" : event, listener);
748
+ }
749
+ return this;
750
+ }
751
+ removeListener(event, listener) {
752
+ super.removeListener(event, listener);
753
+ this.client.removeListener?.(event === "close" ? "end" : event, listener);
754
+ return this;
755
+ }
756
+ };
757
+ function createNodeRedisAdapter(client) {
758
+ if (client instanceof NodeRedisAdapter) return client;
759
+ return new NodeRedisAdapter(client);
760
+ }
761
+ function parseSetArgs(args) {
762
+ if (args.length === 0) return void 0;
763
+ const opts = {};
764
+ for (let i = 0; i < args.length; i++) {
765
+ const a = String(args[i]).toUpperCase();
766
+ if (a === "EX" && i + 1 < args.length) {
767
+ opts.EX = Number(args[++i]);
768
+ } else if (a === "PX" && i + 1 < args.length) {
769
+ opts.PX = Number(args[++i]);
770
+ } else if (a === "NX") {
771
+ opts.NX = true;
772
+ } else if (a === "XX") {
773
+ opts.XX = true;
774
+ }
775
+ }
776
+ return Object.keys(opts).length > 0 ? opts : void 0;
777
+ }
778
+
779
+ // src/utils/tracing.ts
780
+ function parseTraceParent(header) {
781
+ if (!header || typeof header !== "string") return null;
782
+ const parts = header.trim().split("-");
783
+ if (parts.length < 4) return null;
784
+ const [version, traceId, spanId, flagsStr] = parts;
785
+ if (version.length !== 2 || traceId.length !== 32 || spanId.length !== 16 || flagsStr.length !== 2) {
786
+ return null;
787
+ }
788
+ if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) {
789
+ return null;
790
+ }
791
+ const traceFlags = parseInt(flagsStr, 16);
792
+ if (Number.isNaN(traceFlags)) return null;
793
+ return {
794
+ version,
795
+ traceId,
796
+ spanId,
797
+ traceFlags
798
+ };
799
+ }
800
+ function formatTraceParent(traceId, spanId, traceFlags = 1) {
801
+ const flagsHex = traceFlags.toString(16).padStart(2, "0");
802
+ return `00-${traceId}-${spanId}-${flagsHex}`;
803
+ }
804
+
805
+ // src/origin-capacity.ts
806
+ var OriginCapacityLimiter = class {
807
+ work;
808
+ pending = /* @__PURE__ */ new Set();
809
+ closed = false;
810
+ started = 0;
811
+ completed = 0;
812
+ cancelled = 0;
813
+ timedOut = 0;
814
+ constructor(options) {
815
+ this.work = new WorkLimit(positiveLimit(options?.maxConcurrent, 1024, "maxConcurrent"), "shared origin work");
816
+ }
817
+ async run(origin, options = {}) {
818
+ if (typeof origin !== "function") throw new TypeError("Origin work must be a function");
819
+ const { signal, timeoutMs, weight = 1 } = options;
820
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647)) {
821
+ throw new RangeError("timeoutMs must be finite and between 0 and 2147483647");
822
+ }
823
+ if (this.closed) throw new Error("Origin capacity limiter is closed");
824
+ if (signal?.aborted) {
825
+ this.cancelled++;
826
+ throw signal.reason ?? new DOMException("Origin caller cancelled", "AbortError");
827
+ }
828
+ if (timeoutMs === 0) {
829
+ this.timedOut++;
830
+ throw new DOMException("Origin request deadline exceeded", "TimeoutError");
831
+ }
832
+ const release = this.work.acquire(weight);
833
+ const controller = new AbortController();
834
+ let timer;
835
+ let abandon;
836
+ const cancelled = new Promise((_resolve, reject) => {
837
+ abandon = (reason) => {
838
+ if (controller.signal.aborted) return;
839
+ reject(reason);
840
+ controller.abort(reason);
841
+ clearTimeout(timer);
842
+ signal?.removeEventListener("abort", onCallerAbort);
843
+ };
844
+ });
845
+ const onCallerAbort = () => {
846
+ if (controller.signal.aborted) return;
847
+ this.cancelled++;
848
+ abandon(signal?.reason ?? new DOMException("Origin caller cancelled", "AbortError"));
849
+ };
850
+ const onClose = (reason) => {
851
+ if (controller.signal.aborted) return;
852
+ this.cancelled++;
853
+ abandon(reason);
854
+ };
855
+ this.pending.add(onClose);
856
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
857
+ if (timeoutMs !== void 0) {
858
+ timer = setTimeout(() => {
859
+ if (controller.signal.aborted) return;
860
+ this.timedOut++;
861
+ abandon(new DOMException("Origin request deadline exceeded", "TimeoutError"));
862
+ }, Math.ceil(timeoutMs));
863
+ }
864
+ this.started++;
865
+ let physical;
866
+ try {
867
+ physical = Promise.resolve(origin(controller.signal));
868
+ } catch (error) {
869
+ physical = Promise.reject(error);
870
+ }
871
+ const finish = () => {
872
+ clearTimeout(timer);
873
+ signal?.removeEventListener("abort", onCallerAbort);
874
+ this.pending.delete(onClose);
875
+ release();
876
+ this.completed++;
877
+ };
878
+ const settled = physical.then((value) => {
879
+ finish();
880
+ return value;
881
+ }, (error) => {
882
+ finish();
883
+ throw error;
884
+ });
885
+ return Promise.race([settled, cancelled]);
886
+ }
887
+ /** Reject new work and signal active origins. Ignored cancellation still occupies capacity. */
888
+ close() {
889
+ if (this.closed) return;
890
+ this.closed = true;
891
+ const reason = new DOMException("Origin capacity limiter is closed", "AbortError");
892
+ for (const abort of this.pending) abort(reason);
893
+ }
894
+ metrics() {
895
+ return {
896
+ ...this.work.metrics(),
897
+ started: this.started,
898
+ completed: this.completed,
899
+ cancelled: this.cancelled,
900
+ timedOut: this.timedOut,
901
+ closed: this.closed
902
+ };
903
+ }
904
+ /** Export once per shared origin budget, separately from per-namespace cache series. */
905
+ toPrometheusText(prefix = "tricache_origin") {
906
+ if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(prefix)) throw new TypeError("Invalid Prometheus metric prefix");
907
+ const metrics = this.metrics();
908
+ const lines = [];
909
+ for (const [suffix, value, type, help] of [
910
+ ["active", metrics.active, "gauge", "Reserved physical origin work slots"],
911
+ ["capacity", metrics.capacity, "gauge", "Configured physical origin work capacity"],
912
+ ["closed", metrics.closed ? 1 : 0, "gauge", "Origin budget is closed to new work"],
913
+ ["rejections_total", metrics.rejected, "counter", "Origin admissions rejected at capacity"],
914
+ ["started_total", metrics.started, "counter", "Physical origin invocations started"],
915
+ ["completed_total", metrics.completed, "counter", "Physical origin invocations settled"],
916
+ ["cancelled_total", metrics.cancelled, "counter", "Origin waits cancelled by callers or shutdown"],
917
+ ["timeouts_total", metrics.timedOut, "counter", "Origin waits rejected by their deadline"]
918
+ ]) {
919
+ const name = `${prefix}_${suffix}`;
920
+ lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name} ${value}`);
921
+ }
922
+ return lines.join("\n") + "\n";
923
+ }
924
+ };
71
925
  export {
72
926
  AutoPipeliner,
927
+ CacheCapacityError,
73
928
  CacheCodec,
74
929
  CacheEncryption,
930
+ CacheInvalidationUnavailableError,
75
931
  CachePriority,
76
932
  CacheService,
77
933
  DEFAULT_AUTONOMOUS_L1_CEILING_BYTES,
@@ -82,6 +938,7 @@ export {
82
938
  MIN_AUTONOMOUS_L1_FLOOR_BYTES,
83
939
  Murmur3BloomFilter,
84
940
  NodeRedisAdapter,
941
+ OriginCapacityLimiter,
85
942
  ProcessTerminationBus,
86
943
  SigV4SnapshotAdapter,
87
944
  SmartMemoryCache,