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
@@ -3,6 +3,8 @@ interface KeyDerivationOptions {
3
3
  keyGenerator?: (req: any) => string;
4
4
  /** Optional list of header names (case-insensitive) to include in the cache key. */
5
5
  headerWhitelist?: string[];
6
+ /** Opt in to authenticated request caching with an identity-aware key. Default: false. */
7
+ cacheAuthenticated?: boolean;
6
8
  }
7
9
  /**
8
10
  * Generates a deterministic HTTP cache key from request method, URL path, sorted query parameters,
@@ -18,7 +20,7 @@ declare function buildDeterministicKey(req: any, options?: KeyDerivationOptions)
18
20
  * Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
19
21
  * or matches a custom skipCache predicate.
20
22
  */
21
- declare function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): boolean;
23
+ declare function shouldSkipCache(req: any, customSkip?: (req: any) => boolean, options?: KeyDerivationOptions): boolean;
22
24
  /**
23
25
  * Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
24
26
  */
@@ -0,0 +1,29 @@
1
+ interface KeyDerivationOptions {
2
+ /** Custom key derivation function. Overrides default URL and query string serialization. */
3
+ keyGenerator?: (req: any) => string;
4
+ /** Optional list of header names (case-insensitive) to include in the cache key. */
5
+ headerWhitelist?: string[];
6
+ /** Opt in to authenticated request caching with an identity-aware key. Default: false. */
7
+ cacheAuthenticated?: boolean;
8
+ }
9
+ /**
10
+ * Generates a deterministic HTTP cache key from request method, URL path, sorted query parameters,
11
+ * and optional whitelisted headers.
12
+ *
13
+ * Example:
14
+ * GET /api/products?sort=desc&page=2
15
+ * GET /api/products?page=2&sort=desc
16
+ * Both map to: http:GET:/api/products?page=2&sort=desc
17
+ */
18
+ declare function buildDeterministicKey(req: any, options?: KeyDerivationOptions): string;
19
+ /**
20
+ * Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
21
+ * or matches a custom skipCache predicate.
22
+ */
23
+ declare function shouldSkipCache(req: any, customSkip?: (req: any) => boolean, options?: KeyDerivationOptions): boolean;
24
+ /**
25
+ * Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
26
+ */
27
+ declare function generateETag(data: unknown): string;
28
+
29
+ export { type KeyDerivationOptions as K, buildDeterministicKey as b, generateETag as g, shouldSkipCache as s };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "1.0.1",
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.",
3
+ "version": "2.0.0",
4
+ "description": "Node.js caching with bounded memory, Redis/Valkey sharing, tag invalidation, stale-while-revalidate, per-process request coalescing, framework adapters, and optional local disk spill.",
5
5
  "keywords": [
6
6
  "cache",
7
7
  "redis",
@@ -40,51 +40,102 @@
40
40
  },
