tricache 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -14,16 +14,23 @@
14
14
  "stale-while-revalidate",
15
15
  "msgpack",
16
16
  "aes-256-gcm",
17
+ "envelope-encryption",
17
18
  "nextjs",
19
+ "express",
20
+ "fastify",
21
+ "hono",
22
+ "edge",
23
+ "cli",
18
24
  "nodejs"
19
25
  ],
20
26
  "license": "MIT",
21
27
  "author": "Kareem (https://github.com/Kareem411)",
22
28
  "repository": {
23
29
  "type": "git",
24
- "url": "https://github.com/Kareem411/TriCache.git"
30
+ "url": "git+https://github.com/Kareem411/TriCache.git"
25
31
  },
26
32
  "homepage": "https://github.com/Kareem411/TriCache#readme",
33
+ "sideEffects": false,
27
34
  "type": "module",
28
35
  "main": "./dist/index.js",
29
36
  "module": "./dist/index.js",
@@ -61,10 +68,24 @@
61
68
  "types": "./dist/http/index.d.ts",
62
69
  "import": "./dist/http/index.js",
63
70
  "require": "./dist/http/index.cjs"
71
+ },
72
+ "./dashboard": {
73
+ "types": "./dist/dashboard/index.d.ts",
74
+ "import": "./dist/dashboard/index.js",
75
+ "require": "./dist/dashboard/index.cjs"
76
+ },
77
+ "./edge": {
78
+ "types": "./dist/edge/index.d.ts",
79
+ "edge-light": "./dist/edge/index.js",
80
+ "workerd": "./dist/edge/index.js",
81
+ "import": "./dist/edge/index.js",
82
+ "require": "./dist/edge/index.cjs",
83
+ "default": "./dist/edge/index.js"
64
84
  }
65
85
  },
66
86
  "files": [
67
87
  "bin",
88
+ "dashboards",
68
89
  "dist",
69
90
  "src",
70
91
  "README.md",
@@ -84,25 +105,27 @@
84
105
  },
85
106
  "dependencies": {
86
107
  "ioredis": "6.0.0",
87
- "msgpackr": "2.0.5"
108
+ "msgpackr": "2.1.0"
88
109
  },
89
110
  "devDependencies": {
90
111
  "@nestjs/common": "^11.0.0",
91
112
  "@nestjs/core": "^11.0.0",
92
113
  "@types/node": "^26.2.0",
114
+ "markdown-it-mathjax3": "^4.3.2",
93
115
  "oxlint": "^1.79.0",
94
116
  "redis": "^6.2.1",
95
117
  "tsup": "^8.5.1",
96
118
  "tsx": "^4.23.12",
97
119
  "typescript": "^6.0.3",
98
120
  "vite": "^8.2.2",
121
+ "vitepress": "2.0.0-alpha.20",
99
122
  "vitest": "^4.1.11"
100
123
  },
101
124
  "engines": {
102
- "node": ">=22.13.0"
125
+ "node": ">=20.10.0"
103
126
  },
104
127
  "scripts": {
105
- "build": "tsup src/index.ts src/cli.ts src/serialize-worker.ts src/next/index.ts src/nestjs/index.ts src/prisma/index.ts src/drizzle/index.ts src/http/index.ts --format esm,cjs --dts --clean",
128
+ "build": "tsup src/index.ts src/cli.ts src/serialize-worker.ts src/next/index.ts src/nestjs/index.ts src/prisma/index.ts src/drizzle/index.ts src/http/index.ts src/dashboard/index.ts src/edge/index.ts --format esm,cjs --dts --clean",
106
129
  "postbuild": "node --input-type=module -e \"import{readdirSync,rmSync,statSync}from'fs';import{join}from'path';function clean(d){for(const f of readdirSync(d)){const p=join(d,f);if(statSync(p).isDirectory())clean(p);else if(p.endsWith('.d.cts'))rmSync(p,{force:true});}}clean('dist');\"",
107
130
  "dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
108
131
  "typecheck": "tsc --noEmit",
@@ -112,6 +135,11 @@
112
135
  "test": "vitest run",
113
136
  "test:integration": "vitest run --config vitest.integration.config.ts",
114
137
  "test:watch": "vitest",
115
- "bench": "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts"
138
+ "bench": "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts",
139
+ "bench:roi": "tsx bench/cloud-roi-simulation.ts",
140
+ "docs:dev": "vitepress dev docs",
141
+ "docs:build": "vitepress build docs",
142
+ "docs:preview": "vitepress preview docs",
143
+ "docs:start": "vitepress preview docs"
116
144
  }
