tricache 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +78 -90
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/{cache-service-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -1,666 +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/adapters/node-redis.ts
234
- import { EventEmitter } from "events";
235
- var NodeRedisPipelineAdapter = class {
236
- constructor(multiInstance, transactional = true) {
237
- this.transactional = transactional;
238
- this.multiInstance = multiInstance;
239
- if (typeof multiInstance.pTTL === "function" || typeof multiInstance.pttl === "function") {
240
- this.pttl = (key) => {
241
- this.queueCommand(typeof multiInstance.pTTL === "function" ? "pTTL" : "pttl", [key]);
242
- return this;
243
- };
244
- }
245
- if (typeof multiInstance.eval === "function" || typeof multiInstance.addCommand === "function") {
246
- this.eval = (script, numkeys, ...args) => {
247
- if (typeof multiInstance.eval === "function") {
248
- this.queueCommand("eval", [script, { keys: args.slice(0, numkeys).map(String), arguments: args.slice(numkeys).map(String) }]);
249
- } else this.queueCommand("addCommand", [["EVAL", script, String(numkeys), ...args.map(String)]]);
250
- return this;
251
- };
252
- }
253
- }
254
- transactional;
255
- multiInstance;
256
- operations = [];
257
- pttl;
258
- eval;
259
- queueCommand(method, args) {
260
- if (this.transactional) this.multiInstance[method](...args);
261
- else this.operations.push(() => this.multiInstance[method](...args));
262
- }
263
- get(key) {
264
- this.queueCommand("get", [key]);
265
- return this;
266
- }
267
- set(key, value, ...args) {
268
- const opts = parseSetArgs(args);
269
- if (opts) {
270
- this.queueCommand("set", [key, value, opts]);
271
- } else {
272
- this.queueCommand("set", [key, value]);
273
- }
274
- return this;
275
- }
276
- setex(key, seconds, value) {
277
- if (typeof this.multiInstance.setEx === "function") {
278
- this.queueCommand("setEx", [key, seconds, value]);
279
- } else if (typeof this.multiInstance.setex === "function") {
280
- this.queueCommand("setex", [key, seconds, value]);
281
- } else {
282
- this.queueCommand("set", [key, value, { EX: seconds }]);
283
- }
284
- return this;
285
- }
286
- del(...keys) {
287
- if (keys.length === 0) return this;
288
- this.queueCommand("del", [keys.length === 1 ? keys[0] : keys]);
289
- return this;
290
- }
291
- expire(key, seconds) {
292
- this.queueCommand("expire", [key, seconds]);
293
- return this;
294
- }
295
- incr(key) {
296
- this.queueCommand("incr", [key]);
297
- return this;
298
- }
299
- sadd(key, ...members) {
300
- if (members.length === 0) return this;
301
- if (typeof this.multiInstance.sAdd === "function") {
302
- this.queueCommand("sAdd", [key, members.length === 1 ? members[0] : members]);
303
- } else {
304
- this.queueCommand("sadd", [key, ...members]);
305
- }
306
- return this;
307
- }
308
- smembers(key) {
309
- if (typeof this.multiInstance.sMembers === "function") {
310
- this.queueCommand("sMembers", [key]);
311
- } else {
312
- this.queueCommand("smembers", [key]);
313
- }
314
- return this;
315
- }
316
- hset(key, value) {
317
- if (typeof this.multiInstance.hSet === "function") {
318
- this.queueCommand("hSet", [key, value]);
319
- } else {
320
- this.queueCommand("hset", [key, value]);
321
- }
322
- return this;
323
- }
324
- hgetall(key) {
325
- if (typeof this.multiInstance.hGetAll === "function") {
326
- this.queueCommand("hGetAll", [key]);
327
- } else {
328
- this.queueCommand("hgetall", [key]);
329
- }
330
- return this;
331
- }
332
- async exec() {
333
- let raw;
334
- if (!this.transactional) {
335
- const results = await Promise.allSettled(this.operations.splice(0).map((operation) => Promise.resolve().then(operation)));
336
- return results.map((result) => result.status === "fulfilled" ? [null, result.value] : [result.reason instanceof Error ? result.reason : new Error(String(result.reason)), null]);
337
- }
338
- try {
339
- raw = await this.multiInstance.exec();
340
- } catch (error) {
341
- const replies = error.replies;
342
- if (!Array.isArray(replies)) throw error;
343
- raw = replies;
344
- }
345
- if (!raw) return null;
346
- return raw.map((item) => {
347
- if (item instanceof Error) {
348
- return [item, null];
349
- }
350
- return [null, item];
351
- });
352
- }
353
- };
354
- var NodeRedisAdapter = class _NodeRedisAdapter extends EventEmitter {
355
- client;
356
- connecting = null;
357
- pttl;
358
- constructor(client) {
359
- super();
360
- if (!client) {
361
- throw new Error("NodeRedisAdapter requires an active @redis/client instance");
362
- }
363
- this.client = client;
364
- if (typeof client.pTTL === "function" || typeof client.pttl === "function") {
365
- this.pttl = (key) => (client.pTTL ?? client.pttl).call(client, key);
366
- }
367
- }
368
- get isOpen() {
369
- return this.client.isOpen !== false;
370
- }
371
- async connect() {
372
- if (this.connecting) return this.connecting;
373
- if (typeof this.client.connect === "function" && !this.client.isOpen) {
374
- this.connecting = Promise.resolve(this.client.connect());
375
- try {
376
- return await this.connecting;
377
- } finally {
378
- this.connecting = null;
379
- }
380
- }
381
- return void 0;
382
- }
383
- async disconnect() {
384
- if (typeof this.client.disconnect === "function" && this.client.isOpen !== false) {
385
- try {
386
- await this.client.disconnect();
387
- } catch {
388
- }
389
- } else if (typeof this.client.quit === "function") {
390
- try {
391
- await this.client.quit();
392
- } catch {
393
- }
394
- }
395
- }
396
- async quit() {
397
- return this.disconnect();
398
- }
399
- async get(key) {
400
- return await this.client.get(key) ?? null;
401
- }
402
- async set(key, value, ...args) {
403
- const opts = parseSetArgs(args);
404
- if (opts) {
405
- return await this.client.set(key, value, opts);
406
- }
407
- return await this.client.set(key, value);
408
- }
409
- async setex(key, seconds, value) {
410
- if (typeof this.client.setEx === "function") {
411
- return await this.client.setEx(key, seconds, value);
412
- }
413
- if (typeof this.client.setex === "function") {
414
- return await this.client.setex(key, seconds, value);
415
- }
416
- return await this.client.set(key, value, { EX: seconds });
417
- }
418
- async del(...keys) {
419
- if (keys.length === 0) return 0;
420
- const res = await this.client.del(keys.length === 1 ? keys[0] : keys);
421
- return typeof res === "number" ? res : 0;
422
- }
423
- async ping() {
424
- return await this.client.ping();
425
- }
426
- async expire(key, seconds) {
427
- return await this.client.expire(key, seconds);
428
- }
429
- async incr(key) {
430
- return await this.client.incr(key);
431
- }
432
- async eval(script, numkeys, ...args) {
433
- if (typeof this.client.sendCommand === "function") {
434
- return await this.client.sendCommand([
435
- "EVAL",
436
- script,
437
- String(numkeys),
438
- ...args.map(String)
439
- ]);
440
- }
441
- if (typeof this.client.eval === "function") {
442
- const keys = args.slice(0, numkeys).map(String);
443
- const scriptArgs = args.slice(numkeys).map(String);
444
- return await this.client.eval(script, {
445
- keys,
446
- arguments: scriptArgs
447
- });
448
- }
449
- throw new Error("Redis client does not support EVAL or sendCommand");
450
- }
451
- multi() {
452
- const multiInstance = this.client.multi();
453
- return new NodeRedisPipelineAdapter(multiInstance);
454
- }
455
- pipeline() {
456
- return new NodeRedisPipelineAdapter(this.client, false);
457
- }
458
- async smembers(key) {
459
- if (typeof this.client.sMembers === "function") {
460
- return await this.client.sMembers(key);
461
- }
462
- if (typeof this.client.smembers === "function") {
463
- return await this.client.smembers(key);
464
- }
465
- return [];
466
- }
467
- async sadd(key, ...members) {
468
- if (members.length === 0) return 0;
469
- if (typeof this.client.sAdd === "function") {
470
- return await this.client.sAdd(key, members.length === 1 ? members[0] : members);
471
- }
472
- if (typeof this.client.sadd === "function") {
473
- return await this.client.sadd(key, ...members);
474
- }
475
- return 0;
476
- }
477
- async mget(keys) {
478
- if (keys.length === 0) return [];
479
- if (typeof this.client.mGet === "function") {
480
- return await this.client.mGet(keys);
481
- }
482
- if (typeof this.client.mget === "function") {
483
- return await this.client.mget(keys);
484
- }
485
- return [];
486
- }
487
- async hset(key, value) {
488
- if (typeof this.client.hSet === "function") {
489
- return await this.client.hSet(key, value);
490
- }
491
- if (typeof this.client.hset === "function") {
492
- return await this.client.hset(key, value);
493
- }
494
- return void 0;
495
- }
496
- async hgetall(key) {
497
- if (typeof this.client.hGetAll === "function") {
498
- return await this.client.hGetAll(key) ?? {};
499
- }
500
- if (typeof this.client.hgetall === "function") {
501
- return await this.client.hgetall(key) ?? {};
502
- }
503
- return {};
504
- }
505
- async publish(channel, message) {
506
- return await this.client.publish(channel, message);
507
- }
508
- async subscribe(...channels) {
509
- if (channels.length === 0) return void 0;
510
- await this.connect();
511
- return await this.client.subscribe(channels, (message, channel) => this.emit("message", channel, message));
512
- }
513
- async unsubscribe(...channels) {
514
- if (!channels.length || !this.isOpen) return void 0;
515
- return this.client.unsubscribe(channels);
516
- }
517
- async xread(...args) {
518
- await this.connect();
519
- const raw = await this.client.sendCommand(["XREAD", ...args.map(String)]);
520
- if (raw == null) return null;
521
- if (raw instanceof Map) return [...raw.entries()];
522
- if (!Array.isArray(raw) && typeof raw === "object") return Object.entries(raw);
523
- return raw;
524
- }
525
- async xadd(...args) {
526
- return this.client.sendCommand(["XADD", ...args.map(String)]);
527
- }
528
- async xrange(...args) {
529
- return this.client.sendCommand(["XRANGE", ...args.map(String)]);
530
- }
531
- async xrevrange(...args) {
532
- return this.client.sendCommand(["XREVRANGE", ...args.map(String)]);
533
- }
534
- scanStream(options) {
535
- const ee = new EventEmitter();
536
- const pattern = options?.match ?? "*";
537
- const count = options?.count ?? 100;
538
- queueMicrotask(async () => {
539
- try {
540
- if (typeof this.client.scanIterator === "function") {
541
- const batch = [];
542
- for await (const keys of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
543
- batch.push(...Array.isArray(keys) ? keys : [keys]);
544
- if (batch.length >= count) {
545
- ee.emit("data", [...batch]);
546
- batch.length = 0;
547
- }
548
- }
549
- if (batch.length > 0) {
550
- ee.emit("data", batch);
551
- }
552
- ee.emit("end");
553
- } else if (typeof this.client.sendCommand === "function") {
554
- let cursor = "0";
555
- do {
556
- const raw = await this.client.sendCommand([
557
- "SCAN",
558
- cursor,
559
- "MATCH",
560
- pattern,
561
- "COUNT",
562
- String(count)
563
- ]);
564
- cursor = String(raw[0]);
565
- const batch = raw[1];
566
- if (batch?.length) {
567
- ee.emit("data", batch);
568
- }
569
- } while (cursor !== "0");
570
- ee.emit("end");
571
- } else {
572
- ee.emit("end");
573
- }
574
- } catch (err) {
575
- ee.emit("error", err);
576
- }
577
- });
578
- return ee;
579
- }
580
- duplicate() {
581
- if (typeof this.client.duplicate === "function") {
582
- return new _NodeRedisAdapter(this.client.duplicate());
583
- }
584
- return this;
585
- }
586
- on(event, listener) {
587
- if (event === "message" || event === "smessage") return super.on(event, listener);
588
- if (typeof this.client.on === "function") {
589
- this.client.on(event === "close" ? "end" : event, listener);
590
- }
591
- return this;
592
- }
593
- once(event, listener) {
594
- if (event === "message" || event === "smessage") return super.once(event, listener);
595
- if (typeof this.client.once === "function") {
596
- this.client.once(event === "close" ? "end" : event, listener);
597
- }
598
- return this;
599
- }
600
- removeListener(event, listener) {
601
- super.removeListener(event, listener);
602
- this.client.removeListener?.(event === "close" ? "end" : event, listener);
603
- return this;
604
- }
605
- };
606
- function createNodeRedisAdapter(client) {
607
- if (client instanceof NodeRedisAdapter) return client;
608
- return new NodeRedisAdapter(client);
609
- }
610
- function parseSetArgs(args) {
611
- if (args.length === 0) return void 0;
612
- const opts = {};
613
- for (let i = 0; i < args.length; i++) {
614
- const a = String(args[i]).toUpperCase();
615
- if (a === "EX" && i + 1 < args.length) {
616
- opts.EX = Number(args[++i]);
617
- } else if (a === "PX" && i + 1 < args.length) {
618
- opts.PX = Number(args[++i]);
619
- } else if (a === "NX") {
620
- opts.NX = true;
621
- } else if (a === "XX") {
622
- opts.XX = true;
623
- }
624
- }
625
- return Object.keys(opts).length > 0 ? opts : void 0;
626
- }
627
-
628
- // src/utils/tracing.ts
629
- function parseTraceParent(header) {
630
- if (!header || typeof header !== "string") return null;
631
- const parts = header.trim().split("-");
632
- if (parts.length < 4) return null;
633
- const [version, traceId, spanId, flagsStr] = parts;
634
- if (version.length !== 2 || traceId.length !== 32 || spanId.length !== 16 || flagsStr.length !== 2) {
635
- return null;
636
- }
637
- if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) {
638
- return null;
639
- }
640
- const traceFlags = parseInt(flagsStr, 16);
641
- if (Number.isNaN(traceFlags)) return null;
642
- return {
643
- version,
644
- traceId,
645
- spanId,
646
- traceFlags
647
- };
648
- }
649
- function formatTraceParent(traceId, spanId, traceFlags = 1) {
650
- const flagsHex = traceFlags.toString(16).padStart(2, "0");
651
- return `00-${traceId}-${spanId}-${flagsHex}`;
652
- }
653
-
654
- export {
655
- SigV4SnapshotAdapter,
656
- createSigV4SnapshotAdapter,
657
- createS3SnapshotAdapter,
658
- createR2SnapshotAdapter,
659
- createHttpSnapshotAdapter,
660
- createCustomSnapshotAdapter,
661
- createMemorySnapshotAdapter,
662
- NodeRedisAdapter,
663
- createNodeRedisAdapter,
664
- parseTraceParent,
665
- formatTraceParent
666
- };