41
41
  "exports": {
42
42
  ".": {
43
- "types": "./dist/index.d.ts",
44
- "import": "./dist/index.js",
45
- "require": "./dist/index.cjs"
43
+ "import": {
44
+ "types": "./dist/index.d.ts",
45
+ "default": "./dist/index.js"
46
+ },
47
+ "require": {
48
+ "types": "./dist/index.d.cts",
49
+ "default": "./dist/index.cjs"
50
+ }
46
51
  },
47
52
  "./next": {
48
- "types": "./dist/next/index.d.ts",
49
- "import": "./dist/next/index.js",
50
- "require": "./dist/next/index.cjs"
53
+ "import": {
54
+ "types": "./dist/next/index.d.ts",
55
+ "default": "./dist/next/index.js"
56
+ },
57
+ "require": {
58
+ "types": "./dist/next/index.d.cts",
59
+ "default": "./dist/next/index.cjs"
60
+ }
51
61
  },
52
62
  "./nestjs": {
53
- "types": "./dist/nestjs/index.d.ts",
54
- "import": "./dist/nestjs/index.js",
55
- "require": "./dist/nestjs/index.cjs"
63
+ "import": {
64
+ "types": "./dist/nestjs/index.d.ts",
65
+ "default": "./dist/nestjs/index.js"
66
+ },
67
+ "require": {
68
+ "types": "./dist/nestjs/index.d.cts",
69
+ "default": "./dist/nestjs/index.cjs"
70
+ }
56
71
  },
57
72
  "./prisma": {
58
- "types": "./dist/prisma/index.d.ts",
59
- "import": "./dist/prisma/index.js",
60
- "require": "./dist/prisma/index.cjs"
73
+ "import": {
74
+ "types": "./dist/prisma/index.d.ts",
75
+ "default": "./dist/prisma/index.js"
76
+ },
77
+ "require": {
78
+ "types": "./dist/prisma/index.d.cts",
79
+ "default": "./dist/prisma/index.cjs"
80
+ }
61
81
  },
62
82
  "./drizzle": {
63
- "types": "./dist/drizzle/index.d.ts",
64
- "import": "./dist/drizzle/index.js",
65
- "require": "./dist/drizzle/index.cjs"
83
+ "import": {
84
+ "types": "./dist/drizzle/index.d.ts",
85
+ "default": "./dist/drizzle/index.js"
86
+ },
87
+ "require": {
88
+ "types": "./dist/drizzle/index.d.cts",
89
+ "default": "./dist/drizzle/index.cjs"
90
+ }
66
91
  },
67
92
  "./http": {
68
- "types": "./dist/http/index.d.ts",
69
- "import": "./dist/http/index.js",
70
- "require": "./dist/http/index.cjs"
93
+ "import": {
94
+ "types": "./dist/http/index.d.ts",
95
+ "default": "./dist/http/index.js"
96
+ },
97
+ "require": {
98
+ "types": "./dist/http/index.d.cts",
99
+ "default": "./dist/http/index.cjs"
100
+ }
71
101
  },
72
102
  "./hono": {
73
- "types": "./dist/hono/index.d.ts",
74
- "import": "./dist/hono/index.js",
75
- "require": "./dist/hono/index.cjs"
103
+ "import": {
104
+ "types": "./dist/hono/index.d.ts",
105
+ "default": "./dist/hono/index.js"
106
+ },
107
+ "require": {
108
+ "types": "./dist/hono/index.d.cts",
109
+ "default": "./dist/hono/index.cjs"
110
+ }
76
111
  },
77
112
  "./dashboard": {
78
- "types": "./dist/dashboard/index.d.ts",
79
- "import": "./dist/dashboard/index.js",
80
- "require": "./dist/dashboard/index.cjs"
113
+ "import": {
114
+ "types": "./dist/dashboard/index.d.ts",
115
+ "default": "./dist/dashboard/index.js"
116
+ },
117
+ "require": {
118
+ "types": "./dist/dashboard/index.d.cts",
119
+ "default": "./dist/dashboard/index.cjs"
120
+ }
81
121
  },
82
122
  "./edge": {
83
- "types": "./dist/edge/index.d.ts",
84
- "edge-light": "./dist/edge/index.js",
85
- "workerd": "./dist/edge/index.js",
86
- "import": "./dist/edge/index.js",
87
- "require": "./dist/edge/index.cjs",
123
+ "edge-light": {
124
+ "types": "./dist/edge/index.d.ts",
125
+ "default": "./dist/edge/index.js"
126
+ },
127
+ "workerd": {
128
+ "types": "./dist/edge/index.d.ts",
129
+ "default": "./dist/edge/index.js"
130
+ },
131
+ "import": {
132
+ "types": "./dist/edge/index.d.ts",
133
+ "default": "./dist/edge/index.js"
134
+ },
135
+ "require": {
136
+ "types": "./dist/edge/index.d.cts",
137
+ "default": "./dist/edge/index.cjs"
138
+ },
88
139
  "default": "./dist/edge/index.js"
89
140
  }
90
141
  },
