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
@@ -1,704 +0,0 @@
1
- // src/sigv4-snapshot-adapter.ts
2
- var EMPTY_STRING_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
3
- async function sha256Hex(data) {
4
- const buf = typeof data === "string" ? new TextEncoder().encode(data) : data;
5
- const digest = await crypto.subtle.digest("SHA-256", buf);
6
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
7
- }
8
- async function hmac(key, data) {
9
- let cryptoKey;
10
- if (key instanceof CryptoKey) {
11
- cryptoKey = key;
12
- } else {
13
- const rawBuf = key instanceof Uint8Array ? key.buffer.slice(key.byteOffset, key.byteOffset + key.byteLength) : key;
14
- cryptoKey = await crypto.subtle.importKey(
15
- "raw",
16
- rawBuf,
17
- { name: "HMAC", hash: "SHA-256" },
18
- false,
19
- ["sign"]
20
- );
21
- }
22
- return await crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(data));
23
- }
24
- function encodeRfc3986(str) {
25
- return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
26
- }
27
- function encodePath(path) {
28
- return path.split("/").map(encodeRfc3986).join("/");
29
- }
30
- var SigV4SnapshotAdapter = class {
31
- bucket;
32
- key;
33
- region;
34
- endpoint;
35
- accessKeyId;
36
- secretAccessKey;
37
- sessionToken;
38
- forcePathStyle;
39
- fetchImpl;
40
- constructor(options) {
41
- this.bucket = options.bucket;
42
- this.key = options.key.replace(/^\/+/, "");
43
- this.region = options.region ?? (options.endpoint?.includes("r2.cloudflarestorage.com") ? "auto" : "us-east-1");
44
- this.endpoint = options.endpoint;
45
- const accessKey = options.accessKeyId ?? (typeof process !== "undefined" ? process.env?.AWS_ACCESS_KEY_ID : void 0);
46
- const secretKey = options.secretAccessKey ?? (typeof process !== "undefined" ? process.env?.AWS_SECRET_ACCESS_KEY : void 0);
47
- const token = options.sessionToken ?? (typeof process !== "undefined" ? process.env?.AWS_SESSION_TOKEN : void 0);
48
- if (!accessKey || !secretKey) {
49
- throw new Error(
50
- "SigV4SnapshotAdapter: AWS credentials missing. Provide accessKeyId and secretAccessKey or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY."
51
- );
52
- }
53
- this.accessKeyId = accessKey;
54
- this.secretAccessKey = secretKey;
55
- this.sessionToken = token;
56
- this.forcePathStyle = options.forcePathStyle ?? Boolean(options.endpoint);
57
- this.fetchImpl = options.fetch ?? globalThis.fetch;
58
- }
59
- _resolveTarget() {
60
- const encodedKey = encodePath(this.key);
61
- if (this.endpoint) {
62
- const base = new URL(this.endpoint);
63
- const basePath = base.pathname.replace(/\/+$/, "");
64
- if (this.forcePathStyle) {
65
- const canonicalUri2 = `${basePath}/${encodeRfc3986(this.bucket)}/${encodedKey}`;
66
- const url2 = new URL(canonicalUri2, base.origin);
67
- return { url: url2, canonicalUri: canonicalUri2, host: url2.host };
68
- } else {
69
- const host2 = `${this.bucket}.${base.host}`;
70
- const canonicalUri2 = `${basePath}/${encodedKey}`;
71
- const url2 = new URL(canonicalUri2, `${base.protocol}//${host2}`);
72
- return { url: url2, canonicalUri: canonicalUri2, host: host2 };
73
- }
74
- }
75
- if (this.forcePathStyle) {
76
- const host2 = this.region === "us-east-1" ? "s3.amazonaws.com" : `s3.${this.region}.amazonaws.com`;
77
- const canonicalUri2 = `/${encodeRfc3986(this.bucket)}/${encodedKey}`;
78
- const url2 = new URL(`https://${host2}${canonicalUri2}`);
79
- return { url: url2, canonicalUri: canonicalUri2, host: host2 };
80
- }
81
- const host = this.region === "us-east-1" ? `${this.bucket}.s3.amazonaws.com` : `${this.bucket}.s3.${this.region}.amazonaws.com`;
82
- const canonicalUri = `/${encodedKey}`;
83
- const url = new URL(`https://${host}${canonicalUri}`);
84
- return { url, canonicalUri, host };
85
- }
86
- async _buildHeaders(method, body) {
87
- const { url, canonicalUri, host } = this._resolveTarget();
88
- const now = /* @__PURE__ */ new Date();
89
- const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
90
- const dateStamp = amzDate.slice(0, 8);
91
- const service = "s3";
92
- const payloadHash = body ? await sha256Hex(body) : EMPTY_STRING_SHA256;
93
- const headersToSign = {
94
- host,
95
- "x-amz-content-sha256": payloadHash,
96
- "x-amz-date": amzDate
97
- };
98
- if (this.sessionToken) {
99
- headersToSign["x-amz-security-token"] = this.sessionToken;
100
- }
101
- if (body) {
102
- headersToSign["content-type"] = "application/octet-stream";
103
- }
104
- const sortedHeaderKeys = Object.keys(headersToSign).sort();
105
- const canonicalHeaders = sortedHeaderKeys.map((k) => `${k}:${headersToSign[k]}
106
- `).join("");
107
- const signedHeaders = sortedHeaderKeys.join(";");
108
- const canonicalRequest = [
109
- method,
110
- canonicalUri,
111
- "",
112
- // canonical query string
113
- canonicalHeaders,
114
- signedHeaders,
115
- payloadHash
116
- ].join("\n");
117
- const credentialScope = `${dateStamp}/${this.region}/${service}/aws4_request`;
118
- const stringToSign = [
119
- "AWS4-HMAC-SHA256",
120
- amzDate,
121
- credentialScope,
122
- await sha256Hex(canonicalRequest)
123
- ].join("\n");
124
- const kDate = await hmac(new TextEncoder().encode(`AWS4${this.secretAccessKey}`), dateStamp);
125
- const kRegion = await hmac(kDate, this.region);
126
- const kService = await hmac(kRegion, service);
127
- const kSigning = await hmac(kService, "aws4_request");
128
- const signatureBytes = await hmac(kSigning, stringToSign);
129
- const signature = Array.from(new Uint8Array(signatureBytes)).map((b) => b.toString(16).padStart(2, "0")).join("");
130
- const authHeader = `AWS4-HMAC-SHA256 Credential=${this.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
131
- const finalHeaders = {
132
- ...headersToSign,
133
- Authorization: authHeader
134
- };
135
- return { headers: finalHeaders, url };
136
- }
137
- async get() {
138
- const { headers, url } = await this._buildHeaders("GET");
139
- const res = await this.fetchImpl(url.toString(), {
140
- method: "GET",
141
- headers
142
- });
143
- if (res.status === 404) return null;
144
- if (!res.ok) {
145
- const errBody = await res.text().catch(() => "");
146
- throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
147
- }
148
- const ab = await res.arrayBuffer();
149
- return Buffer.from(ab);
150
- }
151
- async put(data) {
152
- const { headers, url } = await this._buildHeaders("PUT", data);
153
- const res = await this.fetchImpl(url.toString(), {
154
- method: "PUT",
155
- headers,
156
- body: data
157
- });
158
- if (!res.ok) {
159
- const errBody = await res.text().catch(() => "");
160
- throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
161
- }
162
- }
163
- };
164
- function createSigV4SnapshotAdapter(options) {
165
- return new SigV4SnapshotAdapter(options);
166
- }
167
- function createS3SnapshotAdapter(options) {
168
- return createSigV4SnapshotAdapter(options);
169
- }
170
- function createR2SnapshotAdapter(options) {
171
- const endpoint = options.endpoint ?? (options.accountId ? `https://${options.accountId}.r2.cloudflarestorage.com` : void 0);
172
- return createSigV4SnapshotAdapter({
173
- ...options,
174
- endpoint,
175
- region: options.region ?? "auto"
176
- });
177
- }
178
-
179
- // src/remote-snapshot.ts
180
- function createHttpSnapshotAdapter(options) {
181
- const getUrl = options.getUrl;
182
- const putUrl = options.putUrl ?? getUrl;
183
- const headers = options.headers ?? {};
184
- return {
185
- async get() {
186
- const res = await fetch(getUrl, {
187
- method: "GET",
188
- headers
189
- });
190
- if (res.status === 404) return null;
191
- if (!res.ok) {
192
- throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
193
- }
194
- const ab = await res.arrayBuffer();
195
- return Buffer.from(ab);
196
- },
197
- async put(data) {
198
- const res = await fetch(putUrl, {
199
- method: "PUT",
200
- headers: {
201
- "Content-Type": "application/octet-stream",
202
- ...headers
203
- },
204
- body: data
205
- });
206
- if (!res.ok) {
207
- throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
208
- }
209
- }
210
- };
211
- }
212
- function createCustomSnapshotAdapter(adapter) {
213
- return adapter;
214
- }
215
- function createMemorySnapshotAdapter() {
216
- let stored = null;
217
- return {
218
- async get() {
219
- return stored ? Buffer.from(stored) : null;
220
- },
221
- async put(data) {
222
- stored = Buffer.from(data);
223
- },
224
- getBuffer() {
225
- return stored;
226
- },
227
- clear() {
228
- stored = null;
229
- }
230
- };
231
- }
232
-
233
- // src/cross-region.ts
234
- function createHttpMeshRelay(options) {
235
- const peerUrls = options.peerUrls;
236
- const timeoutMs = options.timeoutMs ?? 3e3;
237
- const fetcher = options.fetchFn ?? globalThis.fetch;
238
- const headers = {
239
- "Content-Type": "application/json"
240
- };
241
- if (options.authSecret) {
242
- headers["Authorization"] = `Bearer ${options.authSecret}`;
243
- headers["X-TriCache-Auth"] = options.authSecret;
244
- }
245
- return {
246
- async broadcast(event) {
247
- if (!peerUrls.length) return;
248
- const body = JSON.stringify(event);
249
- await Promise.allSettled(
250
- peerUrls.map(async (url) => {
251
- const res = await fetcher(url, {
252
- method: "POST",
253
- headers,
254
- body,
255
- signal: AbortSignal.timeout(timeoutMs)
256
- });
257
- if (!res.ok) {
258
- throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
259
- }
260
- })
261
- );
262
- }
263
- };
264
- }
265
- function createCustomCrossRegionRelay(relay) {
266
- return relay;
267
- }
268
- function createMemoryCrossRegionRelay() {
269
- const handlers = /* @__PURE__ */ new Map();
270
- let broadcastCount = 0;
271
- return {
272
- async broadcast(event) {
273
- broadcastCount++;
274
- const promises = [];
275
- for (const [region, set] of handlers.entries()) {
276
- if (region !== event.originRegion) {
277
- for (const fn of set) {
278
- promises.push(Promise.resolve(fn(event)));
279
- }
280
- }
281
- }
282
- await Promise.allSettled(promises);
283
- },
284
- register(region, handler) {
285
- if (!handlers.has(region)) {
286
- handlers.set(region, /* @__PURE__ */ new Set());
287
- }
288
- handlers.get(region).add(handler);
289
- return () => {
290
- handlers.get(region)?.delete(handler);
291
- };
292
- },
293
- getBroadcastCount() {
294
- return broadcastCount;
295
- },
296
- clear() {
297
- handlers.clear();
298
- broadcastCount = 0;
299
- }
300
- };
301
- }
302
- function createCrossRegionWebhookHandler(cache, options = {}) {
303
- return async function handleCrossRegionWebhook(req) {
304
- if (options.authSecret) {
305
- const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
306
- const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
307
- const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
308
- const provided = typeof customHeader === "string" ? customHeader : bearer;
309
- if (!provided || provided !== options.authSecret) {
310
- return {
311
- status: 401,
312
- body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
313
- };
314
- }
315
- }
316
- try {
317
- let event;
318
- if (typeof req.body === "string") {
319
- event = JSON.parse(req.body);
320
- } else if (req.body && typeof req.body === "object") {
321
- event = req.body;
322
- } else {
323
- return {
324
- status: 400,
325
- body: { ok: false, message: "Invalid payload: body must be JSON object" }
326
- };
327
- }
328
- const accepted = await cache.receiveCrossRegionInvalidation(event);
329
- return {
330
- status: 200,
331
- body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
332
- };
333
- } catch (err) {
334
- return {
335
- status: 400,
336
- body: { ok: false, message: err.message }
337
- };
338
- }
339
- };
340
- }
341
-
342
- // src/adapters/node-redis.ts
343
- import { EventEmitter } from "events";
344
- var NodeRedisPipelineAdapter = class {
345
- multiInstance;
346
- constructor(multiInstance) {
347
- this.multiInstance = multiInstance;
348
- }
349
- get(key) {
350
- this.multiInstance.get(key);
351
- return this;
352
- }
353
- set(key, value, ...args) {
354
- const opts = parseSetArgs(args);
355
- if (opts) {
356
- this.multiInstance.set(key, value, opts);
357
- } else {
358
- this.multiInstance.set(key, value);
359
- }
360
- return this;
361
- }
362
- setex(key, seconds, value) {
363
- if (typeof this.multiInstance.setEx === "function") {
364
- this.multiInstance.setEx(key, seconds, value);
365
- } else if (typeof this.multiInstance.setex === "function") {
366
- this.multiInstance.setex(key, seconds, value);
367
- } else {
368
- this.multiInstance.set(key, value, { EX: seconds });
369
- }
370
- return this;
371
- }
372
- del(...keys) {
373
- if (keys.length === 0) return this;
374
- this.multiInstance.del(keys.length === 1 ? keys[0] : keys);
375
- return this;
376
- }
377
- expire(key, seconds) {
378
- this.multiInstance.expire(key, seconds);
379
- return this;
380
- }
381
- incr(key) {
382
- this.multiInstance.incr(key);
383
- return this;
384
- }
385
- sadd(key, ...members) {
386
- if (members.length === 0) return this;
387
- if (typeof this.multiInstance.sAdd === "function") {
388
- this.multiInstance.sAdd(key, members.length === 1 ? members[0] : members);
389
- } else {
390
- this.multiInstance.sadd(key, ...members);
391
- }
392
- return this;
393
- }
394
- smembers(key) {
395
- if (typeof this.multiInstance.sMembers === "function") {
396
- this.multiInstance.sMembers(key);
397
- } else {
398
- this.multiInstance.smembers(key);
399
- }
400
- return this;
401
- }
402
- hset(key, value) {
403
- if (typeof this.multiInstance.hSet === "function") {
404
- this.multiInstance.hSet(key, value);
405
- } else {
406
- this.multiInstance.hset(key, value);
407
- }
408
- return this;
409
- }
410
- hgetall(key) {
411
- if (typeof this.multiInstance.hGetAll === "function") {
412
- this.multiInstance.hGetAll(key);
413
- } else {
414
- this.multiInstance.hgetall(key);
415
- }
416
- return this;
417
- }
418
- async exec() {
419
- const raw = await this.multiInstance.exec();
420
- if (!raw) return null;
421
- return raw.map((item) => {
422
- if (item instanceof Error) {
423
- return [item, null];
424
- }
425
- return [null, item];
426
- });
427
- }
428
- };
429
- var NodeRedisAdapter = class _NodeRedisAdapter {
430
- client;
431
- constructor(client) {
432
- if (!client) {
433
- throw new Error("NodeRedisAdapter requires an active @redis/client instance");
434
- }
435
- this.client = client;
436
- }
437
- get isOpen() {
438
- return this.client.isOpen !== false;
439
- }
440
- async connect() {
441
- if (typeof this.client.connect === "function" && !this.client.isOpen) {
442
- return await this.client.connect();
443
- }
444
- return void 0;
445
- }
446
- async disconnect() {
447
- if (typeof this.client.disconnect === "function" && this.client.isOpen !== false) {
448
- try {
449
- await this.client.disconnect();
450
- } catch {
451
- }
452
- } else if (typeof this.client.quit === "function") {
453
- try {
454
- await this.client.quit();
455
- } catch {
456
- }
457
- }
458
- }
459
- async quit() {
460
- return this.disconnect();
461
- }
462
- async get(key) {
463
- return await this.client.get(key) ?? null;
464
- }
465
- async set(key, value, ...args) {
466
- const opts = parseSetArgs(args);
467
- if (opts) {
468
- return await this.client.set(key, value, opts);
469
- }
470
- return await this.client.set(key, value);
471
- }
472
- async setex(key, seconds, value) {
473
- if (typeof this.client.setEx === "function") {
474
- return await this.client.setEx(key, seconds, value);
475
- }
476
- if (typeof this.client.setex === "function") {
477
- return await this.client.setex(key, seconds, value);
478
- }
479
- return await this.client.set(key, value, { EX: seconds });
480
- }
481
- async del(...keys) {
482
- if (keys.length === 0) return 0;
483
- const res = await this.client.del(keys.length === 1 ? keys[0] : keys);
484
- return typeof res === "number" ? res : 0;
485
- }
486
- async ping() {
487
- return await this.client.ping();
488
- }
489
- async expire(key, seconds) {
490
- return await this.client.expire(key, seconds);
491
- }
492
- async incr(key) {
493
- return await this.client.incr(key);
494
- }
495
- async eval(script, numkeys, ...args) {
496
- if (typeof this.client.sendCommand === "function") {
497
- return await this.client.sendCommand([
498
- "EVAL",
499
- script,
500
- String(numkeys),
501
- ...args.map(String)
502
- ]);
503
- }
504
- if (typeof this.client.eval === "function") {
505
- const keys = args.slice(0, numkeys).map(String);
506
- const scriptArgs = args.slice(numkeys).map(String);
507
- return await this.client.eval(script, {
508
- keys,
509
- arguments: scriptArgs
510
- });
511
- }
512
- throw new Error("Redis client does not support EVAL or sendCommand");
513
- }
514
- multi() {
515
- const multiInstance = this.client.multi();
516
- return new NodeRedisPipelineAdapter(multiInstance);
517
- }
518
- pipeline() {
519
- return this.multi();
520
- }
521
- async smembers(key) {
522
- if (typeof this.client.sMembers === "function") {
523
- return await this.client.sMembers(key);
524
- }
525
- if (typeof this.client.smembers === "function") {
526
- return await this.client.smembers(key);
527
- }
528
- return [];
529
- }
530
- async sadd(key, ...members) {
531
- if (members.length === 0) return 0;
532
- if (typeof this.client.sAdd === "function") {
533
- return await this.client.sAdd(key, members.length === 1 ? members[0] : members);
534
- }
535
- if (typeof this.client.sadd === "function") {
536
- return await this.client.sadd(key, ...members);
537
- }
538
- return 0;
539
- }
540
- async mget(keys) {
541
- if (keys.length === 0) return [];
542
- if (typeof this.client.mGet === "function") {
543
- return await this.client.mGet(keys);
544
- }
545
- if (typeof this.client.mget === "function") {
546
- return await this.client.mget(keys);
547
- }
548
- return [];
549
- }
550
- async hset(key, value) {
551
- if (typeof this.client.hSet === "function") {
552
- return await this.client.hSet(key, value);
553
- }
554
- if (typeof this.client.hset === "function") {
555
- return await this.client.hset(key, value);
556
- }
557
- return void 0;
558
- }
559
- async hgetall(key) {
560
- if (typeof this.client.hGetAll === "function") {
561
- return await this.client.hGetAll(key) ?? {};
562
- }
563
- if (typeof this.client.hgetall === "function") {
564
- return await this.client.hgetall(key) ?? {};
565
- }
566
- return {};
567
- }
568
- async publish(channel, message) {
569
- return await this.client.publish(channel, message);
570
- }
571
- async subscribe(...channels) {
572
- if (channels.length === 0) return void 0;
573
- return await this.client.subscribe(channels);
574
- }
575
- scanStream(options) {
576
- const ee = new EventEmitter();
577
- const pattern = options?.match ?? "*";
578
- const count = options?.count ?? 100;
579
- queueMicrotask(async () => {
580
- try {
581
- if (typeof this.client.scanIterator === "function") {
582
- const batch = [];
583
- for await (const key of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
584
- batch.push(key);
585
- if (batch.length >= count) {
586
- ee.emit("data", [...batch]);
587
- batch.length = 0;
588
- }
589
- }
590
- if (batch.length > 0) {
591
- ee.emit("data", batch);
592
- }
593
- ee.emit("end");
594
- } else if (typeof this.client.sendCommand === "function") {
595
- let cursor = "0";
596
- do {
597
- const raw = await this.client.sendCommand([
598
- "SCAN",
599
- cursor,
600
- "MATCH",
601
- pattern,
602
- "COUNT",
603
- String(count)
604
- ]);
605
- cursor = String(raw[0]);
606
- const batch = raw[1];
607
- if (batch?.length) {
608
- ee.emit("data", batch);
609
- }
610
- } while (cursor !== "0");
611
- ee.emit("end");
612
- } else {
613
- ee.emit("end");
614
- }
615
- } catch (err) {
616
- ee.emit("error", err);
617
- }
618
- });
619
- return ee;
620
- }
621
- duplicate() {
622
- if (typeof this.client.duplicate === "function") {
623
- return new _NodeRedisAdapter(this.client.duplicate());
624
- }
625
- return this;
626
- }
627
- on(event, listener) {
628
- if (typeof this.client.on === "function") {
629
- this.client.on(event, listener);
630
- }
631
- return this;
632
- }
633
- once(event, listener) {
634
- if (typeof this.client.once === "function") {
635
- this.client.once(event, listener);
636
- }
637
- return this;
638
- }
639
- };
640
- function createNodeRedisAdapter(client) {
641
- if (client instanceof NodeRedisAdapter) return client;
642
- return new NodeRedisAdapter(client);
643
- }
644
- function parseSetArgs(args) {
645
- if (args.length === 0) return void 0;
646
- const opts = {};
647
- for (let i = 0; i < args.length; i++) {
648
- const a = String(args[i]).toUpperCase();
649
- if (a === "EX" && i + 1 < args.length) {
650
- opts.EX = Number(args[++i]);
651
- } else if (a === "PX" && i + 1 < args.length) {
652
- opts.PX = Number(args[++i]);
653
- } else if (a === "NX") {
654
- opts.NX = true;
655
- } else if (a === "XX") {
656
- opts.XX = true;
657
- }
658
- }
659
- return Object.keys(opts).length > 0 ? opts : void 0;
660
- }
661
-
662
- // src/utils/tracing.ts
663
- function parseTraceParent(header) {
664
- if (!header || typeof header !== "string") return null;
665
- const parts = header.trim().split("-");
666
- if (parts.length < 4) return null;
667
- const [version, traceId, spanId, flagsStr] = parts;
668
- if (version.length !== 2 || traceId.length !== 32 || spanId.length !== 16 || flagsStr.length !== 2) {
669
- return null;
670
- }
671
- if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) {
672
- return null;
673
- }
674
- const traceFlags = parseInt(flagsStr, 16);
675
- if (Number.isNaN(traceFlags)) return null;
676
- return {
677
- version,
678
- traceId,
679
- spanId,
680
- traceFlags
681
- };
682
- }
683
- function formatTraceParent(traceId, spanId, traceFlags = 1) {
684
- const flagsHex = traceFlags.toString(16).padStart(2, "0");
685
- return `00-${traceId}-${spanId}-${flagsHex}`;
686
- }
687
-
688
- export {
689
- SigV4SnapshotAdapter,
690
- createSigV4SnapshotAdapter,
691
- createS3SnapshotAdapter,
692
- createR2SnapshotAdapter,
693
- createHttpSnapshotAdapter,
694
- createCustomSnapshotAdapter,
695
- createMemorySnapshotAdapter,
696
- createHttpMeshRelay,
697
- createCustomCrossRegionRelay,
698
- createMemoryCrossRegionRelay,
699
- createCrossRegionWebhookHandler,
700
- NodeRedisAdapter,
701
- createNodeRedisAdapter,
702
- parseTraceParent,
703
- formatTraceParent
704
- };