tricache 0.6.7 → 0.7.1

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 (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1428 -970
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-5GATUYAK.js +7 -0
  5. package/dist/cache-service-D8tIXmzb.d.ts +1498 -0
  6. package/dist/chunk-EUGYR7KR.js +4629 -0
  7. package/dist/chunk-UBSR5UYA.js +0 -0
  8. package/dist/{chunk-FKY5R3CE.js → chunk-X5AXHPVD.js} +139 -6
  9. package/dist/cli.cjs +5238 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5218 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5374 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +200 -0
  18. package/dist/index.cjs +1245 -209
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3705
  21. package/dist/nestjs/index.cjs +5362 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5407 -0
  25. package/dist/next/index.d.ts +208 -0
  26. package/dist/next/index.js +297 -0
  27. package/dist/prisma/index.cjs +123 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +87 -0
  30. package/dist/serialize-worker.cjs +190 -15
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +71 -21
  33. package/src/cache-service.ts +3294 -2429
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +56 -0
  36. package/src/disk-tier.ts +821 -757
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +513 -442
  39. package/src/http/index.ts +265 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +268 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +154 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +1026 -1010
  53. package/src/types.ts +911 -732
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
package/dist/index.cjs CHANGED
@@ -70,6 +70,19 @@ try {
70
70
  } catch {
71
71
  _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
72
72
  }
73
+ function getTransferableArrayBuffer(buf) {
74
+ if (buf.buffer instanceof ArrayBuffer) {
75
+ if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
76
+ return buf.buffer;
77
+ }
78
+ }
79
+ if (buf.byteLength >= 131072) {
80
+ const copy = new ArrayBuffer(buf.byteLength);
81
+ new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
82
+ return copy;
83
+ }
84
+ return null;
85
+ }
73
86
  var WorkerPool = class {
74
87
  workers = [];
75
88
  pending = [];
@@ -77,66 +90,142 @@ var WorkerPool = class {
77
90
  _robin = 0;
78
91
  _available = false;
79
92
  constructor(opts) {
93
+ try {
94
+ const { workers, pending } = this._spawnWorkers(opts);
95
+ this.workers = workers;
96
+ this.pending = pending;
97
+ this._available = true;
98
+ } catch {
99
+ this._destroy();
100
+ }
101
+ }
102
+ _spawnWorkers(opts) {
80
103
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
81
104
  const workerData = {
82
105
  keyBase64: opts.keyBase64,
83
106
  mode: opts.mode,
84
107
  prevKeyBase64: opts.prevKeyBase64 ?? "",
85
- prevMode: opts.prevMode
108
+ prevMode: opts.prevMode,
109
+ compression: opts.compression ?? "none",
110
+ compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024
86
111
  };
87
- try {
88
- for (let i = 0; i < size; i++) {
89
- const worker = new import_worker_threads.Worker(_workerFile, {
90
- workerData,
91
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
92
- });
93
- const pending = /* @__PURE__ */ new Map();
94
- worker.on("message", (msg) => {
95
- const entry = pending.get(msg.id);
96
- if (!entry) return;
97
- pending.delete(msg.id);
98
- if (pending.size === 0) worker.unref();
99
- if (msg.error !== void 0) {
100
- entry.reject(new Error(msg.error));
101
- } else {
112
+ const workers = [];
113
+ const pendingList = [];
114
+ const createWorker = (index) => {
115
+ const worker = new import_worker_threads.Worker(_workerFile, {
116
+ workerData,
117
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
118
+ });
119
+ const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
120
+ if (!pendingList[index]) pendingList[index] = pending;
121
+ worker.on("message", (msg) => {
122
+ const entry = pending.get(msg.id);
123
+ if (!entry) return;
124
+ pending.delete(msg.id);
125
+ if (pending.size === 0) worker.unref();
126
+ if (msg.error !== void 0) {
127
+ entry.reject(new Error(msg.error));
128
+ } else if (msg.result !== void 0) {
129
+ if (typeof msg.result === "string") {
102
130
  entry.resolve(msg.result);
131
+ } else {
132
+ entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString("utf8"));
103
133
  }
104
- });
105
- worker.on("error", (err) => {
106
- for (const [, entry] of pending) entry.reject(err);
107
- pending.clear();
108
- worker.unref();
109
- });
134
+ }
135
+ });
136
+ worker.on("error", (err) => {
137
+ for (const [, entry] of pending) entry.reject(err);
138
+ pending.clear();
139
+ worker.unref();
140
+ });
141
+ worker.on("exit", (exitCode) => {
142
+ for (const [, entry] of pending) {
143
+ entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
144
+ }
145
+ pending.clear();
110
146
  worker.unref();
111
- this.workers.push(worker);
112
- this.pending.push(pending);
147
+ if (this._available && exitCode !== 0 && workers[index] === worker) {
148
+ try {
149
+ workers[index] = createWorker(index);
150
+ } catch {
151
+ }
152
+ }
153
+ });
154
+ worker.unref();
155
+ return worker;
156
+ };
157
+ for (let i = 0; i < size; i++) {
158
+ const worker = createWorker(i);
159
+ workers.push(worker);
160
+ }
161
+ return { workers, pending: pendingList };
162
+ }
163
+ /**
164
+ * Gracefully drain in-flight tasks and re-initialize workers with updated key material.
165
+ * Atomically swaps workers so new requests immediately route to new workers,
166
+ * while existing in-flight operations complete on old workers before termination.
167
+ */
168
+ async drainAndReinit(opts) {
169
+ const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
170
+ const oldWorkers = this.workers;
171
+ const oldPending = this.pending;
172
+ this.workers = newWorkers;
173
+ this.pending = newPending;
174
+ this._robin = 0;
175
+ this._available = true;
176
+ const start = Date.now();
177
+ while (oldPending.some((m) => m.size > 0)) {
178
+ if (Date.now() - start > 5e3) break;
179
+ await new Promise((r) => setTimeout(r, 10));
180
+ }
181
+ for (let i = 0; i < oldWorkers.length; i++) {
182
+ for (const [, entry] of oldPending[i] ?? []) {
183
+ entry.reject(new Error("WorkerPool replaced during key rotation"));
113
184
  }
114
- this._available = true;
115
- } catch {
116
- this._destroy();
185
+ oldPending[i]?.clear();
186
+ oldWorkers[i]?.terminate().catch(() => {
187
+ });
117
188
  }
118
189
  }
119
190
  get isAvailable() {
120
191
  return this._available;
121
192
  }
122
- /** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
193
+ /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
123
194
  encrypt(payload) {
124
195
  return this._dispatch("encrypt", payload);
125
196
  }
126
- /** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
197
+ /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
127
198
  decrypt(payload) {
128
199
  return this._dispatch("decrypt", payload);
129
200
  }
130
201
  _dispatch(type, payload) {
202
+ if (!this._available || this.workers.length === 0) {
203
+ return Promise.reject(new Error("WorkerPool is not available"));
204
+ }
131
205
  const id = this._nextId++;
132
206
  const idx = this._robin;
133
207
  const worker = this.workers[idx];
134
208
  const pending = this.pending[idx];
135
209
  this._robin = (this._robin + 1) % this.workers.length;
210
+ let transferable = null;
211
+ let dataToSend = typeof payload === "string" ? payload : payload;
212
+ if (typeof payload !== "string") {
213
+ transferable = getTransferableArrayBuffer(payload);
214
+ if (transferable) {
215
+ dataToSend = new Uint8Array(transferable);
216
+ }
217
+ } else if (payload.length >= 131072) {
218
+ const buf = Buffer.from(payload, "utf8");
219
+ transferable = getTransferableArrayBuffer(buf);
220
+ if (transferable) {
221
+ dataToSend = new Uint8Array(transferable);
222
+ }
223
+ }
224
+ const transferList = transferable ? [transferable] : [];
136
225
  return new Promise((resolve, reject) => {
137
226
  pending.set(id, { resolve, reject });
138
227
  worker.ref();
139
- worker.postMessage({ id, type, payload });
228
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
140
229
  });
141
230
  }
142
231
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -166,7 +255,7 @@ var import_path3 = __toESM(require("path"), 1);
166
255
 
167
256
  // src/types.ts
168
257
  var consoleLogger = {
169
- debug: (msg, meta) => {
258
+ debug: () => {
170
259
  },
171
260
  info: (msg, meta) => console.info("[tricache]", msg, meta ?? ""),
172
261
  warn: (msg, meta) => console.warn("[tricache]", msg, meta ?? ""),
@@ -201,6 +290,8 @@ var CacheEncryption = class {
201
290
  _keyObj = null;
202
291
  // parsed KeyObject — used for all AES modes
203
292
  _mode;
293
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
294
+ _strictKeyValidation;
204
295
  _prevKey = null;
205
296
  _prevKeyObj = null;
206
297
  _prevMode = "aes-256-gcm";
@@ -266,9 +357,12 @@ var CacheEncryption = class {
266
357
  }
267
358
  return out;
268
359
  }
269
- constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
270
- this._mode = mode;
271
- if (!keyBase64) {
360
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
361
+ const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
362
+ const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
363
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
364
+ this._mode = resolvedMode;
365
+ if (keyBase64 === void 0 || keyBase64 === null) {
272
366
  if (process.env.NODE_ENV === "production") {
273
367
  logger.warn(
274
368
  "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
@@ -277,11 +371,17 @@ var CacheEncryption = class {
277
371
  }
278
372
  return;
279
373
  }
374
+ if (keyBase64 === "") {
375
+ const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
376
+ if (this._strictKeyValidation) throw err;
377
+ logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
378
+ return;
379
+ }
280
380
  try {
281
381
  const buf = Buffer.from(keyBase64, "base64");
282
- const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
382
+ const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
283
383
  if (requiredLen > 0 && buf.length !== requiredLen) {
284
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
384
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
285
385
  }
286
386
  if (buf.length < 1) {
287
387
  throw new Error("XOR key must be at least 1 byte");
@@ -305,6 +405,9 @@ var CacheEncryption = class {
305
405
  logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
306
406
  }
307
407
  } catch (err) {
408
+ if (this._strictKeyValidation) {
409
+ throw err;
410
+ }
308
411
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
309
412
  }
310
413
  if (previousKeyBase64) {
@@ -330,6 +433,9 @@ var CacheEncryption = class {
330
433
  get isEnabled() {
331
434
  return this._key !== null;
332
435
  }
436
+ get mode() {
437
+ return this._mode;
438
+ }
333
439
  /**
334
440
  * Snapshot the key material needed to spin up an off-main-thread worker pool.
335
441
  * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
@@ -344,6 +450,43 @@ var CacheEncryption = class {
344
450
  prevMode: this._prevMode
345
451
  };
346
452
  }
453
+ /**
454
+ * Rotate the active encryption key dynamically at runtime.
455
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
456
+ * fallback decryption of existing cache entries in L2/Disk, and installs
457
+ * the new key as primary for all subsequent writes.
458
+ */
459
+ rotateKey(newKeyBase64, newMode) {
460
+ if (!newKeyBase64) {
461
+ throw new Error("rotateKey requires a valid non-empty base64 key");
462
+ }
463
+ const mode = newMode ?? this._mode;
464
+ const buf = Buffer.from(newKeyBase64, "base64");
465
+ const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
466
+ if (requiredLen > 0 && buf.length !== requiredLen) {
467
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
468
+ }
469
+ if (buf.length < 1) {
470
+ throw new Error("XOR key must be at least 1 byte");
471
+ }
472
+ let newKeyObj = null;
473
+ if (mode !== "xor") {
474
+ newKeyObj = (0, import_crypto.createSecretKey)(buf);
475
+ const _wc = (0, import_crypto.createCipheriv)(
476
+ mode,
477
+ newKeyObj,
478
+ Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
479
+ );
480
+ _wc.update(Buffer.alloc(0));
481
+ _wc.final();
482
+ }
483
+ this._prevKey = this._key;
484
+ this._prevKeyObj = this._keyObj;
485
+ this._prevMode = this._mode;
486
+ this._key = buf;
487
+ this._keyObj = newKeyObj;
488
+ this._mode = mode;
489
+ }
347
490
  // ── String (Redis) ────────────────────────────────────────────────────────
348
491
  /**
349
492
  * Encrypt a string for Redis storage.
@@ -534,6 +677,7 @@ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "b
534
677
  var WasmBloomFilter = class {
535
678
  exports;
536
679
  mem;
680
+ stagingTarget;
537
681
  encoder = new TextEncoder();
538
682
  numBits = 1e5;
539
683
  /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
@@ -544,13 +688,13 @@ var WasmBloomFilter = class {
544
688
  const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
545
689
  this.exports = instance.exports;
546
690
  this.mem = new Uint8Array(this.exports.memory.buffer);
691
+ this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
547
692
  const k = 7, p = 0.01;
548
693
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
549
694
  }
550
695
  writeKey(key) {
551
696
  if (key.length === 0) return 0;
552
- const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
553
- return this.encoder.encodeInto(key, target).written;
697
+ return this.encoder.encodeInto(key, this.stagingTarget).written;
554
698
  }
555
699
  add(key) {
556
700
  const len = this.writeKey(key);
@@ -590,7 +734,6 @@ var WasmBloomFilter = class {
590
734
  };
591
735
 
592
736
  // src/smart-memory-cache.ts
593
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
594
737
  var LARGE_VALUE_BYTES = 16384;
595
738
  var EVICTION_BATCH_PERCENT = 0.2;
596
739
  var EVICTION_SAMPLE = 16;
@@ -993,15 +1136,19 @@ var SmartMemoryCache = class {
993
1136
  entry.lastAccess = now;
994
1137
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
995
1138
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
996
- _hit.value = value;
997
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
998
- _hit.expiresAt = entry.expiresAt;
999
- _hit.ttlMs = entry.ttlMs;
1000
- _hit.delta = entry.delta;
1001
- _hit.fetchedAt = now;
1002
- return _hit;
1003
- }
1004
- set(key, data, ttlMs, priority = 2, staleAt, delta) {
1139
+ const hit = {
1140
+ value,
1141
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
1142
+ expiresAt: entry.expiresAt,
1143
+ ttlMs: entry.ttlMs,
1144
+ delta: entry.delta,
1145
+ fetchedAt: now,
1146
+ tagVersions: entry.tagVersions,
1147
+ setAt: entry.setAt
1148
+ };
1149
+ return hit;
1150
+ }
1151
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1005
1152
  const packed = (0, import_msgpackr.pack)(data);
1006
1153
  const size = packed.byteLength;
1007
1154
  this.compressions++;
@@ -1022,7 +1169,7 @@ var SmartMemoryCache = class {
1022
1169
  this.ensureCapacity(cat, size);
1023
1170
  const now = Date.now();
1024
1171
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1025
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
1172
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1026
1173
  if (!existingEntry) this.bloom.add(key);
1027
1174
  this.maybeRebuildBloom();
1028
1175
  this.totalSize += size;
@@ -1211,6 +1358,22 @@ var SmartMemoryCache = class {
1211
1358
  }
1212
1359
  return evicted;
1213
1360
  }
1361
+ /**
1362
+ * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
1363
+ * Used for concurrency-safe compare-and-delete on stale generational reads,
1364
+ * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
1365
+ */
1366
+ deleteIfSetBefore(key, cutoffMs) {
1367
+ const entry = this.cache.get(key);
1368
+ if (!entry) return false;
1369
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
1370
+ if (setAt <= cutoffMs) {
1371
+ const deleted = this._delete(key, "manual");
1372
+ if (deleted) this.maybeRebuildBloom();
1373
+ return deleted;
1374
+ }
1375
+ return false;
1376
+ }
1214
1377
  exportEntries(forbiddenPrefixes) {
1215
1378
  const now = Date.now();
1216
1379
  const out = [];
@@ -1414,6 +1577,63 @@ var import_fs2 = __toESM(require("fs"), 1);
1414
1577
  var import_path2 = __toESM(require("path"), 1);
1415
1578
  var import_crypto2 = __toESM(require("crypto"), 1);
1416
1579
  var import_msgpackr2 = require("msgpackr");
1580
+
1581
+ // src/compression.ts
1582
+ var import_zlib = __toESM(require("zlib"), 1);
1583
+ var PREFIX_COMPRESSED = "cmp:v1:";
1584
+ var PREFIX_ENC_COMPRESSED = "ecp:v1:";
1585
+ var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
1586
+ function isCompressed(buf) {
1587
+ return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1588
+ }
1589
+ function compressBuffer(buf, algorithm) {
1590
+ if (algorithm === "brotli") {
1591
+ return import_zlib.default.brotliCompressSync(buf, {
1592
+ params: {
1593
+ [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4
1594
+ // Fast level 4 compression
1595
+ }
1596
+ });
1597
+ }
1598
+ if (algorithm === "gzip") {
1599
+ return import_zlib.default.gzipSync(buf, { level: 6 });
1600
+ }
1601
+ return buf;
1602
+ }
1603
+ function decompressBuffer(buf, algorithm = "brotli") {
1604
+ const tryBrotli = () => {
1605
+ try {
1606
+ return import_zlib.default.brotliDecompressSync(buf);
1607
+ } catch {
1608
+ return null;
1609
+ }
1610
+ };
1611
+ const tryGzip = () => {
1612
+ try {
1613
+ return import_zlib.default.gunzipSync(buf);
1614
+ } catch {
1615
+ return null;
1616
+ }
1617
+ };
1618
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
1619
+ if (result === null) {
1620
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1621
+ }
1622
+ return result;
1623
+ }
1624
+ function compressWithHeader(buf, algorithm) {
1625
+ if (algorithm === "none") return buf;
1626
+ const compressed = compressBuffer(buf, algorithm);
1627
+ return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1628
+ }
1629
+ function decompressWithHeader(buf, algorithm = "brotli") {
1630
+ if (isCompressed(buf)) {
1631
+ return decompressBuffer(buf.subarray(4), algorithm);
1632
+ }
1633
+ return buf;
1634
+ }
1635
+
1636
+ // src/disk-tier.ts
1417
1637
  var _SqliteDB = null;
1418
1638
  try {
1419
1639
  const sqlite = process.getBuiltinModule("node:sqlite");
@@ -1671,26 +1891,46 @@ var DiskTier = class {
1671
1891
  };
1672
1892
  const packed = (0, import_msgpackr2.pack)(payload);
1673
1893
  if (packed.length > this.opts.entryMaxBytes) return;
1894
+ let toEncrypt = packed;
1895
+ if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
1896
+ toEncrypt = compressWithHeader(packed, this.opts.compression);
1897
+ }
1674
1898
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1675
1899
  DISK_MAGIC_V2.copy(header, 0);
1676
1900
  header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1677
- final = Buffer.concat([header, this.encryptV2(packed)]);
1901
+ final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
1678
1902
  } catch (err) {
1679
1903
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1680
1904
  return;
1681
1905
  }
1682
1906
  const hash = this.keyToHash(key);
1683
1907
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
1908
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1684
1909
  this.diskUsageBytes += final.length;
1685
1910
  this.fileCount++;
1686
1911
  try {
1687
1912
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
1688
- await import_fs2.default.promises.writeFile(filePath, final, { mode: 384 });
1913
+ await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
1914
+ try {
1915
+ await import_fs2.default.promises.rename(tmpPath, filePath);
1916
+ } catch (renameErr) {
1917
+ const code = renameErr?.code;
1918
+ if (code === "EBUSY" || code === "EPERM") {
1919
+ await new Promise((resolve) => setTimeout(resolve, 5));
1920
+ await import_fs2.default.promises.rename(tmpPath, filePath);
1921
+ } else {
1922
+ throw renameErr;
1923
+ }
1924
+ }
1689
1925
  if (this._db) {
1690
1926
  this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1691
1927
  }
1692
1928
  this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1693
1929
  } catch (err) {
1930
+ try {
1931
+ await import_fs2.default.promises.unlink(tmpPath);
1932
+ } catch {
1933
+ }
1694
1934
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1695
1935
  this.fileCount = Math.max(0, this.fileCount - 1);
1696
1936
  if (this._db) try {
@@ -1774,7 +2014,8 @@ var DiskTier = class {
1774
2014
  return null;
1775
2015
  }
1776
2016
  }
1777
- const payload = (0, import_msgpackr2.unpack)(decrypted);
2017
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
2018
+ const payload = (0, import_msgpackr2.unpack)(uncompressed);
1778
2019
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1779
2020
  if (payload.entry.expiresAt <= Date.now()) return null;
1780
2021
  const entry = payload.entry;
@@ -1833,6 +2074,17 @@ var DiskTier = class {
1833
2074
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1834
2075
  for (const filePath of this.walkCacheFiles()) {
1835
2076
  const filename = import_path2.default.basename(filePath);
2077
+ if (filename.endsWith(".tmp")) {
2078
+ try {
2079
+ const stat = import_fs2.default.statSync(filePath);
2080
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
2081
+ import_fs2.default.unlinkSync(filePath);
2082
+ purged++;
2083
+ }
2084
+ } catch {
2085
+ }
2086
+ continue;
2087
+ }
1836
2088
  if (filename.length === 77 && filename[64] === "_") {
1837
2089
  const expiresAt = parseInt(filename.slice(65), 16);
1838
2090
  if (expiresAt <= now) {
@@ -1881,6 +2133,7 @@ var DiskTier = class {
1881
2133
  dec = this.decrypt(raw);
1882
2134
  } catch {
1883
2135
  import_fs2.default.unlinkSync(filePath);
2136
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1884
2137
  this.fileCount = Math.max(0, this.fileCount - 1);
1885
2138
  purged++;
1886
2139
  continue;
@@ -1942,6 +2195,17 @@ var DiskTier = class {
1942
2195
  return expired.length;
1943
2196
  }
1944
2197
  for (const file of orphanFiles) {
2198
+ if (file.endsWith(".tmp")) {
2199
+ const fp = import_path2.default.join(orphanBucketP, file);
2200
+ try {
2201
+ const stat = import_fs2.default.statSync(fp);
2202
+ if (now2 - stat.mtimeMs > 5 * 60 * 1e3) {
2203
+ import_fs2.default.unlinkSync(fp);
2204
+ }
2205
+ } catch {
2206
+ }
2207
+ continue;
2208
+ }
1945
2209
  if (file.length === 77 && file[64] === "_") {
1946
2210
  const expiresAt = parseInt(file.slice(65), 16);
1947
2211
  if (expiresAt <= now2) {
@@ -1971,6 +2235,18 @@ var DiskTier = class {
1971
2235
  let purged = 0;
1972
2236
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1973
2237
  for (const file of files) {
2238
+ if (file.endsWith(".tmp")) {
2239
+ const fp = import_path2.default.join(bucketPath, file);
2240
+ try {
2241
+ const stat = import_fs2.default.statSync(fp);
2242
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
2243
+ import_fs2.default.unlinkSync(fp);
2244
+ purged++;
2245
+ }
2246
+ } catch {
2247
+ }
2248
+ continue;
2249
+ }
1974
2250
  if (file.length === 77 && file[64] === "_") {
1975
2251
  const expiresAt = parseInt(file.slice(65), 16);
1976
2252
  if (expiresAt <= now) {
@@ -2021,6 +2297,7 @@ var DiskTier = class {
2021
2297
  dec = this.decrypt(raw);
2022
2298
  } catch {
2023
2299
  import_fs2.default.unlinkSync(filePath);
2300
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2024
2301
  this.fileCount = Math.max(0, this.fileCount - 1);
2025
2302
  purged++;
2026
2303
  continue;
@@ -2089,13 +2366,40 @@ var DiskTier = class {
2089
2366
  };
2090
2367
 
2091
2368
  // src/cache-service.ts
2369
+ var LUA_COMPARE_AND_DELETE = `
2370
+ local currentTs = redis.call('HGET', KEYS[1], 't')
2371
+ if currentTs and currentTs == ARGV[1] then
2372
+ return redis.call('DEL', KEYS[1])
2373
+ end
2374
+ return 0
2375
+ `;
2092
2376
  var SNAPSHOT_VERSION = 1;
2093
2377
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
2378
+ var INDEFINITE_TTL_SECONDS = 31536e3;
2094
2379
  var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
2095
2380
  var DEFAULT_CATEGORY_LIMITS = {
2096
2381
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
2097
2382
  };
2098
2383
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
2384
+ var DEFAULT_COUNTER_TTL_SECONDS = 60;
2385
+ var GLOB_REGEX_CACHE_MAX = 256;
2386
+ var globRegexCache = /* @__PURE__ */ new Map();
2387
+ function getGlobRegex(pattern) {
2388
+ let re = globRegexCache.get(pattern);
2389
+ if (re) {
2390
+ globRegexCache.delete(pattern);
2391
+ globRegexCache.set(pattern, re);
2392
+ return re;
2393
+ }
2394
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
2395
+ re = new RegExp("^" + escaped + "$");
2396
+ if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
2397
+ const oldestKey = globRegexCache.keys().next().value;
2398
+ if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
2399
+ }
2400
+ globRegexCache.set(pattern, re);
2401
+ return re;
2402
+ }
2099
2403
  var L2CircuitBreaker = class {
2100
2404
  constructor(threshold, cooldownMs) {
2101
2405
  this.threshold = threshold;
@@ -2276,6 +2580,8 @@ var CacheService = class _CacheService {
2276
2580
  _l1Counters = /* @__PURE__ */ new Map();
2277
2581
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
2278
2582
  tagIndex = /* @__PURE__ */ new Map();
2583
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
2584
+ tagVersions = /* @__PURE__ */ new Map();
2279
2585
  /**
2280
2586
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
2281
2587
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -2284,6 +2590,10 @@ var CacheService = class _CacheService {
2284
2590
  redis = null;
2285
2591
  redisConnecting = null;
2286
2592
  cb;
2593
+ /** In-process mutex lock map for single-process environments or Redis outages. */
2594
+ _localLocks = /* @__PURE__ */ new Map();
2595
+ /** Active OpenTelemetry monotonic counters. */
2596
+ _otelMetrics = {};
2287
2597
  snapshotLoaded = false;
2288
2598
  _readyPromise = Promise.resolve();
2289
2599
  cleanupInterval = null;
@@ -2294,7 +2604,11 @@ var CacheService = class _CacheService {
2294
2604
  latencyTracker = null;
2295
2605
  instanceId;
2296
2606
  backplaneChannel;
2607
+ backplaneStreamKey;
2297
2608
  subClient = null;
2609
+ streamClient = null;
2610
+ _lastStreamId = "$";
2611
+ _destroyed = false;
2298
2612
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2299
2613
  _subDisconnectedAt = null;
2300
2614
  counters = {
@@ -2310,13 +2624,18 @@ var CacheService = class _CacheService {
2310
2624
  invSent: 0,
2311
2625
  invReceived: 0,
2312
2626
  invSkipped: 0,
2627
+ streamEntriesReceived: 0,
2628
+ streamReplays: 0,
2629
+ streamGaps: 0,
2313
2630
  oomEvictions: 0,
2314
2631
  oomLastAt: null,
2315
2632
  /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
2316
2633
  counterErrors: 0,
2317
2634
  /** Times a later `create(ns)` call passed options differing from the live singleton. */
2318
2635
  singletonDivergences: 0,
2319
- startedAt: Date.now()
2636
+ startedAt: Date.now(),
2637
+ bloomChecks: 0,
2638
+ bloomFalsePositives: 0
2320
2639
  };
2321
2640
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2322
2641
  _incrementFallbackWarned = false;
@@ -2331,7 +2650,8 @@ var CacheService = class _CacheService {
2331
2650
  logger,
2332
2651
  options.encryptionMode,
2333
2652
  options.previousEncryptionKey,
2334
- options.previousEncryptionMode
2653
+ options.previousEncryptionMode,
2654
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2335
2655
  );
2336
2656
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2337
2657
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
@@ -2340,7 +2660,7 @@ var CacheService = class _CacheService {
2340
2660
  logger,
2341
2661
  l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
2342
2662
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2343
- categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits ?? {} },
2663
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2344
2664
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2345
2665
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2346
2666
  // two instances with different namespaces never share cache files.
@@ -2353,8 +2673,14 @@ var CacheService = class _CacheService {
2353
2673
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2354
2674
  redisPort: options.redisPort ?? 6379,
2355
2675
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2356
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2676
+ disableRedis: options.disableRedis ?? (() => {
2677
+ const explicitConfig = Boolean(
2678
+ options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2679
+ );
2680
+ return !explicitConfig && process.env.NODE_ENV !== "production";
2681
+ })(),
2357
2682
  encryptionKey: encKeyRaw,
2683
+ encryptionMode: options.encryptionMode,
2358
2684
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2359
2685
  import_os2.default.tmpdir(),
2360
2686
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
@@ -2373,6 +2699,7 @@ var CacheService = class _CacheService {
2373
2699
  l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
2374
2700
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
2375
2701
  tracer: options.tracer,
2702
+ meter: options.meter,
2376
2703
  notFoundTtl: options.notFoundTtl ?? 0,
2377
2704
  warmKeys: options.warmKeys,
2378
2705
  onHit: options.onHit,
@@ -2391,8 +2718,19 @@ var CacheService = class _CacheService {
2391
2718
  disableDisk: options.disableDisk ?? false,
2392
2719
  redisClusterNodes: options.redisClusterNodes,
2393
2720
  redisSentinel: options.redisSentinel,
2721
+ redisProtocol: options.redisProtocol,
2722
+ useShardedPubSub: options.useShardedPubSub ?? false,
2723
+ compression: options.compression ?? "none",
2724
+ compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
2394
2725
  strictSingleton: options.strictSingleton ?? false,
2395
- failClosed: options.failClosed ?? false
2726
+ failClosed: options.failClosed ?? false,
2727
+ tagStrategy: options.tagStrategy ?? "set",
2728
+ tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
2729
+ cloneStrategy: options.cloneStrategy ?? "none",
2730
+ backplaneMode: options.backplaneMode ?? "pubsub",
2731
+ backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2732
+ backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2733
+ backplaneStreamKey: options.backplaneStreamKey
2396
2734
  };
2397
2735
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2398
2736
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -2422,6 +2760,8 @@ var CacheService = class _CacheService {
2422
2760
  entryMaxBytes: this.opts.diskEntryMaxBytes,
2423
2761
  forbiddenPrefixes,
2424
2762
  encryption: this.enc.isEnabled ? this.enc : null,
2763
+ compression: this.opts.compression,
2764
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2425
2765
  logger
2426
2766
  });
2427
2767
  this._namespace = ns;
@@ -2446,11 +2786,10 @@ var CacheService = class _CacheService {
2446
2786
  }
2447
2787
  this._shutdownHandler = () => {
2448
2788
  if (!this._diskDisabled) this.writeSnapshot();
2449
- process.exit(0);
2450
2789
  };
2451
2790
  process.once("SIGTERM", this._shutdownHandler);
2452
2791
  process.once("SIGINT", this._shutdownHandler);
2453
- if (this.opts.workerThreads && this.enc.isEnabled) {
2792
+ if (this.opts.workerThreads) {
2454
2793
  try {
2455
2794
  const encRef = this.enc.toWorkerInit();
2456
2795
  this._workerPool = new WorkerPool({
@@ -2458,6 +2797,8 @@ var CacheService = class _CacheService {
2458
2797
  mode: encRef.mode,
2459
2798
  prevKeyBase64: encRef.prevKeyBase64,
2460
2799
  prevMode: encRef.prevMode,
2800
+ compression: this.opts.compression,
2801
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2461
2802
  size: this.opts.workerPoolSize || void 0
2462
2803
  });
2463
2804
  if (this._workerPool.isAvailable) {
@@ -2513,10 +2854,30 @@ var CacheService = class _CacheService {
2513
2854
  }
2514
2855
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
2515
2856
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2857
+ this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2516
2858
  this.initBackplane();
2517
2859
  if (this.opts.warmKeys) {
2518
2860
  this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
2519
2861
  }
2862
+ if (this.opts.meter) {
2863
+ this._initOtelMetrics(this.opts.meter);
2864
+ const otel = this._otelMetrics;
2865
+ const nsAttr = this._namespace ? { namespace: this._namespace } : void 0;
2866
+ const targetCounters = this.counters;
2867
+ this.counters = new Proxy(targetCounters, {
2868
+ set(target, prop, value, receiver) {
2869
+ const oldVal = target[prop];
2870
+ const ok = Reflect.set(target, prop, value, receiver);
2871
+ if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
2872
+ const diff = value - oldVal;
2873
+ if (diff > 0 && otel[prop]) {
2874
+ otel[prop].add(diff, nsAttr);
2875
+ }
2876
+ }
2877
+ return ok;
2878
+ }
2879
+ });
2880
+ }
2520
2881
  }
2521
2882
  // ── Singleton factory ─────────────────────────────────────────────────────
2522
2883
  /**
@@ -2603,7 +2964,10 @@ var CacheService = class _CacheService {
2603
2964
  disableRedis: this._redisDisabled,
2604
2965
  redisClusterNodes: o.redisClusterNodes,
2605
2966
  redisSentinel: o.redisSentinel,
2606
- encryptionKey: o.encryptionKey,
2967
+ // Never surface key material through diagnostics — a JSON.stringify of
2968
+ // this object previously leaked the raw encryption key.
2969
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
2970
+ encryptionMode: o.encryptionMode,
2607
2971
  l2WriteMode: o.l2WriteMode,
2608
2972
  instanceName: o.instanceName,
2609
2973
  frozen: o.frozen,
@@ -2676,20 +3040,18 @@ var CacheService = class _CacheService {
2676
3040
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
2677
3041
  return _CacheService._nullSpan;
2678
3042
  }
2679
- initBackplane() {
2680
- if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2681
- if (this.subClient) return;
2682
- let sub;
3043
+ createDedicatedRedisClient() {
2683
3044
  if (this.opts.redisClusterNodes?.length) {
2684
- sub = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
3045
+ return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
2685
3046
  redisOptions: {
2686
3047
  tls: this.opts.redisTls ? {} : void 0,
2687
3048
  connectTimeout: 1e4,
2688
- maxRetriesPerRequest: null
3049
+ maxRetriesPerRequest: null,
3050
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2689
3051
  }
2690
3052
  });
2691
3053
  } else if (this.opts.redisSentinel) {
2692
- sub = new import_ioredis.Redis({
3054
+ return new import_ioredis.Redis({
2693
3055
  sentinels: this.opts.redisSentinel.sentinels,
2694
3056
  name: this.opts.redisSentinel.name,
2695
3057
  tls: this.opts.redisTls ? {} : void 0,
@@ -2697,10 +3059,11 @@ var CacheService = class _CacheService {
2697
3059
  lazyConnect: true,
2698
3060
  maxRetriesPerRequest: null,
2699
3061
  enableAutoPipelining: false,
2700
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3062
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3063
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2701
3064
  });
2702
3065
  } else {
2703
- sub = new import_ioredis.Redis({
3066
+ return new import_ioredis.Redis({
2704
3067
  host: this.opts.redisHost,
2705
3068
  port: this.opts.redisPort,
2706
3069
  tls: this.opts.redisTls ? {} : void 0,
@@ -2709,10 +3072,24 @@ var CacheService = class _CacheService {
2709
3072
  maxRetriesPerRequest: null,
2710
3073
  enableAutoPipelining: false,
2711
3074
  family: 4,
2712
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3075
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3076
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2713
3077
  });
2714
3078
  }
2715
- sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
3079
+ }
3080
+ initBackplane() {
3081
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
3082
+ if (this.opts.backplaneMode === "stream") {
3083
+ if (this.streamClient) return;
3084
+ void this._startStreamConsumer();
3085
+ return;
3086
+ }
3087
+ if (this.subClient) return;
3088
+ const sub = this.createDedicatedRedisClient();
3089
+ sub.on("error", (e) => {
3090
+ this._checkAndLogResp3Hint(e);
3091
+ this.logger.debug("Backplane subscriber error", { error: e.message });
3092
+ });
2716
3093
  sub.on("close", () => {
2717
3094
  if (this._subDisconnectedAt === null) {
2718
3095
  this._subDisconnectedAt = Date.now();
@@ -2733,22 +3110,155 @@ var CacheService = class _CacheService {
2733
3110
  this._subDisconnectedAt = null;
2734
3111
  }
2735
3112
  });
2736
- sub.on("message", (_channel, message) => {
2737
- this._handleBackplaneMessage(message);
2738
- });
2739
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
2740
- channel: this.backplaneChannel,
2741
- instanceId: this.instanceId
2742
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
2743
- error: err.message
2744
- }));
3113
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
3114
+ if (isClusterSharded) {
3115
+ sub.on("smessage", (_channel, message) => {
3116
+ this._handleBackplaneMessage(message);
3117
+ });
3118
+ sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
3119
+ channel: this.backplaneChannel,
3120
+ instanceId: this.instanceId
3121
+ })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
3122
+ error: err.message
3123
+ }));
3124
+ } else {
3125
+ sub.on("message", (_channel, message) => {
3126
+ this._handleBackplaneMessage(message);
3127
+ });
3128
+ sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
3129
+ channel: this.backplaneChannel,
3130
+ instanceId: this.instanceId
3131
+ })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
3132
+ error: err.message
3133
+ }));
3134
+ }
2745
3135
  this.subClient = sub;
2746
3136
  }
3137
+ async _startStreamConsumer() {
3138
+ const sub = this.streamClient ?? this.createDedicatedRedisClient();
3139
+ this.streamClient = sub;
3140
+ if (typeof sub.on === "function") {
3141
+ sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
3142
+ sub.on("close", () => {
3143
+ if (this._subDisconnectedAt === null) {
3144
+ this._subDisconnectedAt = Date.now();
3145
+ this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
3146
+ }
3147
+ });
3148
+ sub.on("ready", () => {
3149
+ if (this._subDisconnectedAt !== null) {
3150
+ this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
3151
+ this._subDisconnectedAt = null;
3152
+ }
3153
+ });
3154
+ }
3155
+ const runLoop = async () => {
3156
+ while (!this._destroyed && !this._redisDisabled) {
3157
+ try {
3158
+ const res = await sub.xread(
3159
+ "BLOCK",
3160
+ this.opts.backplaneStreamBlockMs,
3161
+ "STREAMS",
3162
+ this.backplaneStreamKey,
3163
+ this._lastStreamId
3164
+ );
3165
+ if (this._destroyed) break;
3166
+ if (res && res.length > 0) {
3167
+ for (const [, entries] of res) {
3168
+ if (entries.length > 0) {
3169
+ if (this._lastStreamId !== "$") {
3170
+ this.counters.streamReplays++;
3171
+ }
3172
+ for (const [id, fields] of entries) {
3173
+ this._lastStreamId = id;
3174
+ this.counters.streamEntriesReceived++;
3175
+ this._processStreamEntry(fields);
3176
+ }
3177
+ }
3178
+ }
3179
+ } else {
3180
+ await new Promise((resolve) => setTimeout(resolve, 10));
3181
+ }
3182
+ } catch (err) {
3183
+ if (this._destroyed) break;
3184
+ const msg = err.message ?? "";
3185
+ if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
3186
+ this.counters.streamGaps++;
3187
+ this.l1.clear();
3188
+ this._lastStreamId = "$";
3189
+ }
3190
+ await new Promise((resolve) => setTimeout(resolve, 200));
3191
+ }
3192
+ }
3193
+ };
3194
+ void runLoop();
3195
+ }
3196
+ /**
3197
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
3198
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
3199
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
3200
+ * key/src must be non-empty strings, tagVersion must parse to a finite
3201
+ * number. Invalid entries are logged and dropped — never applied.
3202
+ */
3203
+ /** @internal Exposed for testing. */
3204
+ _processStreamEntry(fields) {
3205
+ let op = "";
3206
+ let key = "";
3207
+ let src = "";
3208
+ let tagVersionRaw;
3209
+ for (let i = 0; i + 1 < fields.length; i += 2) {
3210
+ const f = fields[i];
3211
+ const v = fields[i + 1];
3212
+ if (f === "op") op = v;
3213
+ else if (f === "key") key = v;
3214
+ else if (f === "src") src = v;
3215
+ else if (f === "tagVersion") tagVersionRaw = v;
3216
+ }
3217
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
3218
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
3219
+ this.logger.warn("Backplane: rejected invalid stream entry", {
3220
+ op: String(op).slice(0, 40),
3221
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
3222
+ });
3223
+ return;
3224
+ }
3225
+ let tagVersion;
3226
+ if (tagVersionRaw !== void 0) {
3227
+ const parsed = parseInt(tagVersionRaw, 10);
3228
+ if (!Number.isFinite(parsed)) {
3229
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
3230
+ return;
3231
+ }
3232
+ tagVersion = parsed;
3233
+ }
3234
+ if (src === this.instanceId) {
3235
+ this.counters.invSkipped++;
3236
+ return;
3237
+ }
3238
+ this.counters.invReceived++;
3239
+ this._applyInvalidationEvent(op, key, tagVersion);
3240
+ }
3241
+ _applyInvalidationEvent(op, key, tagVersion) {
3242
+ if (op === "del") {
3243
+ this.l1.delete(key);
3244
+ setImmediate(() => {
3245
+ if (!this._diskDisabled) this.disk.delete(key);
3246
+ });
3247
+ this._cascadeDependencies(key);
3248
+ } else if (op === "del-glob") {
3249
+ this.l1.deletePattern(key);
3250
+ } else if (op === "tag_incr") {
3251
+ const tag = key;
3252
+ const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
3253
+ this._setLocalTagVersion(tag, ver, Date.now());
3254
+ }
3255
+ this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
3256
+ }
2747
3257
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
2748
3258
  _handleBackplaneMessage(message) {
2749
3259
  try {
2750
3260
  const msg = JSON.parse(message);
2751
- if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob") {
3261
+ if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
2752
3262
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
2753
3263
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
2754
3264
  });
@@ -2759,35 +3269,133 @@ var CacheService = class _CacheService {
2759
3269
  return;
2760
3270
  }
2761
3271
  this.counters.invReceived++;
2762
- if (msg.op === "del") {
2763
- this.l1.delete(msg.key);
2764
- setImmediate(() => {
2765
- if (!this._diskDisabled) this.disk.delete(msg.key);
2766
- });
2767
- this._cascadeDependencies(msg.key);
2768
- } else if (msg.op === "del-glob") {
2769
- this.l1.deletePattern(msg.key);
2770
- }
2771
- this.logger.debug("Backplane: peer invalidation applied", {
2772
- op: msg.op,
2773
- key: msg.key.slice(0, 60)
2774
- });
3272
+ this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === "number" ? msg.tagVersion : void 0);
2775
3273
  } catch {
2776
3274
  this.logger.warn("Backplane: malformed message JSON parse failed");
2777
3275
  }
2778
3276
  }
2779
- async publishInvalidation(op, key) {
3277
+ async publishInvalidation(op, key, tagVersion) {
2780
3278
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2781
3279
  try {
2782
3280
  const client = await this.getRedis();
2783
- await client.publish(
2784
- this.backplaneChannel,
2785
- JSON.stringify({ op, key, src: this.instanceId })
2786
- );
3281
+ if (this.opts.backplaneMode === "stream") {
3282
+ const args = [
3283
+ this.backplaneStreamKey,
3284
+ "MAXLEN",
3285
+ "~",
3286
+ String(this.opts.backplaneStreamMaxLen),
3287
+ "*",
3288
+ "op",
3289
+ op,
3290
+ "key",
3291
+ key,
3292
+ "src",
3293
+ this.instanceId
3294
+ ];
3295
+ if (typeof tagVersion === "number") {
3296
+ args.push("tagVersion", String(tagVersion));
3297
+ }
3298
+ await client.xadd(...args);
3299
+ this.counters.invSent++;
3300
+ return;
3301
+ }
3302
+ const payload = JSON.stringify({ op, key, src: this.instanceId, tagVersion });
3303
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
3304
+ if (isClusterSharded && typeof client.spublish === "function") {
3305
+ await client.spublish(
3306
+ this.backplaneChannel,
3307
+ payload
3308
+ );
3309
+ } else {
3310
+ await client.publish(
3311
+ this.backplaneChannel,
3312
+ payload
3313
+ );
3314
+ }
2787
3315
  this.counters.invSent++;
2788
3316
  } catch {
2789
3317
  }
2790
3318
  }
3319
+ _setLocalTagVersion(tag, version, now = Date.now()) {
3320
+ const existing = this.tagVersions.get(tag)?.version ?? 0;
3321
+ const finalVersion = Math.max(existing, version);
3322
+ if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
3323
+ const oldestKey = this.tagVersions.keys().next().value;
3324
+ if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
3325
+ }
3326
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
3327
+ }
3328
+ async _getTagVersion(tag) {
3329
+ const now = Date.now();
3330
+ const local = this.tagVersions.get(tag);
3331
+ if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
3332
+ return local.version;
3333
+ }
3334
+ if (!this._redisDisabled) {
3335
+ try {
3336
+ const client = await this.getRedis();
3337
+ const raw = await client.get(this.nk(`tag_ver:${tag}`));
3338
+ const version = raw ? parseInt(raw, 10) : 0;
3339
+ this._setLocalTagVersion(tag, version, now);
3340
+ return version;
3341
+ } catch {
3342
+ }
3343
+ }
3344
+ return local?.version ?? 0;
3345
+ }
3346
+ _deleteIfStale(k, setAtMs) {
3347
+ this.l1.deleteIfSetBefore(k, setAtMs);
3348
+ if (!this._diskDisabled) this.disk.delete(k);
3349
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3350
+ void this.getRedis().then((client) => {
3351
+ return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
3352
+ }).catch(() => {
3353
+ });
3354
+ }
3355
+ }
3356
+ /**
3357
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
3358
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
3359
+ */
3360
+ async _serializeAndEncrypt(serialized) {
3361
+ const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
3362
+ if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
3363
+ return this._workerPool.encrypt(serialized);
3364
+ }
3365
+ if (isCompressed2) {
3366
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
3367
+ if (this.enc.isEnabled) {
3368
+ const encrypted = this.enc.encryptBuffer(compressed);
3369
+ return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
3370
+ }
3371
+ return PREFIX_COMPRESSED + compressed.toString("base64");
3372
+ }
3373
+ return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3374
+ }
3375
+ /**
3376
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
3377
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
3378
+ */
3379
+ async _decryptAndDeserialize(raw) {
3380
+ let plain;
3381
+ if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
3382
+ plain = await this._workerPool.decrypt(raw);
3383
+ } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
3384
+ const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
3385
+ const decBuf = this.enc.decryptBuffer(encBuf);
3386
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
3387
+ plain = decompressed.toString("utf8");
3388
+ } else if (raw.startsWith(PREFIX_COMPRESSED)) {
3389
+ const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
3390
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
3391
+ plain = decompressed.toString("utf8");
3392
+ } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
3393
+ plain = this.enc.decrypt(raw);
3394
+ } else {
3395
+ plain = raw;
3396
+ }
3397
+ return JSON.parse(plain);
3398
+ }
2791
3399
  /**
2792
3400
  * Scan all keys matching `pattern` across single-node or Cluster clients.
2793
3401
  * For Cluster, iterates every master node independently (SCAN is node-local).
@@ -2814,8 +3422,18 @@ var CacheService = class _CacheService {
2814
3422
  }
2815
3423
  return keys;
2816
3424
  }
3425
+ _checkAndLogResp3Hint(err) {
3426
+ const msg = err?.message || "";
3427
+ if (!this.opts.redisProtocol && (msg.includes("unknown command") || msg.includes("HELLO") || msg.includes("protocol error") || msg.includes("ProtocolError") || msg.includes("Connection is closed"))) {
3428
+ this.logger.warn(
3429
+ "Redis connection/protocol error detected. If your Redis endpoint or proxy (e.g. Twemproxy, Envoy, older ElastiCache) does not support RESP3, set redisProtocol: 2 in CacheOptions to force RESP2 compatibility.",
3430
+ { hint: "redisProtocol: 2", originalError: msg }
3431
+ );
3432
+ }
3433
+ }
2817
3434
  async getRedis() {
2818
3435
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
3436
+ if (this.redis) return this.redis;
2819
3437
  if (this.redisConnecting) return this.redisConnecting;
2820
3438
  this.redisConnecting = (async () => {
2821
3439
  try {
@@ -2826,14 +3444,18 @@ var CacheService = class _CacheService {
2826
3444
  tls: this.opts.redisTls ? {} : void 0,
2827
3445
  connectTimeout: 1e4,
2828
3446
  maxRetriesPerRequest: 3,
2829
- keepAlive: 3e4
3447
+ keepAlive: 3e4,
3448
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2830
3449
  },
2831
3450
  enableAutoPipelining: true,
2832
3451
  retryDelayOnClusterDown: 200,
2833
3452
  retryDelayOnFailover: 1e3
2834
3453
  });
2835
3454
  client.on("connect", () => this.logger.info("Redis Cluster connected"));
2836
- client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
3455
+ client.on("error", (e) => {
3456
+ this._checkAndLogResp3Hint(e);
3457
+ this.logger.error("Redis Cluster error", {}, e);
3458
+ });
2837
3459
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
2838
3460
  } else if (this.opts.redisSentinel) {
2839
3461
  client = new import_ioredis.Redis({
@@ -2845,10 +3467,14 @@ var CacheService = class _CacheService {
2845
3467
  maxRetriesPerRequest: 3,
2846
3468
  enableAutoPipelining: true,
2847
3469
  keepAlive: 3e4,
2848
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3470
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3471
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2849
3472
  });
2850
3473
  client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
2851
- client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
3474
+ client.on("error", (e) => {
3475
+ this._checkAndLogResp3Hint(e);
3476
+ this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e);
3477
+ });
2852
3478
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
2853
3479
  } else {
2854
3480
  client = new import_ioredis.Redis({
@@ -2861,15 +3487,22 @@ var CacheService = class _CacheService {
2861
3487
  enableAutoPipelining: true,
2862
3488
  keepAlive: 3e4,
2863
3489
  family: 4,
2864
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3490
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3491
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2865
3492
  });
2866
3493
  client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2867
- client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
3494
+ client.on("error", (e) => {
3495
+ this._checkAndLogResp3Hint(e);
3496
+ this.logger.error("Redis error", { host: this.opts.redisHost }, e);
3497
+ });
2868
3498
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2869
3499
  }
2870
3500
  await new Promise((resolve, reject) => {
2871
3501
  client.once("ready", resolve);
2872
- client.once("error", reject);
3502
+ client.once("error", (e) => {
3503
+ this._checkAndLogResp3Hint(e);
3504
+ reject(e);
3505
+ });
2873
3506
  setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
2874
3507
  });
2875
3508
  this.cb.onSuccess();
@@ -2879,6 +3512,7 @@ var CacheService = class _CacheService {
2879
3512
  } catch (err) {
2880
3513
  this.cb.onFailure();
2881
3514
  this.redisConnecting = null;
3515
+ this._checkAndLogResp3Hint(err);
2882
3516
  throw err;
2883
3517
  }
2884
3518
  })();
@@ -2893,6 +3527,7 @@ var CacheService = class _CacheService {
2893
3527
  const packed = (0, import_msgpackr3.pack)(payload);
2894
3528
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2895
3529
  const dest = altPath ?? this.opts.snapshotPath;
3530
+ import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
2896
3531
  import_fs3.default.writeFileSync(dest, final, { mode: 384 });
2897
3532
  this.logger.info("Cache snapshot written", {
2898
3533
  path: dest,
@@ -2984,44 +3619,58 @@ var CacheService = class _CacheService {
2984
3619
  const optTags = opts.tags;
2985
3620
  const l1Hit = this.l1.get(k);
2986
3621
  if (l1Hit !== null) {
2987
- if (l1Hit.isStale) {
2988
- const swrGraceMs2 = optSwr * 1e3;
2989
- if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
2990
- const priority2 = optPriority ?? inferPriority(cacheKey);
2991
- this.revalidating.add(k);
2992
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
2993
- this.counters.swrRevalidations++;
2994
- this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
2995
- } else {
2996
- this.logger.debug("L1 hit");
3622
+ let isGenerationalStale = false;
3623
+ if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3624
+ for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3625
+ const currentVer = await this._getTagVersion(tag);
3626
+ if (currentVer > entryVer) {
3627
+ isGenerationalStale = true;
3628
+ break;
3629
+ }
2997
3630
  }
3631
+ }
3632
+ if (isGenerationalStale) {
3633
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
2998
3634
  } else {
2999
- this.logger.debug("L1 hit");
3000
- const ra = optRefreshAhead;
3001
- const xb = optXfetchBeta;
3002
- if (ra || xb) {
3003
- const now = l1Hit.fetchedAt ?? Date.now();
3004
- const remaining = l1Hit.expiresAt - now;
3005
- const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
3006
- const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
3007
- const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
3008
- if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3635
+ if (l1Hit.isStale) {
3636
+ const swrGraceMs2 = optSwr * 1e3;
3637
+ if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
3009
3638
  const priority2 = optPriority ?? inferPriority(cacheKey);
3010
3639
  this.revalidating.add(k);
3011
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
3640
+ void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
3012
3641
  this.counters.swrRevalidations++;
3013
- this.logger.debug(
3014
- shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
3015
- { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
3016
- );
3642
+ this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
3643
+ } else {
3644
+ this.logger.debug("L1 hit");
3645
+ }
3646
+ } else {
3647
+ this.logger.debug("L1 hit");
3648
+ const ra = optRefreshAhead;
3649
+ const xb = optXfetchBeta;
3650
+ if (ra || xb) {
3651
+ const now = l1Hit.fetchedAt ?? Date.now();
3652
+ const remaining = l1Hit.expiresAt - now;
3653
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
3654
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
3655
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
3656
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3657
+ const priority2 = optPriority ?? inferPriority(cacheKey);
3658
+ this.revalidating.add(k);
3659
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
3660
+ this.counters.swrRevalidations++;
3661
+ this.logger.debug(
3662
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
3663
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
3664
+ );
3665
+ }
3017
3666
  }
3018
3667
  }
3668
+ this.counters.l1Hits++;
3669
+ this.opts.onHit?.(cacheKey, "l1");
3670
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
3671
+ span.setAttribute("cache.hit", "l1").end();
3672
+ return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3019
3673
  }
3020
- this.counters.l1Hits++;
3021
- this.opts.onHit?.(cacheKey, "l1");
3022
- if (this.opts.frozen) deepFreeze(l1Hit.value);
3023
- span.setAttribute("cache.hit", "l1").end();
3024
- return l1Hit.value;
3025
3674
  }
3026
3675
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3027
3676
  const swrGraceMs = optSwr * 1e3;
@@ -3029,22 +3678,52 @@ var CacheService = class _CacheService {
3029
3678
  if (!this._redisDisabled) {
3030
3679
  try {
3031
3680
  const client = await this.getRedis();
3032
- const raw = await client.get(k);
3033
- this.cb.onSuccess();
3034
- if (raw) {
3035
- let decrypted;
3036
- if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
3037
- decrypted = await this._workerPool.decrypt(raw);
3038
- } else {
3039
- decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3681
+ if (this.opts.tagStrategy === "generational") {
3682
+ const hashData = await client.hgetall(k);
3683
+ this.cb.onSuccess();
3684
+ if (hashData && hashData.d) {
3685
+ let isStale = false;
3686
+ let storedTagVersions = {};
3687
+ if (hashData.tv) {
3688
+ try {
3689
+ storedTagVersions = JSON.parse(hashData.tv);
3690
+ } catch {
3691
+ }
3692
+ }
3693
+ for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3694
+ const currentVer = await this._getTagVersion(tag);
3695
+ if (currentVer > entryVer) {
3696
+ isStale = true;
3697
+ break;
3698
+ }
3699
+ }
3700
+ if (isStale) {
3701
+ const setAtMs = parseInt(hashData.t, 10) || 0;
3702
+ this._deleteIfStale(k, setAtMs);
3703
+ } else {
3704
+ const parsed = await this._decryptAndDeserialize(hashData.d);
3705
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3706
+ this.counters.l2Hits++;
3707
+ this.opts.onHit?.(cacheKey, "l2");
3708
+ this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3709
+ span.setAttribute("cache.hit", "l2").end();
3710
+ if (this.opts.frozen) deepFreeze(parsed);
3711
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3712
+ }
3713
+ }
3714
+ } else {
3715
+ const raw = await client.get(k);
3716
+ this.cb.onSuccess();
3717
+ if (raw) {
3718
+ const parsed = await this._decryptAndDeserialize(raw);
3719
+ this.l1.set(k, parsed, ttlMs, priority);
3720
+ this.counters.l2Hits++;
3721
+ this.opts.onHit?.(cacheKey, "l2");
3722
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
3723
+ span.setAttribute("cache.hit", "l2").end();
3724
+ if (this.opts.frozen) deepFreeze(parsed);
3725
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3040
3726
  }
3041
- const parsed = JSON.parse(decrypted);
3042
- this.l1.set(k, parsed, ttlMs, priority);
3043
- this.counters.l2Hits++;
3044
- this.opts.onHit?.(cacheKey, "l2");
3045
- this.logger.debug("L2 hit (Redis)", { cacheKey });
3046
- span.setAttribute("cache.hit", "l2").end();
3047
- return parsed;
3048
3727
  }
3049
3728
  } catch (err) {
3050
3729
  this.cb.onFailure();
@@ -3054,18 +3733,33 @@ var CacheService = class _CacheService {
3054
3733
  if (!this._diskDisabled) {
3055
3734
  const diskHit = this.disk.load(k);
3056
3735
  if (diskHit !== null) {
3057
- const promoted = this.l1.importEntries(
3058
- [{ key: k, entry: diskHit }],
3059
- this.opts.forbiddenSnapshotPrefixes
3060
- );
3061
- if (promoted > 0) {
3062
- const l1Check = this.l1.get(k);
3063
- if (l1Check !== null) {
3064
- this.counters.diskHits++;
3065
- this.opts.onHit?.(cacheKey, "disk");
3066
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3067
- span.setAttribute("cache.hit", "disk").end();
3068
- return l1Check.value;
3736
+ let isDiskStale = false;
3737
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3738
+ for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3739
+ const currentVer = await this._getTagVersion(tag);
3740
+ if (currentVer > entryVer) {
3741
+ isDiskStale = true;
3742
+ break;
3743
+ }
3744
+ }
3745
+ }
3746
+ if (isDiskStale) {
3747
+ this.disk.delete(k);
3748
+ } else {
3749
+ const promoted = this.l1.importEntries(
3750
+ [{ key: k, entry: diskHit }],
3751
+ this.opts.forbiddenSnapshotPrefixes
3752
+ );
3753
+ if (promoted > 0) {
3754
+ const l1Check = this.l1.get(k);
3755
+ if (l1Check !== null) {
3756
+ this.counters.diskHits++;
3757
+ this.opts.onHit?.(cacheKey, "disk");
3758
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3759
+ span.setAttribute("cache.hit", "disk").end();
3760
+ if (this.opts.frozen) deepFreeze(l1Check.value);
3761
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
3762
+ }
3069
3763
  }
3070
3764
  }
3071
3765
  }
@@ -3100,19 +3794,37 @@ var CacheService = class _CacheService {
3100
3794
  }
3101
3795
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
3102
3796
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
3103
- this.l1.set(k, data, storeTtl, priority, staleAt, delta);
3104
- if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3797
+ let activeTagVersions;
3798
+ if (optTags?.length) {
3799
+ if (this.opts.tagStrategy === "generational") {
3800
+ activeTagVersions = {};
3801
+ for (const tag of optTags) {
3802
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3803
+ }
3804
+ } else {
3805
+ await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3806
+ }
3807
+ }
3808
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
3105
3809
  if (!this._redisDisabled) {
3106
3810
  try {
3107
3811
  const client = await this.getRedis();
3108
3812
  const serialized = JSON.stringify(data);
3109
- let toStore;
3110
- if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
3111
- toStore = await this._workerPool.encrypt(serialized);
3813
+ const toStore = await this._serializeAndEncrypt(serialized);
3814
+ const ttlSec = Math.ceil(effectiveTtl / 1e3);
3815
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3816
+ const now = Date.now();
3817
+ const tx = client.multi();
3818
+ tx.hset(k, {
3819
+ d: toStore,
3820
+ t: String(now),
3821
+ tv: JSON.stringify(activeTagVersions)
3822
+ });
3823
+ tx.expire(k, ttlSec);
3824
+ await tx.exec();
3112
3825
  } else {
3113
- toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3826
+ await client.setex(k, ttlSec, toStore);
3114
3827
  }
3115
- await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
3116
3828
  this.cb.onSuccess();
3117
3829
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
3118
3830
  } catch {
@@ -3122,7 +3834,8 @@ var CacheService = class _CacheService {
3122
3834
  } else {
3123
3835
  this.logger.debug("Cached L1", { cacheKey });
3124
3836
  }
3125
- return data;
3837
+ if (this.opts.frozen) deepFreeze(data);
3838
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
3126
3839
  } finally {
3127
3840
  this.inflight.delete(k);
3128
3841
  span.end();
@@ -3131,6 +3844,27 @@ var CacheService = class _CacheService {
3131
3844
  this.inflight.set(k, fetchPromise);
3132
3845
  return fetchPromise;
3133
3846
  }
3847
+ /**
3848
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
3849
+ *
3850
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
3851
+ * from `cache-manager` and `keyv`.
3852
+ *
3853
+ * @param cacheKey - Unique cache key.
3854
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
3855
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
3856
+ *
3857
+ * @example
3858
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
3859
+ * ttl: 300,
3860
+ * swr: 60,
3861
+ * tags: ['users'],
3862
+ * });
3863
+ */
3864
+ wrap(cacheKey, fetchFn, options) {
3865
+ const ttl = options?.ttl ?? 300;
3866
+ return this.get(cacheKey, fetchFn, ttl, options);
3867
+ }
3134
3868
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
3135
3869
  try {
3136
3870
  const fetchStart = Date.now();
@@ -3138,18 +3872,34 @@ var CacheService = class _CacheService {
3138
3872
  const delta = Date.now() - fetchStart;
3139
3873
  const staleAt = Date.now() + ttlMs;
3140
3874
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
3141
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
3875
+ let activeTagVersions;
3876
+ const l1Existing = this.l1.get(cacheKey);
3877
+ if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
3878
+ activeTagVersions = {};
3879
+ for (const tag of Object.keys(l1Existing.tagVersions)) {
3880
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3881
+ }
3882
+ }
3883
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
3142
3884
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3143
3885
  try {
3144
3886
  const client = await this.getRedis();
3145
3887
  const s = JSON.stringify(data);
3146
- let stored;
3147
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
3148
- stored = await this._workerPool.encrypt(s);
3888
+ const stored = await this._serializeAndEncrypt(s);
3889
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3890
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3891
+ const now = Date.now();
3892
+ const tx = client.multi();
3893
+ tx.hset(cacheKey, {
3894
+ d: stored,
3895
+ t: String(now),
3896
+ tv: JSON.stringify(activeTagVersions)
3897
+ });
3898
+ tx.expire(cacheKey, ttlSec);
3899
+ await tx.exec();
3149
3900
  } else {
3150
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
3901
+ await client.setex(cacheKey, ttlSec, stored);
3151
3902
  }
3152
- await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
3153
3903
  } catch {
3154
3904
  }
3155
3905
  }
@@ -3174,12 +3924,23 @@ var CacheService = class _CacheService {
3174
3924
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3175
3925
  const span = this._startSpan("tricache.set");
3176
3926
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3177
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3927
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3928
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3178
3929
  const p = priority ?? inferPriority(cacheKey);
3179
3930
  const k = this.nk(cacheKey);
3180
3931
  this.counters.sets++;
3181
- this.l1.set(k, data, ttlMs, p);
3182
- if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
3932
+ let activeTagVersions;
3933
+ if (opts?.tags?.length) {
3934
+ if (this.opts.tagStrategy === "generational") {
3935
+ activeTagVersions = {};
3936
+ for (const tag of opts.tags) {
3937
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3938
+ }
3939
+ } else {
3940
+ await this._registerTags(k, opts.tags, ttlSeconds);
3941
+ }
3942
+ }
3943
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3183
3944
  if (opts?.dependsOn?.length) {
3184
3945
  for (const pattern of opts.dependsOn) {
3185
3946
  const nsPattern = this.nk(pattern);
@@ -3195,13 +3956,21 @@ var CacheService = class _CacheService {
3195
3956
  try {
3196
3957
  const client = await this.getRedis();
3197
3958
  const s = JSON.stringify(data);
3198
- let stored;
3199
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
3200
- stored = await this._workerPool.encrypt(s);
3959
+ const stored = await this._serializeAndEncrypt(s);
3960
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3961
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3962
+ const now = Date.now();
3963
+ const tx = client.multi();
3964
+ tx.hset(k, {
3965
+ d: stored,
3966
+ t: String(now),
3967
+ tv: JSON.stringify(activeTagVersions)
3968
+ });
3969
+ tx.expire(k, ttlSec);
3970
+ await tx.exec();
3201
3971
  } else {
3202
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
3972
+ await client.setex(k, ttlSec, stored);
3203
3973
  }
3204
- await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
3205
3974
  this.cb.onSuccess();
3206
3975
  } catch (err) {
3207
3976
  this.cb.onFailure();
@@ -3310,7 +4079,7 @@ var CacheService = class _CacheService {
3310
4079
  );
3311
4080
  }
3312
4081
  const now = Date.now();
3313
- const ttlMs = (ttlSeconds ?? 60) * 1e3;
4082
+ const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1e3;
3314
4083
  const entry = this._l1Counters.get(k);
3315
4084
  if (entry && entry.expiresAt > now) {
3316
4085
  entry.value++;
@@ -3350,6 +4119,7 @@ var CacheService = class _CacheService {
3350
4119
  if (!this._diskDisabled) this.disk.clear();
3351
4120
  this._l1Counters.clear();
3352
4121
  this.tagIndex.clear();
4122
+ this.tagVersions.clear();
3353
4123
  }
3354
4124
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3355
4125
  try {
@@ -3397,9 +4167,10 @@ var CacheService = class _CacheService {
3397
4167
  * for (const key of cache.keys()) console.log(key);
3398
4168
  */
3399
4169
  *keys() {
3400
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4170
+ const prefix = this._namespace ? this._namespace + ":" : "";
3401
4171
  for (const key of this.l1.liveKeys()) {
3402
- yield prefixLen > 0 ? key.slice(prefixLen) : key;
4172
+ if (prefix && !key.startsWith(prefix)) continue;
4173
+ yield prefix ? key.slice(prefix.length) : key;
3403
4174
  }
3404
4175
  }
3405
4176
  /**
@@ -3410,7 +4181,15 @@ var CacheService = class _CacheService {
3410
4181
  * for (const val of cache.values<User>()) console.log(val.id);
3411
4182
  */
3412
4183
  *values() {
3413
- yield* this.l1.liveValues();
4184
+ const prefix = this._namespace ? this._namespace + ":" : "";
4185
+ if (!prefix) {
4186
+ yield* this.l1.liveValues();
4187
+ } else {
4188
+ for (const [key, entry] of this.l1.liveEntries()) {
4189
+ if (!key.startsWith(prefix)) continue;
4190
+ yield this.l1.resolveValue(entry);
4191
+ }
4192
+ }
3414
4193
  }
3415
4194
  /**
3416
4195
  * Lazily yield every non-expired L1 [key, value] pair.
@@ -3420,10 +4199,10 @@ var CacheService = class _CacheService {
3420
4199
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
3421
4200
  */
3422
4201
  *entries() {
3423
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4202
+ const prefix = this._namespace ? this._namespace + ":" : "";
3424
4203
  for (const [key, entry] of this.l1.liveEntries()) {
3425
- const k = prefixLen > 0 ? key.slice(prefixLen) : key;
3426
- yield [k, this.l1.resolveValue(entry)];
4204
+ if (prefix && !key.startsWith(prefix)) continue;
4205
+ yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry)];
3427
4206
  }
3428
4207
  }
3429
4208
  /**
@@ -3488,6 +4267,63 @@ var CacheService = class _CacheService {
3488
4267
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
3489
4268
  return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
3490
4269
  }
4270
+ /**
4271
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
4272
+ * Returns the cached value if found and valid, or `null` if absent / expired.
4273
+ * Does not write dummy entries on misses or trigger side-effects.
4274
+ *
4275
+ * @example
4276
+ * const val = await cache.peek<User>('user:123');
4277
+ */
4278
+ async peek(cacheKey) {
4279
+ const k = this.nk(cacheKey);
4280
+ const l1Hit = this.l1.get(k);
4281
+ if (l1Hit !== null) {
4282
+ this.counters.gets++;
4283
+ this.counters.l1Hits++;
4284
+ const val = l1Hit.value;
4285
+ if (this.opts.frozen) deepFreeze(val);
4286
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4287
+ }
4288
+ if (!this._diskDisabled) {
4289
+ const diskHit = this.disk.load(k);
4290
+ if (diskHit !== null) {
4291
+ const promoted = this.l1.importEntries(
4292
+ [{ key: k, entry: diskHit }],
4293
+ this.opts.forbiddenSnapshotPrefixes
4294
+ );
4295
+ if (promoted > 0) {
4296
+ const l1Check = this.l1.get(k);
4297
+ if (l1Check !== null) {
4298
+ this.counters.gets++;
4299
+ this.counters.diskHits++;
4300
+ const val = l1Check.value;
4301
+ if (this.opts.frozen) deepFreeze(val);
4302
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4303
+ }
4304
+ }
4305
+ }
4306
+ }
4307
+ if (!this._redisDisabled && !this.cb.isOpen) {
4308
+ try {
4309
+ const client = await this.getRedis();
4310
+ const raw = await client.get(k);
4311
+ if (raw !== null) {
4312
+ const parsed = await this._decryptAndDeserialize(raw);
4313
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
4314
+ this.counters.gets++;
4315
+ this.counters.l2Hits++;
4316
+ this.cb.onSuccess();
4317
+ if (this.opts.frozen) deepFreeze(parsed);
4318
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
4319
+ }
4320
+ } catch (err) {
4321
+ this.cb.onFailure();
4322
+ this.logger.debug("peek: Redis read failed", { cacheKey, error: err.message });
4323
+ }
4324
+ }
4325
+ return null;
4326
+ }
3491
4327
  /**
3492
4328
  * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
3493
4329
  * Preserves input ordering. Uses inflight coalescing per key.
@@ -3498,7 +4334,7 @@ var CacheService = class _CacheService {
3498
4334
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
3499
4335
  */
3500
4336
  async mget(keys, fetchFn, ttl = 300, priority) {
3501
- const result = new Array(keys.length);
4337
+ const result = Array.from({ length: keys.length });
3502
4338
  const missIndexes = [];
3503
4339
  const missKeys = [];
3504
4340
  for (let i = 0; i < keys.length; i++) {
@@ -3525,13 +4361,7 @@ var CacheService = class _CacheService {
3525
4361
  const raw = raws[j] ? raws[j][1] : null;
3526
4362
  const idx = missIndexes[j];
3527
4363
  if (raw) {
3528
- let parsed;
3529
- if (this.enc.isEnabled) {
3530
- const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
3531
- parsed = JSON.parse(decrypted);
3532
- } else {
3533
- parsed = JSON.parse(raw);
3534
- }
4364
+ const parsed = await this._decryptAndDeserialize(raw);
3535
4365
  const k = nsKeys[j];
3536
4366
  const p = priority ?? inferPriority(missKeys[j]);
3537
4367
  this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
@@ -3663,12 +4493,10 @@ var CacheService = class _CacheService {
3663
4493
  const [err, raw] = results[i];
3664
4494
  if (err || raw == null) continue;
3665
4495
  try {
3666
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3667
- const parsed = JSON.parse(decrypted);
4496
+ const parsed = await this._decryptAndDeserialize(raw);
3668
4497
  const remainingMs = 10 * 60 * 1e3;
3669
4498
  this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3670
4499
  loaded++;
3671
- ;
3672
4500
  } catch {
3673
4501
  }
3674
4502
  }
@@ -3694,6 +4522,25 @@ var CacheService = class _CacheService {
3694
4522
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3695
4523
  */
3696
4524
  async invalidateTag(tag) {
4525
+ if (this.opts.tagStrategy === "generational") {
4526
+ let newVer = 1;
4527
+ if (!this._redisDisabled) {
4528
+ try {
4529
+ const client = await this.getRedis();
4530
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
4531
+ } catch (err) {
4532
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4533
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4534
+ newVer = current + 1;
4535
+ }
4536
+ } else {
4537
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4538
+ newVer = current + 1;
4539
+ }
4540
+ this._setLocalTagVersion(tag, newVer, Date.now());
4541
+ void this.publishInvalidation("tag_incr", tag, newVer);
4542
+ return;
4543
+ }
3697
4544
  const tagKey = this.nk(`_tag_:${tag}`);
3698
4545
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
3699
4546
  for (const k of members) {
@@ -3734,6 +4581,32 @@ var CacheService = class _CacheService {
3734
4581
  await this.invalidateTag(tags[0]);
3735
4582
  return;
3736
4583
  }
4584
+ if (this.opts.tagStrategy === "generational") {
4585
+ const now = Date.now();
4586
+ if (!this._redisDisabled) {
4587
+ try {
4588
+ const client = await this.getRedis();
4589
+ const pl = client.pipeline();
4590
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
4591
+ const results = await pl.exec();
4592
+ for (let i = 0; i < tags.length; i++) {
4593
+ const [err, newVer] = results[i] ?? [null, null];
4594
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4595
+ this._setLocalTagVersion(tags[i], ver, now);
4596
+ void this.publishInvalidation("tag_incr", tags[i], ver);
4597
+ }
4598
+ return;
4599
+ } catch (err) {
4600
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
4601
+ }
4602
+ }
4603
+ for (const tag of tags) {
4604
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4605
+ this._setLocalTagVersion(tag, ver, now);
4606
+ void this.publishInvalidation("tag_incr", tag, ver);
4607
+ }
4608
+ return;
4609
+ }
3737
4610
  const tagKeys = [];
3738
4611
  const allMembers = /* @__PURE__ */ new Set();
3739
4612
  for (const tag of tags) {
@@ -3768,6 +4641,12 @@ var CacheService = class _CacheService {
3768
4641
  }
3769
4642
  }
3770
4643
  }
4644
+ /**
4645
+ * Get the current generational tag version for a tag (synced with Redis when due).
4646
+ */
4647
+ async getTagVersion(tag) {
4648
+ return this._getTagVersion(tag);
4649
+ }
3771
4650
  /**
3772
4651
  * Measure L1 / disk / Redis latency.
3773
4652
  * Useful for health checks and dashboards.
@@ -3866,6 +4745,136 @@ var CacheService = class _CacheService {
3866
4745
  this.counters.sets++;
3867
4746
  return true;
3868
4747
  }
4748
+ // ── Distributed / In-Process Mutex Lock ───────────────────────────────────
4749
+ /**
4750
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
4751
+ * execute `fn`, and automatically release the lock on completion or error.
4752
+ *
4753
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
4754
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
4755
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
4756
+ *
4757
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
4758
+ * @param fn Task to run exclusively while holding the lock.
4759
+ * @param options TTL, acquire timeout, and retry polling intervals.
4760
+ */
4761
+ async lock(resourceKey, fn, options) {
4762
+ const ttlSeconds = Math.max(1, options?.ttl ?? 30);
4763
+ const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
4764
+ const retryInterval = Math.max(10, options?.retryInterval ?? 100);
4765
+ const lockKey = this.nk(`lock:${resourceKey}`);
4766
+ const token = import_crypto3.default.randomUUID();
4767
+ const deadline = Date.now() + acquireTimeout;
4768
+ let acquired = false;
4769
+ if (!this._redisDisabled) {
4770
+ let client = null;
4771
+ try {
4772
+ client = await this.getRedis();
4773
+ while (Date.now() <= deadline) {
4774
+ const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4775
+ if (res === "OK") {
4776
+ acquired = true;
4777
+ break;
4778
+ }
4779
+ const remaining = deadline - Date.now();
4780
+ if (remaining <= 0) break;
4781
+ await new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)));
4782
+ }
4783
+ if (!acquired) {
4784
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4785
+ }
4786
+ } catch (err) {
4787
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4788
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4789
+ resourceKey,
4790
+ error: err.message
4791
+ });
4792
+ client = null;
4793
+ }
4794
+ if (client !== null && acquired) {
4795
+ try {
4796
+ return await fn();
4797
+ } finally {
4798
+ try {
4799
+ const LUA_RELEASE_LOCK = `
4800
+ if redis.call("get", KEYS[1]) == ARGV[1] then
4801
+ return redis.call("del", KEYS[1])
4802
+ else
4803
+ return 0
4804
+ end
4805
+ `;
4806
+ await client.eval(LUA_RELEASE_LOCK, 1, lockKey, token);
4807
+ } catch {
4808
+ }
4809
+ }
4810
+ }
4811
+ }
4812
+ let unlock = () => {
4813
+ };
4814
+ const lockPromise = new Promise((resolve) => {
4815
+ unlock = resolve;
4816
+ });
4817
+ while (Date.now() <= deadline) {
4818
+ const existing = this._localLocks.get(lockKey);
4819
+ if (!existing) {
4820
+ this._localLocks.set(lockKey, lockPromise);
4821
+ acquired = true;
4822
+ break;
4823
+ }
4824
+ const remaining = deadline - Date.now();
4825
+ if (remaining <= 0) break;
4826
+ await Promise.race([
4827
+ existing,
4828
+ new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)))
4829
+ ]);
4830
+ }
4831
+ if (!acquired) {
4832
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4833
+ }
4834
+ try {
4835
+ return await fn();
4836
+ } finally {
4837
+ unlock();
4838
+ if (this._localLocks.get(lockKey) === lockPromise) {
4839
+ this._localLocks.delete(lockKey);
4840
+ }
4841
+ }
4842
+ }
4843
+ // ── OpenTelemetry Metrics Integration ──────────────────────────────────────
4844
+ _initOtelMetrics(meter) {
4845
+ try {
4846
+ this._otelMetrics.gets = meter.createCounter("tricache.gets.total", { description: "Total cache get operations" });
4847
+ this._otelMetrics.l1Hits = meter.createCounter("tricache.l1.hits", { description: "L1 RAM cache hits" });
4848
+ this._otelMetrics.l2Hits = meter.createCounter("tricache.l2.hits", { description: "L2 Redis cache hits" });
4849
+ this._otelMetrics.diskHits = meter.createCounter("tricache.disk.hits", { description: "L1.5 disk cache hits" });
4850
+ this._otelMetrics.fetches = meter.createCounter("tricache.fetches", { description: "Cache miss fetch calls" });
4851
+ this._otelMetrics.stampedes = meter.createCounter("tricache.stampedes.prevented", { description: "Coalesced duplicate inflight requests" });
4852
+ this._otelMetrics.sets = meter.createCounter("tricache.sets.total", { description: "Total set operations" });
4853
+ this._otelMetrics.deletes = meter.createCounter("tricache.deletes.total", { description: "Total delete operations" });
4854
+ this._otelMetrics.swrRevalidations = meter.createCounter("tricache.swr.revalidations", { description: "SWR background revalidations" });
4855
+ const gL1Entries = meter.createObservableGauge("tricache.l1.entries", { description: "Current L1 entry count" });
4856
+ const gL1Bytes = meter.createObservableGauge("tricache.l1.bytes", { description: "Current L1 memory usage in bytes" });
4857
+ const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
4858
+ const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
4859
+ const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
4860
+ meter.addBatchObservableCallback((observableResult) => {
4861
+ const stats = this.stats();
4862
+ const l1 = stats.l1;
4863
+ const disk = stats.disk;
4864
+ const checks = this.counters.bloomChecks;
4865
+ const fps = this.counters.bloomFalsePositives;
4866
+ const fpr = checks > 0 ? fps / checks : 0;
4867
+ const attrs = this._namespace ? { namespace: this._namespace } : void 0;
4868
+ observableResult.observe(gL1Entries, l1.entries, attrs);
4869
+ observableResult.observe(gL1Bytes, l1.sizeBytes, attrs);
4870
+ observableResult.observe(gDiskFiles, disk.files, attrs);
4871
+ observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
4872
+ observableResult.observe(gBloomFpr, fpr, attrs);
4873
+ }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
4874
+ } catch (err) {
4875
+ this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
4876
+ }
4877
+ }
3869
4878
  // ── Hot key introspection ─────────────────────────────────────────────
3870
4879
  /**
3871
4880
  * Return the top-N live L1 keys by historical access frequency.
@@ -3896,18 +4905,20 @@ var CacheService = class _CacheService {
3896
4905
  */
3897
4906
  _matchesGlob(key, pattern) {
3898
4907
  if (!pattern.includes("*")) return key === pattern;
3899
- const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
3900
- return re.test(key);
4908
+ return getGlobRegex(pattern).test(key);
3901
4909
  }
3902
4910
  /**
3903
4911
  * When an exact key `deletedKey` is removed, cascade to every dependent key
3904
4912
  * that was registered via `dependsOn` and whose source pattern matches.
4913
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
3905
4914
  */
3906
- _cascadeDependencies(deletedKey) {
4915
+ _cascadeDependencies(deletedKey, visited = /* @__PURE__ */ new Set()) {
4916
+ if (visited.has(deletedKey)) return;
4917
+ visited.add(deletedKey);
3907
4918
  for (const [pattern, dependents] of this.dependencyIndex) {
3908
4919
  if (!this._matchesGlob(deletedKey, pattern)) continue;
3909
4920
  for (const dep of dependents) {
3910
- if (dep === deletedKey) continue;
4921
+ if (visited.has(dep)) continue;
3911
4922
  this.l1.delete(dep);
3912
4923
  if (!this._diskDisabled) this.disk.delete(dep);
3913
4924
  void this.publishInvalidation("del", dep);
@@ -3915,6 +4926,7 @@ var CacheService = class _CacheService {
3915
4926
  trigger: deletedKey.slice(0, 60),
3916
4927
  dependent: dep.slice(0, 60)
3917
4928
  });
4929
+ this._cascadeDependencies(dep, visited);
3918
4930
  }
3919
4931
  }
3920
4932
  }
@@ -3958,9 +4970,13 @@ var CacheService = class _CacheService {
3958
4970
  },
3959
4971
  backplane: {
3960
4972
  enabled: this.opts.invalidationBackplane && !this._redisDisabled,
4973
+ mode: this.opts.backplaneMode,
3961
4974
  sent: c.invSent,
3962
4975
  received: c.invReceived,
3963
- skipped: c.invSkipped
4976
+ skipped: c.invSkipped,
4977
+ streamEntriesReceived: c.streamEntriesReceived,
4978
+ streamReplays: c.streamReplays,
4979
+ streamGaps: c.streamGaps
3964
4980
  },
3965
4981
  l2CircuitBreaker: {
3966
4982
  state: this.cb.currentState
@@ -4054,8 +5070,21 @@ var CacheService = class _CacheService {
4054
5070
  return lines.join("\n");
4055
5071
  }
4056
5072
  // ── Lifecycle ────────────────────────────────────────────────────────────
5073
+ /**
5074
+ * Dynamically rotate the active encryption key at runtime without restarting.
5075
+ * Installs the new key as primary for all subsequent writes, while preserving
5076
+ * the previous key for seamless fallback decryption of existing cache entries.
5077
+ */
5078
+ async rotateEncryptionKey(newKeyBase64, newMode) {
5079
+ this.enc.rotateKey(newKeyBase64, newMode);
5080
+ if (this._workerPool) {
5081
+ await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
5082
+ }
5083
+ this.logger.info("tricache: encryption key rotated dynamically", { mode: this.enc.mode });
5084
+ }
4057
5085
  /** Close Redis connections and stop all background timers. */
4058
5086
  async destroy() {
5087
+ this._destroyed = true;
4059
5088
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4060
5089
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4061
5090
  if (this.oomInterval) clearInterval(this.oomInterval);
@@ -4071,11 +5100,18 @@ var CacheService = class _CacheService {
4071
5100
  }
4072
5101
  if (this.subClient) {
4073
5102
  try {
4074
- await this.subClient.quit();
5103
+ this.subClient.disconnect();
4075
5104
  } catch {
4076
5105
  }
4077
5106
  this.subClient = null;
4078
5107
  }
5108
+ if (this.streamClient) {
5109
+ try {
5110
+ this.streamClient.disconnect();
5111
+ } catch {
5112
+ }
5113
+ this.streamClient = null;
5114
+ }
4079
5115
  if (this.redis) {
4080
5116
  try {
4081
5117
  await this.redis.disconnect();