@@ -97,8 +148,8 @@
97
148
  "LICENSE"
98
149
  ],
99
150
  "peerDependencies": {
100
- "@nestjs/common": "^10.0.0 || ^11.0.0",
101
- "@nestjs/core": "^10.0.0 || ^11.0.0",
151
+ "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
152
+ "@nestjs/core": "^10.0.0 || ^11.0.0 || ^12.0.0",
102
153
  "hono": ">=3.0.0 <5.0.0"
103
154
  },
104
155
  "peerDependenciesMeta": {
@@ -119,13 +170,21 @@
119
170
  "zstd-codec": "^0.1.5"
120
171
  },
121
172
  "devDependencies": {
122
- "@nestjs/common": "^11.0.0",
123
- "@nestjs/core": "^11.0.0",
173
+ "@nestjs/cache-manager": "12.0.5",
174
+ "@nestjs/common": "^12.5.0",
175
+ "@nestjs/core": "^12.5.0",
176
+ "@nestjs/platform-express": "^12.5.0",
124
177
  "@types/node": "^26.6.2",
125
- "hono": "^4.0.0",
178
+ "@opentelemetry/api": "^1.10.0",
179
+ "cache-manager": "7.2.9",
180
+ "hono": "^4.13.16",
181
+ "keyv": "5.6.0",
126
182
  "markdown-it-mathjax3": "^4.3.2",
183
+ "next": "16.4.6",
127
184
  "oxlint": "^1.85.0",
128
185
  "redis": "^6.2.1",
186
+ "reflect-metadata": "^0.2.2",
187
+ "rxjs": "^7.8.2",
129
188
  "tsup": "^8.5.1",
130
189
  "tsx": "^4.23.15",
131
190
  "typescript": "^6.0.3",
@@ -138,7 +197,6 @@
138
197
  },