117
145
  }
@@ -0,0 +1,206 @@
1
+ import type { IRedisDriver, IRedisPipeline } from '../types';
2
+
3
+ export interface AutoPipelinerOptions {
4
+ /** Maximum number of operations to coalesce before forcing an immediate pipeline dispatch. Default: 100 */
5
+ maxBatchSize?: number;
6
+ /** Whether auto-pipelining is enabled. Default: true */
7
+ enabled?: boolean;
8
+ }
9
+
10
+ interface PendingGetOp {
11
+ type: 'get';
12
+ key: string;
13
+ resolve: (val: string | null) => void;
14
+ reject: (err: Error) => void;
15
+ }
16
+
17
+ interface PendingSetexOp {
18
+ type: 'setex';
19
+ key: string;
20
+ seconds: number;
21
+ value: string;
22
+ resolve: () => void;
23
+ reject: (err: Error) => void;
24
+ }
25
+
26
+ interface PendingDelOp {
27
+ type: 'del';
28
+ keys: string[];
29
+ resolve: (deleted: number) => void;
30
+ reject: (err: Error) => void;
31
+ }
32
+
33
+ type PendingOp = PendingGetOp | PendingSetexOp | PendingDelOp;
34
+
35
+ /**
36
+ * AutoPipeliner — Microtask-coalesced Redis request batching.
37
+ *
38
+ * Automatically combines individual Redis commands dispatched during the same synchronous
39
+ * tick of the Node.js event loop into a single `pipeline()` network round-trip.
40
+ *
41
+ * Uses `queueMicrotask` exclusively (never `setImmediate` or timers) to ensure ZERO
42
+ * artificial latency penalty (0ms overhead) while slashing network syscalls under high concurrency.
43
+ */
44
+ export class AutoPipeliner {
45
+ public readonly maxBatchSize: number;
46
+ public enabled: boolean;
47
+
48
+ private queue: PendingOp[] = [];
49
+ private scheduled = false;
50
+ private inFlight = false;
51
+
52
+ private statsInternal = {
53
+ batchesDispatched: 0,
54
+ operationsBatched: 0,
55
+ };
56
+
57
+ constructor(
58
+ private readonly client: IRedisDriver | any,
59
+ options?: AutoPipelinerOptions,
60
+ ) {
61
+ this.maxBatchSize = options?.maxBatchSize ?? 100;
62
+ this.enabled = options?.enabled ?? true;
63
+ }
64
+
65
+ public get stats() {
66
+ return {
67
+ batchesDispatched: this.statsInternal.batchesDispatched,
68
+ operationsBatched: this.statsInternal.operationsBatched,
69
+ pendingQueueSize: this.queue.length,
70
+ };
71
+ }
72
+
73
+ public async get(key: string): Promise<string | null> {
74
+ if (!this.enabled || !this.supportsPipelines()) {
75
+ return this.client.get(key);
76
+ }
77
+
78
+ return new Promise<string | null>((resolve, reject) => {
79
+ this.enqueue({ type: 'get', key, resolve, reject });
80
+ });
81
+ }
82
+
83
+ public async setex(key: string, seconds: number, value: string): Promise<void> {
84
+ if (!this.enabled || !this.supportsPipelines()) {
85
+ if (typeof this.client.setex === 'function') {
86
+ await this.client.setex(key, seconds, value);
87
+ } else {
88
+ await this.client.set(key, value, 'EX', seconds);
89
+ }
90
+ return;
91
+ }
92
+
93
+ return new Promise<void>((resolve, reject) => {
94
+ this.enqueue({ type: 'setex', key, seconds, value, resolve, reject });
95
+ });
96
+ }
97
+
98
+ public async del(...keys: string[]): Promise<number> {
99
+ if (keys.length === 0) return 0;
100
+ if (!this.enabled || !this.supportsPipelines()) {
101
+ return this.client.del(...keys);
102
+ }
103
+
104
+ return new Promise<number>((resolve, reject) => {
105
+ this.enqueue({ type: 'del', keys, resolve, reject });
106
+ });
107
+ }
108
+
109
+ private supportsPipelines(): boolean {
110
+ return Boolean(
111
+ typeof this.client?.pipeline === 'function' ||
112
+ typeof this.client?.multi === 'function'
113
+ );
114
+ }
115
+
116
+ private enqueue(op: PendingOp): void {
117
+ this.queue.push(op);
118
+
119
+ // If batch limit reached, trigger immediate synchronous dispatch to avoid microtask queue starvation
120
+ if (this.queue.length >= this.maxBatchSize) {
121
+ void this.flush();
122
+ return;
123
+ }
124
+
125
+ // Schedule flush in the identical execution tick via microtask
126
+ if (!this.scheduled) {
127
+ this.scheduled = true;
128
+ queueMicrotask(() => {
129
+ this.scheduled = false;
130
+ void this.flush();
131
+ });
132
+ }
133
+ }
134
+
135
+ public async flush(): Promise<void> {
136
+ if (this.queue.length === 0) return;
137
+
138
+ const batch = this.queue;
139
+ this.queue = [];
140
+ this.scheduled = false;
141
+
142
+ this.statsInternal.batchesDispatched++;
143
+ this.statsInternal.operationsBatched += batch.length;
144
+
145
+ const pipe: IRedisPipeline = typeof this.client.pipeline === 'function'
146
+ ? this.client.pipeline()
147
+ : this.client.multi();
148
+
149
+ for (const op of batch) {
150
+ switch (op.type) {
151
+ case 'get':
152
+ pipe.get(op.key);
153
+ break;
154
+ case 'setex':
155
+ pipe.setex(op.key, op.seconds, op.value);
156
+ break;
157
+ case 'del':
158
+ pipe.del(...op.keys);
159
+ break;
160
+ }
161
+ }
162
+
163
+ try {
164
+ const results = await pipe.exec();
165
+
166
+ if (!results) {
167
+ // Pipeline returned null / aborted
168
+ for (const op of batch) {
169
+ if (op.type === 'get') op.resolve(null);
170
+ else if (op.type === 'del') op.resolve(0);
171
+ else op.resolve();
172
+ }
173
+ return;
174
+ }
175
+
176
+ for (let i = 0; i < batch.length; i++) {
177
+ const op = batch[i];
178
+ const resTuple = results[i];
179
+
180
+ if (!resTuple) {
181
+ if (op.type === 'get') op.resolve(null);
182
+ else if (op.type === 'del') op.resolve(0);
183
+ else op.resolve();
184
+ continue;
185
+ }
186
+
187
+ const [err, val] = resTuple;
188
+ if (err) {
189
+ op.reject(err instanceof Error ? err : new Error(String(err)));
190
+ } else {
191
+ if (op.type === 'get') {
192
+ op.resolve(val != null ? String(val) : null);
193
+ } else if (op.type === 'del') {
194
+ op.resolve(typeof val === 'number' ? val : Number(val) || 0);
195
+ } else {
196
+ op.resolve();
197
+ }
198
+ }
199
+ }
200
+ } catch (err) {
201
+ for (const op of batch) {
202
+ op.reject(err instanceof Error ? err : new Error(String(err)));
203
+ }
204
+ }
205
+ }
206
+ }
@@ -0,0 +1,370 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { IRedisDriver, IRedisPipeline } from '../types';
3
+
4
+ export type { IRedisDriver, IRedisPipeline };
5
+
6
+ /**
7
+ * Pipeline adapter converting `@redis/client` (node-redis v4/v5/v6) chained multi calls
8
+ * into the tuple response format (`Array<[Error | null, any]>`) expected by TriCache.
9
+ */
10
+ export class NodeRedisPipelineAdapter implements IRedisPipeline {
11
+ private readonly multiInstance: any;
12
+
13
+ constructor(multiInstance: any) {
14
+ this.multiInstance = multiInstance;
15
+ }
16
+
17
+ get(key: string): this {
18
+ this.multiInstance.get(key);
19
+ return this;
20
+ }
21
+
22
+ set(key: string, value: string, ...args: (string | number)[]): this {
23
+ const opts = parseSetArgs(args);
24
+ if (opts) {
25
+ this.multiInstance.set(key, value, opts);
26
+ } else {
27
+ this.multiInstance.set(key, value);
28
+ }
29
+ return this;
30
+ }
31
+
32
+ setex(key: string, seconds: number, value: string): this {
33
+ if (typeof this.multiInstance.setEx === 'function') {
34
+ this.multiInstance.setEx(key, seconds, value);
35
+ } else if (typeof this.multiInstance.setex === 'function') {
36
+ this.multiInstance.setex(key, seconds, value);
37
+ } else {
38
+ this.multiInstance.set(key, value, { EX: seconds });
39
+ }
40
+ return this;
41
+ }
42
+
43
+ del(...keys: string[]): this {
44
+ if (keys.length === 0) return this;
45
+ this.multiInstance.del(keys.length === 1 ? keys[0] : keys);
46
+ return this;
47
+ }
48
+
49
+ expire(key: string, seconds: number): this {
50
+ this.multiInstance.expire(key, seconds);
51
+ return this;
52
+ }
53
+
54
+ incr(key: string): this {
55
+ this.multiInstance.incr(key);
56
+ return this;
57
+ }
58
+
59
+ sadd(key: string, ...members: string[]): this {
60
+ if (members.length === 0) return this;
61
+ if (typeof this.multiInstance.sAdd === 'function') {
62
+ this.multiInstance.sAdd(key, members.length === 1 ? members[0] : members);
63
+ } else {
64
+ this.multiInstance.sadd(key, ...members);
65
+ }
66
+ return this;
67
+ }
68
+
69
+ smembers(key: string): this {
70
+ if (typeof this.multiInstance.sMembers === 'function') {
71
+ this.multiInstance.sMembers(key);
72
+ } else {
73
+ this.multiInstance.smembers(key);
74
+ }
75
+ return this;
76
+ }
77
+
78
+ hset(key: string, value: Record<string, string>): this {
79
+ if (typeof this.multiInstance.hSet === 'function') {
80
+ this.multiInstance.hSet(key, value);
81
+ } else {
82
+ this.multiInstance.hset(key, value);
83
+ }
84
+ return this;
85
+ }
86
+
87
+ async exec(): Promise<Array<[Error | null, any]> | null> {
88
+ const raw = await this.multiInstance.exec();
89
+ if (!raw) return null;
90
+ return raw.map((item: any) => {
91
+ if (item instanceof Error) {
92
+ return [item, null];
93
+ }
94
+ return [null, item];
95
+ });
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Universal driver adapter wrapping `@redis/client` (node-redis) to satisfy TriCache's
101
+ * `IRedisDriver` contract without adding runtime dependencies.
102
+ */
103
+ export class NodeRedisAdapter implements IRedisDriver {
104
+ readonly client: any;
105
+
106
+ constructor(client: any) {
107
+ if (!client) {
108
+ throw new Error('NodeRedisAdapter requires an active @redis/client instance');
109
+ }
110
+ this.client = client;
111
+ }
112
+
113
+ get isOpen(): boolean {
114
+ return this.client.isOpen !== false;
115
+ }
116
+
117
+ async connect(): Promise<unknown> {
118
+ if (typeof this.client.connect === 'function' && !this.client.isOpen) {
119
+ return await this.client.connect();
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ async disconnect(): Promise<void> {
125
+ if (typeof this.client.disconnect === 'function' && this.client.isOpen !== false) {
126
+ try {
127
+ await this.client.disconnect();
128
+ } catch {
129
+ /* ok */
130
+ }
131
+ } else if (typeof this.client.quit === 'function') {
132
+ try {
133
+ await this.client.quit();
134
+ } catch {
135
+ /* ok */
136
+ }
137
+ }
138
+ }
139
+
140
+ async quit(): Promise<void> {
141
+ return this.disconnect();
142
+ }
143
+
144
+ async get(key: string): Promise<string | null> {
145
+ return (await this.client.get(key)) ?? null;
146
+ }
147
+
148
+ async set(key: string, value: string, ...args: (string | number)[]): Promise<unknown> {
149
+ const opts = parseSetArgs(args);
150
+ if (opts) {
151
+ return await this.client.set(key, value, opts);
152
+ }
153
+ return await this.client.set(key, value);
154
+ }
155
+
156
+ async setex(key: string, seconds: number, value: string): Promise<unknown> {
157
+ if (typeof this.client.setEx === 'function') {
158
+ return await this.client.setEx(key, seconds, value);
159
+ }
160
+ if (typeof this.client.setex === 'function') {
161
+ return await this.client.setex(key, seconds, value);
162
+ }
163
+ return await this.client.set(key, value, { EX: seconds });
164
+ }
165
+
166
+ async del(...keys: string[]): Promise<number> {
167
+ if (keys.length === 0) return 0;
168
+ const res = await this.client.del(keys.length === 1 ? keys[0] : keys);
169
+ return typeof res === 'number' ? res : 0;
170
+ }
171
+
172
+ async ping(): Promise<string> {
173
+ return await this.client.ping();
174
+ }
175
+
176
+ async expire(key: string, seconds: number): Promise<number | boolean> {
177
+ return await this.client.expire(key, seconds);
178
+ }
179
+
180
+ async incr(key: string): Promise<number> {
181
+ return await this.client.incr(key);
182
+ }
183
+
184
+ async eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown> {
185
+ if (typeof this.client.sendCommand === 'function') {
186
+ return await this.client.sendCommand([
187
+ 'EVAL',
188
+ script,
189
+ String(numkeys),
190
+ ...args.map(String),
191
+ ]);
192
+ }
193
+ if (typeof this.client.eval === 'function') {
194
+ const keys = args.slice(0, numkeys).map(String);
195
+ const scriptArgs = args.slice(numkeys).map(String);
196
+ return await this.client.eval(script, {
197
+ keys,
198
+ arguments: scriptArgs,
199
+ });
200
+ }
201
+ throw new Error('Redis client does not support EVAL or sendCommand');
202
+ }
203
+
204
+ multi(): IRedisPipeline {
205
+ const multiInstance = this.client.multi();
206
+ return new NodeRedisPipelineAdapter(multiInstance);
207
+ }
208
+
209
+ pipeline(): IRedisPipeline {
210
+ return this.multi();
211
+ }
212
+
213
+ async smembers(key: string): Promise<string[]> {
214
+ if (typeof this.client.sMembers === 'function') {
215
+ return await this.client.sMembers(key);
216
+ }
217
+ if (typeof this.client.smembers === 'function') {
218
+ return await this.client.smembers(key);
219
+ }
220
+ return [];
221
+ }
222
+
223
+ async sadd(key: string, ...members: string[]): Promise<number> {
224
+ if (members.length === 0) return 0;
225
+ if (typeof this.client.sAdd === 'function') {
226
+ return await this.client.sAdd(key, members.length === 1 ? members[0] : members);
227
+ }
228
+ if (typeof this.client.sadd === 'function') {
229
+ return await this.client.sadd(key, ...members);
230
+ }
231
+ return 0;
232
+ }
233
+
234
+ async mget(keys: string[]): Promise<(string | null)[]> {
235
+ if (keys.length === 0) return [];
236
+ if (typeof this.client.mGet === 'function') {
237
+ return await this.client.mGet(keys);
238
+ }
239
+ if (typeof this.client.mget === 'function') {
240
+ return await this.client.mget(keys);
241
+ }
242
+ return [];
243
+ }
244
+
245
+ async hset(key: string, value: Record<string, string>): Promise<unknown> {
246
+ if (typeof this.client.hSet === 'function') {
247
+ return await this.client.hSet(key, value);
248
+ }
249
+ if (typeof this.client.hset === 'function') {
250
+ return await this.client.hset(key, value);
251
+ }
252
+ return undefined;
253
+ }
254
+
255
+ async publish(channel: string, message: string): Promise<number> {
256
+ return await this.client.publish(channel, message);
257
+ }
258
+
259
+ async subscribe(...channels: string[]): Promise<unknown> {
260
+ if (channels.length === 0) return undefined;
261
+ return await this.client.subscribe(channels);
262
+ }
263
+
264
+ scanStream(options?: { match?: string; count?: number }): EventEmitter {
265
+ const ee = new EventEmitter();
266
+ const pattern = options?.match ?? '*';
267
+ const count = options?.count ?? 100;
268
+
269
+ queueMicrotask(async () => {
270
+ try {
271
+ if (typeof this.client.scanIterator === 'function') {
272
+ const batch: string[] = [];
273
+ for await (const key of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
274
+ batch.push(key);
275
+ if (batch.length >= count) {
276
+ ee.emit('data', [...batch]);
277
+ batch.length = 0;
278
+ }
279
+ }
280
+ if (batch.length > 0) {
281
+ ee.emit('data', batch);
282
+ }
283
+ ee.emit('end');
284
+ } else if (typeof this.client.sendCommand === 'function') {
285
+ let cursor = '0';
286
+ do {
287
+ const raw = await this.client.sendCommand([
288
+ 'SCAN',
289
+ cursor,
290
+ 'MATCH',
291
+ pattern,
292
+ 'COUNT',
293
+ String(count),
294
+ ]);
295
+ cursor = String(raw[0]);
296
+ const batch = raw[1] as string[];
297
+ if (batch?.length) {
298
+ ee.emit('data', batch);
299
+ }
300
+ } while (cursor !== '0');
301
+ ee.emit('end');
302
+ } else {
303
+ ee.emit('end');
304
+ }
305
+ } catch (err) {
306
+ ee.emit('error', err);
307
+ }
308
+ });
309
+
310
+ return ee;
311
+ }
312
+
313
+ duplicate(): IRedisDriver {
314
+ if (typeof this.client.duplicate === 'function') {
315
+ return new NodeRedisAdapter(this.client.duplicate());
316
+ }
317
+ return this;
318
+ }
319
+
320
+ on(event: string, listener: (...args: any[]) => void): this {
321
+ if (typeof this.client.on === 'function') {
322
+ this.client.on(event, listener);
323
+ }
324
+ return this;
325
+ }
326
+
327
+ once(event: string, listener: (...args: any[]) => void): this {
328
+ if (typeof this.client.once === 'function') {
329
+ this.client.once(event, listener);
330
+ }
331
+ return this;
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Creates a pluggable `IRedisDriver` adapter wrapping an existing `@redis/client` instance.
337
+ *
338
+ * @example
339
+ * import { createClient } from 'redis';
340
+ * import { CacheService, createNodeRedisAdapter } from 'tricache';
341
+ *
342
+ * const client = createClient({ url: 'redis://localhost:6379' });
343
+ * await client.connect();
344
+ *
345
+ * const cache = CacheService.create({
346
+ * redisClient: createNodeRedisAdapter(client),
347
+ * });
348
+ */
349
+ export function createNodeRedisAdapter(client: any): IRedisDriver {
350
+ if (client instanceof NodeRedisAdapter) return client;
351
+ return new NodeRedisAdapter(client);
352
+ }
353
+
354
+ function parseSetArgs(args: (string | number)[]): Record<string, any> | undefined {
355
+ if (args.length === 0) return undefined;
356
+ const opts: Record<string, any> = {};
357
+ for (let i = 0; i < args.length; i++) {
358
+ const a = String(args[i]).toUpperCase();
359
+ if (a === 'EX' && i + 1 < args.length) {
360
+ opts.EX = Number(args[++i]);
361
+ } else if (a === 'PX' && i + 1 < args.length) {
362
+ opts.PX = Number(args[++i]);
363
+ } else if (a === 'NX') {
364
+ opts.NX = true;
365
+ } else if (a === 'XX') {
366
+ opts.XX = true;
367
+ }
368
+ }
369
+ return Object.keys(opts).length > 0 ? opts : undefined;
370
+ }