139
198
  "scripts": {
140
199
  "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/hono/index.ts src/dashboard/index.ts src/edge/index.ts --format esm,cjs --dts --clean",
141
- "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');\"",
142
200
  "dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
143
201
  "typecheck": "tsc --noEmit",
144
202
  "typecheck:tests": "tsc --noEmit -p tsconfig.test.json",
@@ -146,10 +204,31 @@
146
204
  "lint": "oxlint src tests scripts",
147
205
  "test": "vitest run",
148
206
  "test:integration": "vitest run --config vitest.integration.config.ts",
207
+ "test:shutdown-docker": "node scripts/run-shutdown-probes.mjs",
208
+ "test:storage-docker": "node scripts/run-storage-permission-probes.mjs",
209
+ "test:recovery-docker": "node scripts/run-redis-recovery-probes.mjs",
210
+ "test:rollout-docker": "node scripts/run-redis-recovery-probes.mjs --rollout",
149
211
  "test:watch": "vitest",
212
+ "check:package": "node scripts/check-package.mjs",
213
+ "check:release-version": "node scripts/check-release-version.mjs",
214
+ "check:production-start": "node scripts/check-production-start.mjs",
215
+ "check:rehearsal-runner": "node --test tests/rehearsal-runner.test.mjs tests/m3-protocol.test.mjs",
216
+ "check:m3-rehearsal": "node --test tests/m3-rehearsal.test.mjs tests/service-telemetry.test.mjs tests/production-service.test.mjs",
217
+ "check:spill-crash": "node scripts/check-spill-crash.mjs",
218
+ "check:edge-provider": "node scripts/check-edge-provider.mjs",
150
219
  "bench": "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts",
151
220
  "bench:roi": "tsx bench/cloud-roi-simulation.ts",
152
221
  "bench:compression": "tsx bench/compression.bench.ts",
222
+ "bench:compare": "tsx bench/compare/runner.ts",
223
+ "bench:compare:smoke": "tsx bench/compare/runner.ts --quick",
224
+ "bench:tag-refresh": "node bench/tag-refresh/run.mjs",
225
+ "bench:public-trace": "tsx bench/public-trace/run-baseline.ts",
226
+ "bench:public-trace:l1": "node --import tsx/esm bench/public-trace/run-l1.ts",
227
+ "bench:public-trace:admission": "node --import tsx/esm bench/public-trace/run-admission-probe.ts",
228
+ "bench:public-trace:calibrate-admission": "node --import tsx/esm bench/public-trace/run-admission-calibration.ts",
229
+ "bench:public-trace:entry-policy": "node --import tsx/esm bench/public-trace/run-entry-policy.ts",
230
+ "bench:outage": "node bench/compare/outage-runner.ts",
231
+ "lint:bench": "oxlint bench/compare bench/tag-refresh bench/public-trace",
153
232
  "docs:dev": "vitepress dev docs",
154
233
  "docs:build": "vitepress build docs",
155
234
  "docs:preview": "vitepress preview docs",
@@ -1,4 +1,19 @@
1
1
  import type { IRedisDriver, IRedisPipeline } from '../types';
2
+ import { Cluster } from 'ioredis';
3
+ import { redisHashSlot } from '../utils/redis-slot';
4
+
5
+ const LUA_TIMED_STRING_READ = `-- tricache: atomic timed string read
6
+ local value = redis.call('GET', KEYS[1])
7
+ return {value, redis.call('PTTL', KEYS[1])}`;
8
+
9
+ const LUA_TIMED_READ = `-- tricache: atomic typed timed read
10
+ local kind = redis.call('TYPE', KEYS[1]).ok
11
+ if kind == 'string' then
12
+ return {kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1])}
13
+ elseif kind == 'hash' then
14
+ return {kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1])}
15
+ end
16
+ return {'none', false, -2}`;
2
17
 
3
18
  export interface AutoPipelinerOptions {
4
19
  /** Maximum number of operations to coalesce before forcing an immediate pipeline dispatch. Default: 100 */
@@ -23,6 +38,15 @@ interface PendingSetexOp {
23
38
  reject: (err: Error) => void;
24
39
  }
25
40
 
41
+ interface PendingSetpxOp {
42
+ type: 'setpx';
43
+ key: string;
44
+ milliseconds: number;
45
+ value: string;
46
+ resolve: () => void;
47
+ reject: (error: Error) => void;
48
+ }
49
+
26
50
  interface PendingDelOp {
27
51
  type: 'del';
28
52
  keys: string[];
@@ -30,7 +54,68 @@ interface PendingDelOp {
30
54
  reject: (err: Error) => void;
31
55
  }
32
56
 
33
- type PendingOp = PendingGetOp | PendingSetexOp | PendingDelOp;
57
+ export interface TimedRedisValue {
58
+ raw: string | Record<string, string> | null;
59
+ ttlMs?: number;
60
+ }
61
+
62
+ interface PendingReadOp {
63
+ type: 'read';
64
+ key: string;
65
+ hash: boolean;
66
+ resolve: (value: TimedRedisValue) => void;
67
+ reject: (err: Error) => void;
68
+ }
69
+
70
+ function parseTimedReadResult(result: unknown): TimedRedisValue {
71
+ if (!Array.isArray(result) || result.length !== 3) throw new Error('Invalid atomic Redis read result');
72
+ const kind = result[0];
73
+ const ttlMs = Number(result[2]);
74
+ if ((kind !== 'string' && kind !== 'hash' && kind !== 'none') || !Number.isFinite(ttlMs)) {
75
+ throw new Error('Invalid atomic Redis read result');
76
+ }
77
+ if (kind === 'none') return { raw: null, ttlMs: -2 };
78
+ if (kind === 'string') {
79
+ const raw = result[1] === false || result[1] === null ? null : String(result[1]);
80
+ return { raw, ttlMs };
81
+ }
82
+ const payload = result[1];
83
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) throw new Error('Invalid atomic Redis hash result');
84
+ return {
85
+ raw: Object.fromEntries(Array.from({ length: payload.length / 2 }, (_, index) => [
86
+ String(payload[index * 2]), String(payload[index * 2 + 1]),
87
+ ])),
88
+ ttlMs,
89
+ };
90
+ }
91
+
92
+ function parseTimedStringReadResult(result: unknown): TimedRedisValue {
93
+ if (!Array.isArray(result) || result.length !== 2 || !Number.isFinite(Number(result[1]))) {
94
+ throw new Error('Invalid atomic Redis string read result');
95
+ }
96
+ return { raw: result[0] === false || result[0] === null ? null : String(result[0]), ttlMs: Number(result[1]) };
97
+ }
98
+
99
+ /** Read value + PTTL in one atomic, single-key Redis operation where supported. */
100
+ export async function readRedisValue(client: any, key: string, hash = false): Promise<TimedRedisValue> {
101
+ if (typeof client.pttl === 'function' && typeof client.multi === 'function') {
102
+ const transaction = client.multi();
103
+ if (typeof transaction.pttl === 'function' && (!hash || typeof transaction.hgetall === 'function')) {
104
+ if (hash) transaction.hgetall(key);
105
+ else transaction.get(key);
106
+ transaction.pttl(key);
107
+ const results = await transaction.exec();
108
+ if (!results) throw new Error('Redis read transaction aborted');
109
+ if (results[0]?.[0]) throw results[0][0];
110
+ if (results[1]?.[0]) throw results[1][0];
111
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
112
+ }
113
+ }
114
+ // Legacy/custom drivers without an atomic TTL read retain the documented L1 fallback TTL.
115
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
116
+ }
117
+
118
+ type PendingOp = PendingGetOp | PendingSetexOp | PendingSetpxOp | PendingDelOp | PendingReadOp;
34
119
 
35
120
  /**
36
121
  * AutoPipeliner — Microtask-coalesced Redis request batching.
@@ -38,8 +123,8 @@ type PendingOp = PendingGetOp | PendingSetexOp | PendingDelOp;
38
123
  * Automatically combines individual Redis commands dispatched during the same synchronous
39
124
  * tick of the Node.js event loop into a single `pipeline()` network round-trip.
40
125
  *
41
- * Uses `queueMicrotask` exclusively (never `setImmediate` or timers) to ensure ZERO
42
- * artificial latency penalty (0ms overhead) while slashing network syscalls under high concurrency.
126
+ * Uses `queueMicrotask` rather than a batching timer. Scheduling and command
127
+ * execution still have a cost; timed reads remain atomic within each batch.
43
128
  */
44
129
  export class AutoPipeliner {
45
130
  public readonly maxBatchSize: number;
@@ -80,6 +165,18 @@ export class AutoPipeliner {
80
165
  });
81
166
  }
82
167
 
168
+ public async read(key: string, hash = false): Promise<TimedRedisValue> {
169
+ if (!hash && typeof this.client.pttl !== 'function') return { raw: await this.get(key) };
170
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== 'function') {
171
+ return readRedisValue(this.client, key, hash);
172
+ }
173
+ const probe = typeof this.client.pipeline === 'function' ? this.client.pipeline() : this.client.multi();
174
+ if (typeof probe.eval !== 'function') {
175
+ return readRedisValue(this.client, key, hash);
176
+ }
177
+ return new Promise<TimedRedisValue>((resolve, reject) => this.enqueue({ type: 'read', key, hash, resolve, reject }));
178
+ }
179
+
83
180
  public async setex(key: string, seconds: number, value: string): Promise<void> {
84
181
  if (!this.enabled || !this.supportsPipelines()) {
85
182
  if (typeof this.client.setex === 'function') {
@@ -95,8 +192,19 @@ export class AutoPipeliner {
95
192
  });
96
193
  }
97
194
 
195
+ public async setpx(key: string, milliseconds: number, value: string): Promise<void> {
196
+ if (!this.enabled || !this.supportsPipelines()) {
197
+ await this.client.set(key, value, 'PX', milliseconds);
198
+ return;
199
+ }
200
+ return new Promise<void>((resolve, reject) => this.enqueue({ type: 'setpx', key, milliseconds, value, resolve, reject }));
201
+ }
202
+
98
203
  public async del(...keys: string[]): Promise<number> {
99
204
  if (keys.length === 0) return 0;
205
+ if (this.client instanceof Cluster && keys.length > 1) {
206
+ return (await Promise.all(keys.map(key => this.del(key)))).reduce((sum, value) => sum + value, 0);
207
+ }
100
208
  if (!this.enabled || !this.supportsPipelines()) {
101
209
  return this.client.del(...keys);
102
210
  }
@@ -142,45 +250,55 @@ export class AutoPipeliner {
142
250
  this.statsInternal.batchesDispatched++;
143
251
  this.statsInternal.operationsBatched += batch.length;
144
252
 
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;
253
+ if (this.client instanceof Cluster) {
254
+ const groups = new Map<string, PendingOp[]>();
255
+ for (const operation of batch) {
256
+ const key = operation.type === 'del' ? operation.keys[0] : operation.key;
257
+ const slot = redisHashSlot(key);
258
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
259
+ const members = groups.get(master) ?? [];
260
+ members.push(operation);
261
+ groups.set(master, members);
160
262
  }
263
+ await Promise.all([...groups.values()].map(members => this.dispatch(members)));
264
+ return;
161
265
  }
266
+ await this.dispatch(batch);
267
+ }
162
268
 
269
+ private async dispatch(batch: PendingOp[]): Promise<void> {
163
270
  try {
271
+ const pipe: IRedisPipeline = typeof this.client.pipeline === 'function' ? this.client.pipeline() : this.client.multi();
272
+ const indexes: number[] = [];
273
+ let commandCount = 0;
274
+ for (const op of batch) {
275
+ indexes.push(commandCount++);
276
+ switch (op.type) {
277
+ case 'get': pipe.get(op.key); break;
278
+ case 'setex': pipe.setex(op.key, op.seconds, op.value); break;
279
+ case 'setpx': pipe.set(op.key, op.value, 'PX', op.milliseconds); break;
280
+ case 'del': pipe.del(...op.keys); break;
281
+ case 'read':
282
+ pipe.eval!(op.hash ? LUA_TIMED_READ : LUA_TIMED_STRING_READ, 1, op.key);
283
+ break;
284
+ }
285
+ }
164
286
  const results = await pipe.exec();
165
287
 
166
288
  if (!results) {
167
289
  // Pipeline returned null / aborted
168
290
  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();
291
+ op.reject(new Error('Redis pipeline aborted'));
172
292
  }
173
293
  return;
174
294
  }
175
295
 
176
296
  for (let i = 0; i < batch.length; i++) {
177
297
  const op = batch[i];
178
- const resTuple = results[i];
298
+ const resTuple = results[indexes[i]];
179
299
 
180
300
  if (!resTuple) {
181
- if (op.type === 'get') op.resolve(null);
182
- else if (op.type === 'del') op.resolve(0);
183
- else op.resolve();
301
+ op.reject(new Error('Missing Redis pipeline result'));
184
302
  continue;
185
303
  }
186
304
 
@@ -188,7 +306,13 @@ export class AutoPipeliner {
188
306
  if (err) {
189
307
  op.reject(err instanceof Error ? err : new Error(String(err)));
190
308
  } else {
191
- if (op.type === 'get') {
309
+ if (op.type === 'read') {
310
+ try {
311
+ op.resolve(op.hash ? parseTimedReadResult(val) : parseTimedStringReadResult(val));
312
+ } catch (error) {
313
+ op.reject(error instanceof Error ? error : new Error(String(error)));
314
+ }
315
+ } else if (op.type === 'get') {
192
316
  op.resolve(val != null ? String(val) : null);
193
317
  } else if (op.type === 'del') {
194
318
  op.resolve(typeof val === 'number' ? val : Number(val) || 0);