tricache 0.6.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +500 -24
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1181 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3697
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +64 -15
  33. package/src/cache-service.ts +1005 -192
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -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 +244 -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 +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  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 ?? ""),
@@ -266,8 +355,10 @@ var CacheEncryption = class {
266
355
  }
267
356
  return out;
268
357
  }
269
- constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
270
- this._mode = mode;
358
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
359
+ const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
360
+ const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
361
+ this._mode = resolvedMode;
271
362
  if (!keyBase64) {
272
363
  if (process.env.NODE_ENV === "production") {
273
364
  logger.warn(
@@ -279,7 +370,7 @@ var CacheEncryption = class {
279
370
  }
280
371
  try {
281
372
  const buf = Buffer.from(keyBase64, "base64");
282
- const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
373
+ const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
283
374
  if (requiredLen > 0 && buf.length !== requiredLen) {
284
375
  throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
285
376
  }
@@ -330,6 +421,9 @@ var CacheEncryption = class {
330
421
  get isEnabled() {
331
422
  return this._key !== null;
332
423
  }
424
+ get mode() {
425
+ return this._mode;
426
+ }
333
427
  /**
334
428
  * Snapshot the key material needed to spin up an off-main-thread worker pool.
335
429
  * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
@@ -344,6 +438,43 @@ var CacheEncryption = class {
344
438
  prevMode: this._prevMode
345
439
  };
346
440
  }
441
+ /**
442
+ * Rotate the active encryption key dynamically at runtime.
443
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
444
+ * fallback decryption of existing cache entries in L2/Disk, and installs
445
+ * the new key as primary for all subsequent writes.
446
+ */
447
+ rotateKey(newKeyBase64, newMode) {
448
+ if (!newKeyBase64) {
449
+ throw new Error("rotateKey requires a valid non-empty base64 key");
450
+ }
451
+ const mode = newMode ?? this._mode;
452
+ const buf = Buffer.from(newKeyBase64, "base64");
453
+ const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
454
+ if (requiredLen > 0 && buf.length !== requiredLen) {
455
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
456
+ }
457
+ if (buf.length < 1) {
458
+ throw new Error("XOR key must be at least 1 byte");
459
+ }
460
+ let newKeyObj = null;
461
+ if (mode !== "xor") {
462
+ newKeyObj = (0, import_crypto.createSecretKey)(buf);
463
+ const _wc = (0, import_crypto.createCipheriv)(
464
+ mode,
465
+ newKeyObj,
466
+ Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
467
+ );
468
+ _wc.update(Buffer.alloc(0));
469
+ _wc.final();
470
+ }
471
+ this._prevKey = this._key;
472
+ this._prevKeyObj = this._keyObj;
473
+ this._prevMode = this._mode;
474
+ this._key = buf;
475
+ this._keyObj = newKeyObj;
476
+ this._mode = mode;
477
+ }
347
478
  // ── String (Redis) ────────────────────────────────────────────────────────
348
479
  /**
349
480
  * Encrypt a string for Redis storage.
@@ -534,6 +665,7 @@ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "b
534
665
  var WasmBloomFilter = class {
535
666
  exports;
536
667
  mem;
668
+ stagingTarget;
537
669
  encoder = new TextEncoder();
538
670
  numBits = 1e5;
539
671
  /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
@@ -544,13 +676,13 @@ var WasmBloomFilter = class {
544
676
  const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
545
677
  this.exports = instance.exports;
546
678
  this.mem = new Uint8Array(this.exports.memory.buffer);
679
+ this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
547
680
  const k = 7, p = 0.01;
548
681
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
549
682
  }
550
683
  writeKey(key) {
551
684
  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;
685
+ return this.encoder.encodeInto(key, this.stagingTarget).written;
554
686
  }
555
687
  add(key) {
556
688
  const len = this.writeKey(key);
@@ -590,7 +722,7 @@ var WasmBloomFilter = class {
590
722
  };
591
723
 
592
724
  // src/smart-memory-cache.ts
593
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
725
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
594
726
  var LARGE_VALUE_BYTES = 16384;
595
727
  var EVICTION_BATCH_PERCENT = 0.2;
596
728
  var EVICTION_SAMPLE = 16;
@@ -999,9 +1131,11 @@ var SmartMemoryCache = class {
999
1131
  _hit.ttlMs = entry.ttlMs;
1000
1132
  _hit.delta = entry.delta;
1001
1133
  _hit.fetchedAt = now;
1134
+ _hit.tagVersions = entry.tagVersions;
1135
+ _hit.setAt = entry.setAt;
1002
1136
  return _hit;
1003
1137
  }
1004
- set(key, data, ttlMs, priority = 2, staleAt, delta) {
1138
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1005
1139
  const packed = (0, import_msgpackr.pack)(data);
1006
1140
  const size = packed.byteLength;
1007
1141
  this.compressions++;
@@ -1022,7 +1156,7 @@ var SmartMemoryCache = class {
1022
1156
  this.ensureCapacity(cat, size);
1023
1157
  const now = Date.now();
1024
1158
  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 });
1159
+ 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
1160
  if (!existingEntry) this.bloom.add(key);
1027
1161
  this.maybeRebuildBloom();
1028
1162
  this.totalSize += size;
@@ -1211,6 +1345,22 @@ var SmartMemoryCache = class {
1211
1345
  }
1212
1346
  return evicted;
1213
1347
  }
1348
+ /**
1349
+ * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
1350
+ * Used for concurrency-safe compare-and-delete on stale generational reads,
1351
+ * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
1352
+ */
1353
+ deleteIfSetBefore(key, cutoffMs) {
1354
+ const entry = this.cache.get(key);
1355
+ if (!entry) return false;
1356
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
1357
+ if (setAt <= cutoffMs) {
1358
+ const deleted = this._delete(key, "manual");
1359
+ if (deleted) this.maybeRebuildBloom();
1360
+ return deleted;
1361
+ }
1362
+ return false;
1363
+ }
1214
1364
  exportEntries(forbiddenPrefixes) {
1215
1365
  const now = Date.now();
1216
1366
  const out = [];
@@ -1414,6 +1564,64 @@ var import_fs2 = __toESM(require("fs"), 1);
1414
1564
  var import_path2 = __toESM(require("path"), 1);
1415
1565
  var import_crypto2 = __toESM(require("crypto"), 1);
1416
1566
  var import_msgpackr2 = require("msgpackr");
1567
+
1568
+ // src/compression.ts
1569
+ var import_zlib = __toESM(require("zlib"), 1);
1570
+ var PREFIX_COMPRESSED = "cmp:v1:";
1571
+ var PREFIX_ENC_COMPRESSED = "ecp:v1:";
1572
+ var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
1573
+ function isCompressed(buf) {
1574
+ return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1575
+ }
1576
+ function compressBuffer(buf, algorithm) {
1577
+ if (algorithm === "brotli") {
1578
+ return import_zlib.default.brotliCompressSync(buf, {
1579
+ params: {
1580
+ [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4
1581
+ // Fast level 4 compression
1582
+ }
1583
+ });
1584
+ }
1585
+ if (algorithm === "gzip") {
1586
+ return import_zlib.default.gzipSync(buf, { level: 6 });
1587
+ }
1588
+ return buf;
1589
+ }
1590
+ function decompressBuffer(buf, algorithm = "brotli") {
1591
+ if (algorithm === "gzip") {
1592
+ try {
1593
+ return import_zlib.default.gunzipSync(buf);
1594
+ } catch {
1595
+ try {
1596
+ return import_zlib.default.brotliDecompressSync(buf);
1597
+ } catch {
1598
+ return buf;
1599
+ }
1600
+ }
1601
+ }
1602
+ try {
1603
+ return import_zlib.default.brotliDecompressSync(buf);
1604
+ } catch {
1605
+ try {
1606
+ return import_zlib.default.gunzipSync(buf);
1607
+ } catch {
1608
+ return buf;
1609
+ }
1610
+ }
1611
+ }
1612
+ function compressWithHeader(buf, algorithm) {
1613
+ if (algorithm === "none") return buf;
1614
+ const compressed = compressBuffer(buf, algorithm);
1615
+ return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1616
+ }
1617
+ function decompressWithHeader(buf, algorithm = "brotli") {
1618
+ if (isCompressed(buf)) {
1619
+ return decompressBuffer(buf.subarray(4), algorithm);
1620
+ }
1621
+ return buf;
1622
+ }
1623
+
1624
+ // src/disk-tier.ts
1417
1625
  var _SqliteDB = null;
1418
1626
  try {
1419
1627
  const sqlite = process.getBuiltinModule("node:sqlite");
@@ -1671,26 +1879,46 @@ var DiskTier = class {
1671
1879
  };
1672
1880
  const packed = (0, import_msgpackr2.pack)(payload);
1673
1881
  if (packed.length > this.opts.entryMaxBytes) return;
1882
+ let toEncrypt = packed;
1883
+ if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
1884
+ toEncrypt = compressWithHeader(packed, this.opts.compression);
1885
+ }
1674
1886
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1675
1887
  DISK_MAGIC_V2.copy(header, 0);
1676
1888
  header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1677
- final = Buffer.concat([header, this.encryptV2(packed)]);
1889
+ final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
1678
1890
  } catch (err) {
1679
1891
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1680
1892
  return;
1681
1893
  }
1682
1894
  const hash = this.keyToHash(key);
1683
1895
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
1896
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1684
1897
  this.diskUsageBytes += final.length;
1685
1898
  this.fileCount++;
1686
1899
  try {
1687
1900
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
1688
- await import_fs2.default.promises.writeFile(filePath, final, { mode: 384 });
1901
+ await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
1902
+ try {
1903
+ await import_fs2.default.promises.rename(tmpPath, filePath);
1904
+ } catch (renameErr) {
1905
+ const code = renameErr?.code;
1906
+ if (code === "EBUSY" || code === "EPERM") {
1907
+ await new Promise((resolve) => setTimeout(resolve, 5));
1908
+ await import_fs2.default.promises.rename(tmpPath, filePath);
1909
+ } else {
1910
+ throw renameErr;
1911
+ }
1912
+ }
1689
1913
  if (this._db) {
1690
1914
  this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1691
1915
  }
1692
1916
  this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1693
1917
  } catch (err) {
1918
+ try {
1919
+ await import_fs2.default.promises.unlink(tmpPath);
1920
+ } catch {
1921
+ }
1694
1922
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1695
1923
  this.fileCount = Math.max(0, this.fileCount - 1);
1696
1924
  if (this._db) try {
@@ -1774,7 +2002,8 @@ var DiskTier = class {
1774
2002
  return null;
1775
2003
  }
1776
2004
  }
1777
- const payload = (0, import_msgpackr2.unpack)(decrypted);
2005
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
2006
+ const payload = (0, import_msgpackr2.unpack)(uncompressed);
1778
2007
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1779
2008
  if (payload.entry.expiresAt <= Date.now()) return null;
1780
2009
  const entry = payload.entry;
@@ -1833,6 +2062,17 @@ var DiskTier = class {
1833
2062
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1834
2063
  for (const filePath of this.walkCacheFiles()) {
1835
2064
  const filename = import_path2.default.basename(filePath);
2065
+ if (filename.endsWith(".tmp")) {
2066
+ try {
2067
+ const stat = import_fs2.default.statSync(filePath);
2068
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
2069
+ import_fs2.default.unlinkSync(filePath);
2070
+ purged++;
2071
+ }
2072
+ } catch {
2073
+ }
2074
+ continue;
2075
+ }
1836
2076
  if (filename.length === 77 && filename[64] === "_") {
1837
2077
  const expiresAt = parseInt(filename.slice(65), 16);
1838
2078
  if (expiresAt <= now) {
@@ -1942,6 +2182,17 @@ var DiskTier = class {
1942
2182
  return expired.length;
1943
2183
  }
1944
2184
  for (const file of orphanFiles) {
2185
+ if (file.endsWith(".tmp")) {
2186
+ const fp = import_path2.default.join(orphanBucketP, file);
2187
+ try {
2188
+ const stat = import_fs2.default.statSync(fp);
2189
+ if (now2 - stat.mtimeMs > 5 * 60 * 1e3) {
2190
+ import_fs2.default.unlinkSync(fp);
2191
+ }
2192
+ } catch {
2193
+ }
2194
+ continue;
2195
+ }
1945
2196
  if (file.length === 77 && file[64] === "_") {
1946
2197
  const expiresAt = parseInt(file.slice(65), 16);
1947
2198
  if (expiresAt <= now2) {
@@ -1971,6 +2222,18 @@ var DiskTier = class {
1971
2222
  let purged = 0;
1972
2223
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1973
2224
  for (const file of files) {
2225
+ if (file.endsWith(".tmp")) {
2226
+ const fp = import_path2.default.join(bucketPath, file);
2227
+ try {
2228
+ const stat = import_fs2.default.statSync(fp);
2229
+ if (now - stat.mtimeMs > 5 * 60 * 1e3) {
2230
+ import_fs2.default.unlinkSync(fp);
2231
+ purged++;
2232
+ }
2233
+ } catch {
2234
+ }
2235
+ continue;
2236
+ }
1974
2237
  if (file.length === 77 && file[64] === "_") {
1975
2238
  const expiresAt = parseInt(file.slice(65), 16);
1976
2239
  if (expiresAt <= now) {
@@ -2089,6 +2352,13 @@ var DiskTier = class {
2089
2352
  };
2090
2353
 
2091
2354
  // src/cache-service.ts
2355
+ var LUA_COMPARE_AND_DELETE = `
2356
+ local currentTs = redis.call('HGET', KEYS[1], 't')
2357
+ if currentTs and currentTs == ARGV[1] then
2358
+ return redis.call('DEL', KEYS[1])
2359
+ end
2360
+ return 0
2361
+ `;
2092
2362
  var SNAPSHOT_VERSION = 1;
2093
2363
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
2094
2364
  var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
@@ -2096,6 +2366,25 @@ var DEFAULT_CATEGORY_LIMITS = {
2096
2366
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
2097
2367
  };
2098
2368
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
2369
+ var DEFAULT_COUNTER_TTL_SECONDS = 60;
2370
+ var GLOB_REGEX_CACHE_MAX = 256;
2371
+ var globRegexCache = /* @__PURE__ */ new Map();
2372
+ function getGlobRegex(pattern) {
2373
+ let re = globRegexCache.get(pattern);
2374
+ if (re) {
2375
+ globRegexCache.delete(pattern);
2376
+ globRegexCache.set(pattern, re);
2377
+ return re;
2378
+ }
2379
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
2380
+ re = new RegExp("^" + escaped + "$");
2381
+ if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
2382
+ const oldestKey = globRegexCache.keys().next().value;
2383
+ if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
2384
+ }
2385
+ globRegexCache.set(pattern, re);
2386
+ return re;
2387
+ }
2099
2388
  var L2CircuitBreaker = class {
2100
2389
  constructor(threshold, cooldownMs) {
2101
2390
  this.threshold = threshold;
@@ -2276,6 +2565,8 @@ var CacheService = class _CacheService {
2276
2565
  _l1Counters = /* @__PURE__ */ new Map();
2277
2566
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
2278
2567
  tagIndex = /* @__PURE__ */ new Map();
2568
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
2569
+ tagVersions = /* @__PURE__ */ new Map();
2279
2570
  /**
2280
2571
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
2281
2572
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -2284,6 +2575,10 @@ var CacheService = class _CacheService {
2284
2575
  redis = null;
2285
2576
  redisConnecting = null;
2286
2577
  cb;
2578
+ /** In-process mutex lock map for single-process environments or Redis outages. */
2579
+ _localLocks = /* @__PURE__ */ new Map();
2580
+ /** Active OpenTelemetry monotonic counters. */
2581
+ _otelMetrics = {};
2287
2582
  snapshotLoaded = false;
2288
2583
  _readyPromise = Promise.resolve();
2289
2584
  cleanupInterval = null;
@@ -2294,7 +2589,11 @@ var CacheService = class _CacheService {
2294
2589
  latencyTracker = null;
2295
2590
  instanceId;
2296
2591
  backplaneChannel;
2592
+ backplaneStreamKey;
2297
2593
  subClient = null;
2594
+ streamClient = null;
2595
+ _lastStreamId = "$";
2596
+ _destroyed = false;
2298
2597
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2299
2598
  _subDisconnectedAt = null;
2300
2599
  counters = {
@@ -2310,13 +2609,18 @@ var CacheService = class _CacheService {
2310
2609
  invSent: 0,
2311
2610
  invReceived: 0,
2312
2611
  invSkipped: 0,
2612
+ streamEntriesReceived: 0,
2613
+ streamReplays: 0,
2614
+ streamGaps: 0,
2313
2615
  oomEvictions: 0,
2314
2616
  oomLastAt: null,
2315
2617
  /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
2316
2618
  counterErrors: 0,
2317
2619
  /** Times a later `create(ns)` call passed options differing from the live singleton. */
2318
2620
  singletonDivergences: 0,
2319
- startedAt: Date.now()
2621
+ startedAt: Date.now(),
2622
+ bloomChecks: 0,
2623
+ bloomFalsePositives: 0
2320
2624
  };
2321
2625
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2322
2626
  _incrementFallbackWarned = false;
@@ -2340,7 +2644,7 @@ var CacheService = class _CacheService {
2340
2644
  logger,
2341
2645
  l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
2342
2646
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2343
- categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits ?? {} },
2647
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2344
2648
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2345
2649
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2346
2650
  // two instances with different namespaces never share cache files.
@@ -2373,6 +2677,7 @@ var CacheService = class _CacheService {
2373
2677
  l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
2374
2678
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
2375
2679
  tracer: options.tracer,
2680
+ meter: options.meter,
2376
2681
  notFoundTtl: options.notFoundTtl ?? 0,
2377
2682
  warmKeys: options.warmKeys,
2378
2683
  onHit: options.onHit,
@@ -2391,8 +2696,19 @@ var CacheService = class _CacheService {
2391
2696
  disableDisk: options.disableDisk ?? false,
2392
2697
  redisClusterNodes: options.redisClusterNodes,
2393
2698
  redisSentinel: options.redisSentinel,
2699
+ redisProtocol: options.redisProtocol,
2700
+ useShardedPubSub: options.useShardedPubSub ?? false,
2701
+ compression: options.compression ?? "none",
2702
+ compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
2394
2703
  strictSingleton: options.strictSingleton ?? false,
2395
- failClosed: options.failClosed ?? false
2704
+ failClosed: options.failClosed ?? false,
2705
+ tagStrategy: options.tagStrategy ?? "set",
2706
+ tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
2707
+ cloneStrategy: options.cloneStrategy ?? "none",
2708
+ backplaneMode: options.backplaneMode ?? "pubsub",
2709
+ backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2710
+ backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2711
+ backplaneStreamKey: options.backplaneStreamKey
2396
2712
  };
2397
2713
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2398
2714
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -2422,6 +2738,8 @@ var CacheService = class _CacheService {
2422
2738
  entryMaxBytes: this.opts.diskEntryMaxBytes,
2423
2739
  forbiddenPrefixes,
2424
2740
  encryption: this.enc.isEnabled ? this.enc : null,
2741
+ compression: this.opts.compression,
2742
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2425
2743
  logger
2426
2744
  });
2427
2745
  this._namespace = ns;
@@ -2450,7 +2768,7 @@ var CacheService = class _CacheService {
2450
2768
  };
2451
2769
  process.once("SIGTERM", this._shutdownHandler);
2452
2770
  process.once("SIGINT", this._shutdownHandler);
2453
- if (this.opts.workerThreads && this.enc.isEnabled) {
2771
+ if (this.opts.workerThreads) {
2454
2772
  try {
2455
2773
  const encRef = this.enc.toWorkerInit();
2456
2774
  this._workerPool = new WorkerPool({
@@ -2458,6 +2776,8 @@ var CacheService = class _CacheService {
2458
2776
  mode: encRef.mode,
2459
2777
  prevKeyBase64: encRef.prevKeyBase64,
2460
2778
  prevMode: encRef.prevMode,
2779
+ compression: this.opts.compression,
2780
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
2461
2781
  size: this.opts.workerPoolSize || void 0
2462
2782
  });
2463
2783
  if (this._workerPool.isAvailable) {
@@ -2513,10 +2833,30 @@ var CacheService = class _CacheService {
2513
2833
  }
2514
2834
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
2515
2835
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2836
+ this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2516
2837
  this.initBackplane();
2517
2838
  if (this.opts.warmKeys) {
2518
2839
  this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
2519
2840
  }
2841
+ if (this.opts.meter) {
2842
+ this._initOtelMetrics(this.opts.meter);
2843
+ const otel = this._otelMetrics;
2844
+ const nsAttr = this._namespace ? { namespace: this._namespace } : void 0;
2845
+ const targetCounters = this.counters;
2846
+ this.counters = new Proxy(targetCounters, {
2847
+ set(target, prop, value, receiver) {
2848
+ const oldVal = target[prop];
2849
+ const ok = Reflect.set(target, prop, value, receiver);
2850
+ if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
2851
+ const diff = value - oldVal;
2852
+ if (diff > 0 && otel[prop]) {
2853
+ otel[prop].add(diff, nsAttr);
2854
+ }
2855
+ }
2856
+ return ok;
2857
+ }
2858
+ });
2859
+ }
2520
2860
  }
2521
2861
  // ── Singleton factory ─────────────────────────────────────────────────────
2522
2862
  /**
@@ -2656,7 +2996,8 @@ var CacheService = class _CacheService {
2656
2996
  _jitterTtl(ttlMs) {
2657
2997
  const j = this.opts.ttlJitterFactor;
2658
2998
  if (j === 0) return ttlMs;
2659
- return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
2999
+ const rand = import_crypto3.default.randomInt(0, 1e5) / 5e4 - 1;
3000
+ return Math.round(ttlMs * (1 + rand * j));
2660
3001
  }
2661
3002
  /** Shared no-op span for the common case where no tracer is configured.
2662
3003
  * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
@@ -2675,20 +3016,18 @@ var CacheService = class _CacheService {
2675
3016
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
2676
3017
  return _CacheService._nullSpan;
2677
3018
  }
2678
- initBackplane() {
2679
- if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2680
- if (this.subClient) return;
2681
- let sub;
3019
+ createDedicatedRedisClient() {
2682
3020
  if (this.opts.redisClusterNodes?.length) {
2683
- sub = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
3021
+ return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
2684
3022
  redisOptions: {
2685
3023
  tls: this.opts.redisTls ? {} : void 0,
2686
3024
  connectTimeout: 1e4,
2687
- maxRetriesPerRequest: null
3025
+ maxRetriesPerRequest: null,
3026
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2688
3027
  }
2689
3028
  });
2690
3029
  } else if (this.opts.redisSentinel) {
2691
- sub = new import_ioredis.Redis({
3030
+ return new import_ioredis.Redis({
2692
3031
  sentinels: this.opts.redisSentinel.sentinels,
2693
3032
  name: this.opts.redisSentinel.name,
2694
3033
  tls: this.opts.redisTls ? {} : void 0,
@@ -2696,10 +3035,11 @@ var CacheService = class _CacheService {
2696
3035
  lazyConnect: true,
2697
3036
  maxRetriesPerRequest: null,
2698
3037
  enableAutoPipelining: false,
2699
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3038
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3039
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2700
3040
  });
2701
3041
  } else {
2702
- sub = new import_ioredis.Redis({
3042
+ return new import_ioredis.Redis({
2703
3043
  host: this.opts.redisHost,
2704
3044
  port: this.opts.redisPort,
2705
3045
  tls: this.opts.redisTls ? {} : void 0,
@@ -2708,10 +3048,24 @@ var CacheService = class _CacheService {
2708
3048
  maxRetriesPerRequest: null,
2709
3049
  enableAutoPipelining: false,
2710
3050
  family: 4,
2711
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3051
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3052
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2712
3053
  });
2713
3054
  }
2714
- sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
3055
+ }
3056
+ initBackplane() {
3057
+ if (!this.opts.invalidationBackplane || this._redisDisabled) return;
3058
+ if (this.opts.backplaneMode === "stream") {
3059
+ if (this.streamClient) return;
3060
+ void this._startStreamConsumer();
3061
+ return;
3062
+ }
3063
+ if (this.subClient) return;
3064
+ const sub = this.createDedicatedRedisClient();
3065
+ sub.on("error", (e) => {
3066
+ this._checkAndLogResp3Hint(e);
3067
+ this.logger.debug("Backplane subscriber error", { error: e.message });
3068
+ });
2715
3069
  sub.on("close", () => {
2716
3070
  if (this._subDisconnectedAt === null) {
2717
3071
  this._subDisconnectedAt = Date.now();
@@ -2732,54 +3086,264 @@ var CacheService = class _CacheService {
2732
3086
  this._subDisconnectedAt = null;
2733
3087
  }
2734
3088
  });
2735
- sub.on("message", (_channel, message) => {
2736
- this._handleBackplaneMessage(message);
2737
- });
2738
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
2739
- channel: this.backplaneChannel,
2740
- instanceId: this.instanceId
2741
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
2742
- error: err.message
2743
- }));
3089
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
3090
+ if (isClusterSharded) {
3091
+ sub.on("smessage", (_channel, message) => {
3092
+ this._handleBackplaneMessage(message);
3093
+ });
3094
+ sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
3095
+ channel: this.backplaneChannel,
3096
+ instanceId: this.instanceId
3097
+ })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
3098
+ error: err.message
3099
+ }));
3100
+ } else {
3101
+ sub.on("message", (_channel, message) => {
3102
+ this._handleBackplaneMessage(message);
3103
+ });
3104
+ sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
3105
+ channel: this.backplaneChannel,
3106
+ instanceId: this.instanceId
3107
+ })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
3108
+ error: err.message
3109
+ }));
3110
+ }
2744
3111
  this.subClient = sub;
2745
3112
  }
3113
+ async _startStreamConsumer() {
3114
+ const sub = this.streamClient ?? this.createDedicatedRedisClient();
3115
+ this.streamClient = sub;
3116
+ if (typeof sub.on === "function") {
3117
+ sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
3118
+ sub.on("close", () => {
3119
+ if (this._subDisconnectedAt === null) {
3120
+ this._subDisconnectedAt = Date.now();
3121
+ this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
3122
+ }
3123
+ });
3124
+ sub.on("ready", () => {
3125
+ if (this._subDisconnectedAt !== null) {
3126
+ this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
3127
+ this._subDisconnectedAt = null;
3128
+ }
3129
+ });
3130
+ }
3131
+ const runLoop = async () => {
3132
+ while (!this._destroyed && !this._redisDisabled) {
3133
+ try {
3134
+ const res = await sub.xread(
3135
+ "BLOCK",
3136
+ this.opts.backplaneStreamBlockMs,
3137
+ "STREAMS",
3138
+ this.backplaneStreamKey,
3139
+ this._lastStreamId
3140
+ );
3141
+ if (this._destroyed) break;
3142
+ if (res && res.length > 0) {
3143
+ for (const [, entries] of res) {
3144
+ if (entries.length > 0) {
3145
+ if (this._lastStreamId !== "$") {
3146
+ this.counters.streamReplays++;
3147
+ }
3148
+ for (const [id, fields] of entries) {
3149
+ this._lastStreamId = id;
3150
+ this.counters.streamEntriesReceived++;
3151
+ let op = "";
3152
+ let key = "";
3153
+ let src = "";
3154
+ let tagVersion;
3155
+ for (let i = 0; i < fields.length; i += 2) {
3156
+ const f = fields[i];
3157
+ const v = fields[i + 1];
3158
+ if (f === "op") op = v;
3159
+ else if (f === "key") key = v;
3160
+ else if (f === "src") src = v;
3161
+ else if (f === "tagVersion") tagVersion = parseInt(v, 10);
3162
+ }
3163
+ if (src === this.instanceId) {
3164
+ this.counters.invSkipped++;
3165
+ continue;
3166
+ }
3167
+ this.counters.invReceived++;
3168
+ this._applyInvalidationEvent(op, key, tagVersion);
3169
+ }
3170
+ }
3171
+ }
3172
+ } else {
3173
+ await new Promise((resolve) => setTimeout(resolve, 10));
3174
+ }
3175
+ } catch (err) {
3176
+ if (this._destroyed) break;
3177
+ const msg = err.message ?? "";
3178
+ if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
3179
+ this.counters.streamGaps++;
3180
+ this.l1.clear();
3181
+ this._lastStreamId = "$";
3182
+ }
3183
+ await new Promise((resolve) => setTimeout(resolve, 200));
3184
+ }
3185
+ }
3186
+ };
3187
+ void runLoop();
3188
+ }
3189
+ _applyInvalidationEvent(op, key, tagVersion) {
3190
+ if (op === "del") {
3191
+ this.l1.delete(key);
3192
+ setImmediate(() => {
3193
+ if (!this._diskDisabled) this.disk.delete(key);
3194
+ });
3195
+ this._cascadeDependencies(key);
3196
+ } else if (op === "del-glob") {
3197
+ this.l1.deletePattern(key);
3198
+ } else if (op === "tag_incr") {
3199
+ const tag = key;
3200
+ const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
3201
+ this._setLocalTagVersion(tag, ver, Date.now());
3202
+ }
3203
+ this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
3204
+ }
2746
3205
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
2747
3206
  _handleBackplaneMessage(message) {
2748
3207
  try {
2749
3208
  const msg = JSON.parse(message);
3209
+ 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") {
3210
+ this.logger.warn("Backplane: rejected invalid pubsub message format", {
3211
+ raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
3212
+ });
3213
+ return;
3214
+ }
2750
3215
  if (msg.src === this.instanceId) {
2751
3216
  this.counters.invSkipped++;
2752
3217
  return;
2753
3218
  }
2754
3219
  this.counters.invReceived++;
2755
- if (msg.op === "del") {
2756
- this.l1.delete(msg.key);
2757
- setImmediate(() => {
2758
- if (!this._diskDisabled) this.disk.delete(msg.key);
2759
- });
2760
- this._cascadeDependencies(msg.key);
2761
- } else if (msg.op === "del-glob") {
2762
- this.l1.deletePattern(msg.key);
2763
- }
2764
- this.logger.debug("Backplane: peer invalidation applied", {
2765
- op: msg.op,
2766
- key: msg.key.slice(0, 60)
2767
- });
3220
+ this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === "number" ? msg.tagVersion : void 0);
2768
3221
  } catch {
3222
+ this.logger.warn("Backplane: malformed message JSON parse failed");
2769
3223
  }
2770
3224
  }
2771
- async publishInvalidation(op, key) {
3225
+ async publishInvalidation(op, key, tagVersion) {
2772
3226
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2773
3227
  try {
2774
3228
  const client = await this.getRedis();
2775
- await client.publish(
2776
- this.backplaneChannel,
2777
- JSON.stringify({ op, key, src: this.instanceId })
2778
- );
3229
+ if (this.opts.backplaneMode === "stream") {
3230
+ const args = [
3231
+ this.backplaneStreamKey,
3232
+ "MAXLEN",
3233
+ "~",
3234
+ String(this.opts.backplaneStreamMaxLen),
3235
+ "*",
3236
+ "op",
3237
+ op,
3238
+ "key",
3239
+ key,
3240
+ "src",
3241
+ this.instanceId
3242
+ ];
3243
+ if (typeof tagVersion === "number") {
3244
+ args.push("tagVersion", String(tagVersion));
3245
+ }
3246
+ await client.xadd(...args);
3247
+ this.counters.invSent++;
3248
+ return;
3249
+ }
3250
+ const payload = JSON.stringify({ op, key, src: this.instanceId, tagVersion });
3251
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
3252
+ if (isClusterSharded && typeof client.spublish === "function") {
3253
+ await client.spublish(
3254
+ this.backplaneChannel,
3255
+ payload
3256
+ );
3257
+ } else {
3258
+ await client.publish(
3259
+ this.backplaneChannel,
3260
+ payload
3261
+ );
3262
+ }
2779
3263
  this.counters.invSent++;
2780
3264
  } catch {
2781
3265
  }
2782
3266
  }
3267
+ _setLocalTagVersion(tag, version, now = Date.now()) {
3268
+ const existing = this.tagVersions.get(tag)?.version ?? 0;
3269
+ const finalVersion = Math.max(existing, version);
3270
+ if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
3271
+ const oldestKey = this.tagVersions.keys().next().value;
3272
+ if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
3273
+ }
3274
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
3275
+ }
3276
+ async _getTagVersion(tag) {
3277
+ const now = Date.now();
3278
+ const local = this.tagVersions.get(tag);
3279
+ if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
3280
+ return local.version;
3281
+ }
3282
+ if (!this._redisDisabled) {
3283
+ try {
3284
+ const client = await this.getRedis();
3285
+ const raw = await client.get(this.nk(`tag_ver:${tag}`));
3286
+ const version = raw ? parseInt(raw, 10) : 0;
3287
+ this._setLocalTagVersion(tag, version, now);
3288
+ return version;
3289
+ } catch {
3290
+ }
3291
+ }
3292
+ return local?.version ?? 0;
3293
+ }
3294
+ _deleteIfStale(k, setAtMs) {
3295
+ this.l1.deleteIfSetBefore(k, setAtMs);
3296
+ if (!this._diskDisabled) this.disk.delete(k);
3297
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3298
+ void this.getRedis().then((client) => {
3299
+ return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
3300
+ }).catch(() => {
3301
+ });
3302
+ }
3303
+ }
3304
+ /**
3305
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
3306
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
3307
+ */
3308
+ async _serializeAndEncrypt(serialized) {
3309
+ const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
3310
+ if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
3311
+ return this._workerPool.encrypt(serialized);
3312
+ }
3313
+ if (isCompressed2) {
3314
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
3315
+ if (this.enc.isEnabled) {
3316
+ const encrypted = this.enc.encryptBuffer(compressed);
3317
+ return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
3318
+ }
3319
+ return PREFIX_COMPRESSED + compressed.toString("base64");
3320
+ }
3321
+ return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3322
+ }
3323
+ /**
3324
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
3325
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
3326
+ */
3327
+ async _decryptAndDeserialize(raw) {
3328
+ let plain;
3329
+ if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
3330
+ plain = await this._workerPool.decrypt(raw);
3331
+ } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
3332
+ const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
3333
+ const decBuf = this.enc.decryptBuffer(encBuf);
3334
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
3335
+ plain = decompressed.toString("utf8");
3336
+ } else if (raw.startsWith(PREFIX_COMPRESSED)) {
3337
+ const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
3338
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
3339
+ plain = decompressed.toString("utf8");
3340
+ } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
3341
+ plain = this.enc.decrypt(raw);
3342
+ } else {
3343
+ plain = raw;
3344
+ }
3345
+ return JSON.parse(plain);
3346
+ }
2783
3347
  /**
2784
3348
  * Scan all keys matching `pattern` across single-node or Cluster clients.
2785
3349
  * For Cluster, iterates every master node independently (SCAN is node-local).
@@ -2806,8 +3370,18 @@ var CacheService = class _CacheService {
2806
3370
  }
2807
3371
  return keys;
2808
3372
  }
3373
+ _checkAndLogResp3Hint(err) {
3374
+ const msg = err?.message || "";
3375
+ if (!this.opts.redisProtocol && (msg.includes("unknown command") || msg.includes("HELLO") || msg.includes("protocol error") || msg.includes("ProtocolError") || msg.includes("Connection is closed"))) {
3376
+ this.logger.warn(
3377
+ "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.",
3378
+ { hint: "redisProtocol: 2", originalError: msg }
3379
+ );
3380
+ }
3381
+ }
2809
3382
  async getRedis() {
2810
3383
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
3384
+ if (this.redis) return this.redis;
2811
3385
  if (this.redisConnecting) return this.redisConnecting;
2812
3386
  this.redisConnecting = (async () => {
2813
3387
  try {
@@ -2818,14 +3392,18 @@ var CacheService = class _CacheService {
2818
3392
  tls: this.opts.redisTls ? {} : void 0,
2819
3393
  connectTimeout: 1e4,
2820
3394
  maxRetriesPerRequest: 3,
2821
- keepAlive: 3e4
3395
+ keepAlive: 3e4,
3396
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2822
3397
  },
2823
3398
  enableAutoPipelining: true,
2824
3399
  retryDelayOnClusterDown: 200,
2825
3400
  retryDelayOnFailover: 1e3
2826
3401
  });
2827
3402
  client.on("connect", () => this.logger.info("Redis Cluster connected"));
2828
- client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
3403
+ client.on("error", (e) => {
3404
+ this._checkAndLogResp3Hint(e);
3405
+ this.logger.error("Redis Cluster error", {}, e);
3406
+ });
2829
3407
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
2830
3408
  } else if (this.opts.redisSentinel) {
2831
3409
  client = new import_ioredis.Redis({
@@ -2837,10 +3415,14 @@ var CacheService = class _CacheService {
2837
3415
  maxRetriesPerRequest: 3,
2838
3416
  enableAutoPipelining: true,
2839
3417
  keepAlive: 3e4,
2840
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3418
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3419
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2841
3420
  });
2842
3421
  client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
2843
- client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
3422
+ client.on("error", (e) => {
3423
+ this._checkAndLogResp3Hint(e);
3424
+ this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e);
3425
+ });
2844
3426
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
2845
3427
  } else {
2846
3428
  client = new import_ioredis.Redis({
@@ -2853,15 +3435,22 @@ var CacheService = class _CacheService {
2853
3435
  enableAutoPipelining: true,
2854
3436
  keepAlive: 3e4,
2855
3437
  family: 4,
2856
- retryStrategy: (times) => Math.min(times * 50, 2e3)
3438
+ retryStrategy: (times) => Math.min(times * 50, 2e3),
3439
+ ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
2857
3440
  });
2858
3441
  client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2859
- client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
3442
+ client.on("error", (e) => {
3443
+ this._checkAndLogResp3Hint(e);
3444
+ this.logger.error("Redis error", { host: this.opts.redisHost }, e);
3445
+ });
2860
3446
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2861
3447
  }
2862
3448
  await new Promise((resolve, reject) => {
2863
3449
  client.once("ready", resolve);
2864
- client.once("error", reject);
3450
+ client.once("error", (e) => {
3451
+ this._checkAndLogResp3Hint(e);
3452
+ reject(e);
3453
+ });
2865
3454
  setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
2866
3455
  });
2867
3456
  this.cb.onSuccess();
@@ -2871,6 +3460,7 @@ var CacheService = class _CacheService {
2871
3460
  } catch (err) {
2872
3461
  this.cb.onFailure();
2873
3462
  this.redisConnecting = null;
3463
+ this._checkAndLogResp3Hint(err);
2874
3464
  throw err;
2875
3465
  }
2876
3466
  })();
@@ -2885,6 +3475,7 @@ var CacheService = class _CacheService {
2885
3475
  const packed = (0, import_msgpackr3.pack)(payload);
2886
3476
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2887
3477
  const dest = altPath ?? this.opts.snapshotPath;
3478
+ import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
2888
3479
  import_fs3.default.writeFileSync(dest, final, { mode: 384 });
2889
3480
  this.logger.info("Cache snapshot written", {
2890
3481
  path: dest,
@@ -2976,44 +3567,58 @@ var CacheService = class _CacheService {
2976
3567
  const optTags = opts.tags;
2977
3568
  const l1Hit = this.l1.get(k);
2978
3569
  if (l1Hit !== null) {
2979
- if (l1Hit.isStale) {
2980
- const swrGraceMs2 = optSwr * 1e3;
2981
- if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
2982
- const priority2 = optPriority ?? inferPriority(cacheKey);
2983
- this.revalidating.add(k);
2984
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
2985
- this.counters.swrRevalidations++;
2986
- this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
2987
- } else {
2988
- this.logger.debug("L1 hit");
3570
+ let isGenerationalStale = false;
3571
+ if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3572
+ for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3573
+ const currentVer = await this._getTagVersion(tag);
3574
+ if (currentVer > entryVer) {
3575
+ isGenerationalStale = true;
3576
+ break;
3577
+ }
2989
3578
  }
3579
+ }
3580
+ if (isGenerationalStale) {
3581
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
2990
3582
  } else {
2991
- this.logger.debug("L1 hit");
2992
- const ra = optRefreshAhead;
2993
- const xb = optXfetchBeta;
2994
- if (ra || xb) {
2995
- const now = l1Hit.fetchedAt ?? Date.now();
2996
- const remaining = l1Hit.expiresAt - now;
2997
- const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
2998
- const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
2999
- const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
3000
- if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3583
+ if (l1Hit.isStale) {
3584
+ const swrGraceMs2 = optSwr * 1e3;
3585
+ if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
3001
3586
  const priority2 = optPriority ?? inferPriority(cacheKey);
3002
3587
  this.revalidating.add(k);
3003
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
3588
+ void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
3004
3589
  this.counters.swrRevalidations++;
3005
- this.logger.debug(
3006
- shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
3007
- { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
3008
- );
3590
+ this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
3591
+ } else {
3592
+ this.logger.debug("L1 hit");
3593
+ }
3594
+ } else {
3595
+ this.logger.debug("L1 hit");
3596
+ const ra = optRefreshAhead;
3597
+ const xb = optXfetchBeta;
3598
+ if (ra || xb) {
3599
+ const now = l1Hit.fetchedAt ?? Date.now();
3600
+ const remaining = l1Hit.expiresAt - now;
3601
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
3602
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
3603
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
3604
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3605
+ const priority2 = optPriority ?? inferPriority(cacheKey);
3606
+ this.revalidating.add(k);
3607
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
3608
+ this.counters.swrRevalidations++;
3609
+ this.logger.debug(
3610
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
3611
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
3612
+ );
3613
+ }
3009
3614
  }
3010
3615
  }
3616
+ this.counters.l1Hits++;
3617
+ this.opts.onHit?.(cacheKey, "l1");
3618
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
3619
+ span.setAttribute("cache.hit", "l1").end();
3620
+ return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3011
3621
  }
3012
- this.counters.l1Hits++;
3013
- this.opts.onHit?.(cacheKey, "l1");
3014
- if (this.opts.frozen) deepFreeze(l1Hit.value);
3015
- span.setAttribute("cache.hit", "l1").end();
3016
- return l1Hit.value;
3017
3622
  }
3018
3623
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3019
3624
  const swrGraceMs = optSwr * 1e3;
@@ -3021,22 +3626,52 @@ var CacheService = class _CacheService {
3021
3626
  if (!this._redisDisabled) {
3022
3627
  try {
3023
3628
  const client = await this.getRedis();
3024
- const raw = await client.get(k);
3025
- this.cb.onSuccess();
3026
- if (raw) {
3027
- let decrypted;
3028
- if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
3029
- decrypted = await this._workerPool.decrypt(raw);
3030
- } else {
3031
- decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3629
+ if (this.opts.tagStrategy === "generational") {
3630
+ const hashData = await client.hgetall(k);
3631
+ this.cb.onSuccess();
3632
+ if (hashData && hashData.d) {
3633
+ let isStale = false;
3634
+ let storedTagVersions = {};
3635
+ if (hashData.tv) {
3636
+ try {
3637
+ storedTagVersions = JSON.parse(hashData.tv);
3638
+ } catch {
3639
+ }
3640
+ }
3641
+ for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3642
+ const currentVer = await this._getTagVersion(tag);
3643
+ if (currentVer > entryVer) {
3644
+ isStale = true;
3645
+ break;
3646
+ }
3647
+ }
3648
+ if (isStale) {
3649
+ const setAtMs = parseInt(hashData.t, 10) || 0;
3650
+ this._deleteIfStale(k, setAtMs);
3651
+ } else {
3652
+ const parsed = await this._decryptAndDeserialize(hashData.d);
3653
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3654
+ this.counters.l2Hits++;
3655
+ this.opts.onHit?.(cacheKey, "l2");
3656
+ this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3657
+ span.setAttribute("cache.hit", "l2").end();
3658
+ if (this.opts.frozen) deepFreeze(parsed);
3659
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3660
+ }
3661
+ }
3662
+ } else {
3663
+ const raw = await client.get(k);
3664
+ this.cb.onSuccess();
3665
+ if (raw) {
3666
+ const parsed = await this._decryptAndDeserialize(raw);
3667
+ this.l1.set(k, parsed, ttlMs, priority);
3668
+ this.counters.l2Hits++;
3669
+ this.opts.onHit?.(cacheKey, "l2");
3670
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
3671
+ span.setAttribute("cache.hit", "l2").end();
3672
+ if (this.opts.frozen) deepFreeze(parsed);
3673
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3032
3674
  }
3033
- const parsed = JSON.parse(decrypted);
3034
- this.l1.set(k, parsed, ttlMs, priority);
3035
- this.counters.l2Hits++;
3036
- this.opts.onHit?.(cacheKey, "l2");
3037
- this.logger.debug("L2 hit (Redis)", { cacheKey });
3038
- span.setAttribute("cache.hit", "l2").end();
3039
- return parsed;
3040
3675
  }
3041
3676
  } catch (err) {
3042
3677
  this.cb.onFailure();
@@ -3046,18 +3681,33 @@ var CacheService = class _CacheService {
3046
3681
  if (!this._diskDisabled) {
3047
3682
  const diskHit = this.disk.load(k);
3048
3683
  if (diskHit !== null) {
3049
- const promoted = this.l1.importEntries(
3050
- [{ key: k, entry: diskHit }],
3051
- this.opts.forbiddenSnapshotPrefixes
3052
- );
3053
- if (promoted > 0) {
3054
- const l1Check = this.l1.get(k);
3055
- if (l1Check !== null) {
3056
- this.counters.diskHits++;
3057
- this.opts.onHit?.(cacheKey, "disk");
3058
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3059
- span.setAttribute("cache.hit", "disk").end();
3060
- return l1Check.value;
3684
+ let isDiskStale = false;
3685
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3686
+ for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3687
+ const currentVer = await this._getTagVersion(tag);
3688
+ if (currentVer > entryVer) {
3689
+ isDiskStale = true;
3690
+ break;
3691
+ }
3692
+ }
3693
+ }
3694
+ if (isDiskStale) {
3695
+ this.disk.delete(k);
3696
+ } else {
3697
+ const promoted = this.l1.importEntries(
3698
+ [{ key: k, entry: diskHit }],
3699
+ this.opts.forbiddenSnapshotPrefixes
3700
+ );
3701
+ if (promoted > 0) {
3702
+ const l1Check = this.l1.get(k);
3703
+ if (l1Check !== null) {
3704
+ this.counters.diskHits++;
3705
+ this.opts.onHit?.(cacheKey, "disk");
3706
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3707
+ span.setAttribute("cache.hit", "disk").end();
3708
+ if (this.opts.frozen) deepFreeze(l1Check.value);
3709
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
3710
+ }
3061
3711
  }
3062
3712
  }
3063
3713
  }
@@ -3092,19 +3742,37 @@ var CacheService = class _CacheService {
3092
3742
  }
3093
3743
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
3094
3744
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
3095
- this.l1.set(k, data, storeTtl, priority, staleAt, delta);
3096
- if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3745
+ let activeTagVersions;
3746
+ if (optTags?.length) {
3747
+ if (this.opts.tagStrategy === "generational") {
3748
+ activeTagVersions = {};
3749
+ for (const tag of optTags) {
3750
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3751
+ }
3752
+ } else {
3753
+ await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3754
+ }
3755
+ }
3756
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
3097
3757
  if (!this._redisDisabled) {
3098
3758
  try {
3099
3759
  const client = await this.getRedis();
3100
3760
  const serialized = JSON.stringify(data);
3101
- let toStore;
3102
- if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
3103
- toStore = await this._workerPool.encrypt(serialized);
3761
+ const toStore = await this._serializeAndEncrypt(serialized);
3762
+ const ttlSec = Math.ceil(effectiveTtl / 1e3);
3763
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3764
+ const now = Date.now();
3765
+ const tx = client.multi();
3766
+ tx.hset(k, {
3767
+ d: toStore,
3768
+ t: String(now),
3769
+ tv: JSON.stringify(activeTagVersions)
3770
+ });
3771
+ tx.expire(k, ttlSec);
3772
+ await tx.exec();
3104
3773
  } else {
3105
- toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3774
+ await client.setex(k, ttlSec, toStore);
3106
3775
  }
3107
- await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
3108
3776
  this.cb.onSuccess();
3109
3777
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
3110
3778
  } catch {
@@ -3114,7 +3782,8 @@ var CacheService = class _CacheService {
3114
3782
  } else {
3115
3783
  this.logger.debug("Cached L1", { cacheKey });
3116
3784
  }
3117
- return data;
3785
+ if (this.opts.frozen) deepFreeze(data);
3786
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
3118
3787
  } finally {
3119
3788
  this.inflight.delete(k);
3120
3789
  span.end();
@@ -3123,6 +3792,27 @@ var CacheService = class _CacheService {
3123
3792
  this.inflight.set(k, fetchPromise);
3124
3793
  return fetchPromise;
3125
3794
  }
3795
+ /**
3796
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
3797
+ *
3798
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
3799
+ * from `cache-manager` and `keyv`.
3800
+ *
3801
+ * @param cacheKey - Unique cache key.
3802
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
3803
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
3804
+ *
3805
+ * @example
3806
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
3807
+ * ttl: 300,
3808
+ * swr: 60,
3809
+ * tags: ['users'],
3810
+ * });
3811
+ */
3812
+ wrap(cacheKey, fetchFn, options) {
3813
+ const ttl = options?.ttl ?? 300;
3814
+ return this.get(cacheKey, fetchFn, ttl, options);
3815
+ }
3126
3816
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
3127
3817
  try {
3128
3818
  const fetchStart = Date.now();
@@ -3130,18 +3820,34 @@ var CacheService = class _CacheService {
3130
3820
  const delta = Date.now() - fetchStart;
3131
3821
  const staleAt = Date.now() + ttlMs;
3132
3822
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
3133
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
3823
+ let activeTagVersions;
3824
+ const l1Existing = this.l1.get(cacheKey);
3825
+ if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
3826
+ activeTagVersions = {};
3827
+ for (const tag of Object.keys(l1Existing.tagVersions)) {
3828
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3829
+ }
3830
+ }
3831
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
3134
3832
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3135
3833
  try {
3136
3834
  const client = await this.getRedis();
3137
3835
  const s = JSON.stringify(data);
3138
- let stored;
3139
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
3140
- stored = await this._workerPool.encrypt(s);
3836
+ const stored = await this._serializeAndEncrypt(s);
3837
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3838
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3839
+ const now = Date.now();
3840
+ const tx = client.multi();
3841
+ tx.hset(cacheKey, {
3842
+ d: stored,
3843
+ t: String(now),
3844
+ tv: JSON.stringify(activeTagVersions)
3845
+ });
3846
+ tx.expire(cacheKey, ttlSec);
3847
+ await tx.exec();
3141
3848
  } else {
3142
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
3849
+ await client.setex(cacheKey, ttlSec, stored);
3143
3850
  }
3144
- await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
3145
3851
  } catch {
3146
3852
  }
3147
3853
  }
@@ -3170,8 +3876,18 @@ var CacheService = class _CacheService {
3170
3876
  const p = priority ?? inferPriority(cacheKey);
3171
3877
  const k = this.nk(cacheKey);
3172
3878
  this.counters.sets++;
3173
- this.l1.set(k, data, ttlMs, p);
3174
- if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
3879
+ let activeTagVersions;
3880
+ if (opts?.tags?.length) {
3881
+ if (this.opts.tagStrategy === "generational") {
3882
+ activeTagVersions = {};
3883
+ for (const tag of opts.tags) {
3884
+ activeTagVersions[tag] = await this._getTagVersion(tag);
3885
+ }
3886
+ } else {
3887
+ await this._registerTags(k, opts.tags, ttlSeconds);
3888
+ }
3889
+ }
3890
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3175
3891
  if (opts?.dependsOn?.length) {
3176
3892
  for (const pattern of opts.dependsOn) {
3177
3893
  const nsPattern = this.nk(pattern);
@@ -3187,13 +3903,21 @@ var CacheService = class _CacheService {
3187
3903
  try {
3188
3904
  const client = await this.getRedis();
3189
3905
  const s = JSON.stringify(data);
3190
- let stored;
3191
- if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
3192
- stored = await this._workerPool.encrypt(s);
3906
+ const stored = await this._serializeAndEncrypt(s);
3907
+ const ttlSec = Math.ceil(ttlMs / 1e3);
3908
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3909
+ const now = Date.now();
3910
+ const tx = client.multi();
3911
+ tx.hset(k, {
3912
+ d: stored,
3913
+ t: String(now),
3914
+ tv: JSON.stringify(activeTagVersions)
3915
+ });
3916
+ tx.expire(k, ttlSec);
3917
+ await tx.exec();
3193
3918
  } else {
3194
- stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
3919
+ await client.setex(k, ttlSec, stored);
3195
3920
  }
3196
- await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
3197
3921
  this.cb.onSuccess();
3198
3922
  } catch (err) {
3199
3923
  this.cb.onFailure();
@@ -3302,7 +4026,7 @@ var CacheService = class _CacheService {
3302
4026
  );
3303
4027
  }
3304
4028
  const now = Date.now();
3305
- const ttlMs = (ttlSeconds ?? 60) * 1e3;
4029
+ const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1e3;
3306
4030
  const entry = this._l1Counters.get(k);
3307
4031
  if (entry && entry.expiresAt > now) {
3308
4032
  entry.value++;
@@ -3342,6 +4066,7 @@ var CacheService = class _CacheService {
3342
4066
  if (!this._diskDisabled) this.disk.clear();
3343
4067
  this._l1Counters.clear();
3344
4068
  this.tagIndex.clear();
4069
+ this.tagVersions.clear();
3345
4070
  }
3346
4071
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3347
4072
  try {
@@ -3389,9 +4114,10 @@ var CacheService = class _CacheService {
3389
4114
  * for (const key of cache.keys()) console.log(key);
3390
4115
  */
3391
4116
  *keys() {
3392
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4117
+ const prefix = this._namespace ? this._namespace + ":" : "";
3393
4118
  for (const key of this.l1.liveKeys()) {
3394
- yield prefixLen > 0 ? key.slice(prefixLen) : key;
4119
+ if (prefix && !key.startsWith(prefix)) continue;
4120
+ yield prefix ? key.slice(prefix.length) : key;
3395
4121
  }
3396
4122
  }
3397
4123
  /**
@@ -3402,7 +4128,15 @@ var CacheService = class _CacheService {
3402
4128
  * for (const val of cache.values<User>()) console.log(val.id);
3403
4129
  */
3404
4130
  *values() {
3405
- yield* this.l1.liveValues();
4131
+ const prefix = this._namespace ? this._namespace + ":" : "";
4132
+ if (!prefix) {
4133
+ yield* this.l1.liveValues();
4134
+ } else {
4135
+ for (const [key, entry] of this.l1.liveEntries()) {
4136
+ if (!key.startsWith(prefix)) continue;
4137
+ yield this.l1.resolveValue(entry);
4138
+ }
4139
+ }
3406
4140
  }
3407
4141
  /**
3408
4142
  * Lazily yield every non-expired L1 [key, value] pair.
@@ -3412,10 +4146,10 @@ var CacheService = class _CacheService {
3412
4146
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
3413
4147
  */
3414
4148
  *entries() {
3415
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4149
+ const prefix = this._namespace ? this._namespace + ":" : "";
3416
4150
  for (const [key, entry] of this.l1.liveEntries()) {
3417
- const k = prefixLen > 0 ? key.slice(prefixLen) : key;
3418
- yield [k, this.l1.resolveValue(entry)];
4151
+ if (prefix && !key.startsWith(prefix)) continue;
4152
+ yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry)];
3419
4153
  }
3420
4154
  }
3421
4155
  /**
@@ -3480,6 +4214,63 @@ var CacheService = class _CacheService {
3480
4214
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
3481
4215
  return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
3482
4216
  }
4217
+ /**
4218
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
4219
+ * Returns the cached value if found and valid, or `null` if absent / expired.
4220
+ * Does not write dummy entries on misses or trigger side-effects.
4221
+ *
4222
+ * @example
4223
+ * const val = await cache.peek<User>('user:123');
4224
+ */
4225
+ async peek(cacheKey) {
4226
+ const k = this.nk(cacheKey);
4227
+ const l1Hit = this.l1.get(k);
4228
+ if (l1Hit !== null) {
4229
+ this.counters.gets++;
4230
+ this.counters.l1Hits++;
4231
+ const val = l1Hit.value;
4232
+ if (this.opts.frozen) deepFreeze(val);
4233
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4234
+ }
4235
+ if (!this._diskDisabled) {
4236
+ const diskHit = this.disk.load(k);
4237
+ if (diskHit !== null) {
4238
+ const promoted = this.l1.importEntries(
4239
+ [{ key: k, entry: diskHit }],
4240
+ this.opts.forbiddenSnapshotPrefixes
4241
+ );
4242
+ if (promoted > 0) {
4243
+ const l1Check = this.l1.get(k);
4244
+ if (l1Check !== null) {
4245
+ this.counters.gets++;
4246
+ this.counters.diskHits++;
4247
+ const val = l1Check.value;
4248
+ if (this.opts.frozen) deepFreeze(val);
4249
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4250
+ }
4251
+ }
4252
+ }
4253
+ }
4254
+ if (!this._redisDisabled && !this.cb.isOpen) {
4255
+ try {
4256
+ const client = await this.getRedis();
4257
+ const raw = await client.get(k);
4258
+ if (raw !== null) {
4259
+ const parsed = await this._decryptAndDeserialize(raw);
4260
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
4261
+ this.counters.gets++;
4262
+ this.counters.l2Hits++;
4263
+ this.cb.onSuccess();
4264
+ if (this.opts.frozen) deepFreeze(parsed);
4265
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
4266
+ }
4267
+ } catch (err) {
4268
+ this.cb.onFailure();
4269
+ this.logger.debug("peek: Redis read failed", { cacheKey, error: err.message });
4270
+ }
4271
+ }
4272
+ return null;
4273
+ }
3483
4274
  /**
3484
4275
  * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
3485
4276
  * Preserves input ordering. Uses inflight coalescing per key.
@@ -3490,7 +4281,7 @@ var CacheService = class _CacheService {
3490
4281
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
3491
4282
  */
3492
4283
  async mget(keys, fetchFn, ttl = 300, priority) {
3493
- const result = new Array(keys.length);
4284
+ const result = Array.from({ length: keys.length });
3494
4285
  const missIndexes = [];
3495
4286
  const missKeys = [];
3496
4287
  for (let i = 0; i < keys.length; i++) {
@@ -3517,13 +4308,7 @@ var CacheService = class _CacheService {
3517
4308
  const raw = raws[j] ? raws[j][1] : null;
3518
4309
  const idx = missIndexes[j];
3519
4310
  if (raw) {
3520
- let parsed;
3521
- if (this.enc.isEnabled) {
3522
- const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
3523
- parsed = JSON.parse(decrypted);
3524
- } else {
3525
- parsed = JSON.parse(raw);
3526
- }
4311
+ const parsed = await this._decryptAndDeserialize(raw);
3527
4312
  const k = nsKeys[j];
3528
4313
  const p = priority ?? inferPriority(missKeys[j]);
3529
4314
  this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
@@ -3655,12 +4440,10 @@ var CacheService = class _CacheService {
3655
4440
  const [err, raw] = results[i];
3656
4441
  if (err || raw == null) continue;
3657
4442
  try {
3658
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3659
- const parsed = JSON.parse(decrypted);
4443
+ const parsed = await this._decryptAndDeserialize(raw);
3660
4444
  const remainingMs = 10 * 60 * 1e3;
3661
4445
  this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3662
4446
  loaded++;
3663
- ;
3664
4447
  } catch {
3665
4448
  }
3666
4449
  }
@@ -3686,6 +4469,25 @@ var CacheService = class _CacheService {
3686
4469
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3687
4470
  */
3688
4471
  async invalidateTag(tag) {
4472
+ if (this.opts.tagStrategy === "generational") {
4473
+ let newVer = 1;
4474
+ if (!this._redisDisabled) {
4475
+ try {
4476
+ const client = await this.getRedis();
4477
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
4478
+ } catch (err) {
4479
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4480
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4481
+ newVer = current + 1;
4482
+ }
4483
+ } else {
4484
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4485
+ newVer = current + 1;
4486
+ }
4487
+ this._setLocalTagVersion(tag, newVer, Date.now());
4488
+ void this.publishInvalidation("tag_incr", tag, newVer);
4489
+ return;
4490
+ }
3689
4491
  const tagKey = this.nk(`_tag_:${tag}`);
3690
4492
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
3691
4493
  for (const k of members) {
@@ -3726,6 +4528,32 @@ var CacheService = class _CacheService {
3726
4528
  await this.invalidateTag(tags[0]);
3727
4529
  return;
3728
4530
  }
4531
+ if (this.opts.tagStrategy === "generational") {
4532
+ const now = Date.now();
4533
+ if (!this._redisDisabled) {
4534
+ try {
4535
+ const client = await this.getRedis();
4536
+ const pl = client.pipeline();
4537
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
4538
+ const results = await pl.exec();
4539
+ for (let i = 0; i < tags.length; i++) {
4540
+ const [err, newVer] = results[i] ?? [null, null];
4541
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4542
+ this._setLocalTagVersion(tags[i], ver, now);
4543
+ void this.publishInvalidation("tag_incr", tags[i], ver);
4544
+ }
4545
+ return;
4546
+ } catch (err) {
4547
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
4548
+ }
4549
+ }
4550
+ for (const tag of tags) {
4551
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4552
+ this._setLocalTagVersion(tag, ver, now);
4553
+ void this.publishInvalidation("tag_incr", tag, ver);
4554
+ }
4555
+ return;
4556
+ }
3729
4557
  const tagKeys = [];
3730
4558
  const allMembers = /* @__PURE__ */ new Set();
3731
4559
  for (const tag of tags) {
@@ -3760,6 +4588,12 @@ var CacheService = class _CacheService {
3760
4588
  }
3761
4589
  }
3762
4590
  }
4591
+ /**
4592
+ * Get the current generational tag version for a tag (synced with Redis when due).
4593
+ */
4594
+ async getTagVersion(tag) {
4595
+ return this._getTagVersion(tag);
4596
+ }
3763
4597
  /**
3764
4598
  * Measure L1 / disk / Redis latency.
3765
4599
  * Useful for health checks and dashboards.
@@ -3858,6 +4692,132 @@ var CacheService = class _CacheService {
3858
4692
  this.counters.sets++;
3859
4693
  return true;
3860
4694
  }
4695
+ // ── Distributed / In-Process Mutex Lock ───────────────────────────────────
4696
+ /**
4697
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
4698
+ * execute `fn`, and automatically release the lock on completion or error.
4699
+ *
4700
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
4701
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
4702
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
4703
+ *
4704
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
4705
+ * @param fn Task to run exclusively while holding the lock.
4706
+ * @param options TTL, acquire timeout, and retry polling intervals.
4707
+ */
4708
+ async lock(resourceKey, fn, options) {
4709
+ const ttlSeconds = Math.max(1, options?.ttl ?? 30);
4710
+ const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
4711
+ const retryInterval = Math.max(10, options?.retryInterval ?? 100);
4712
+ const lockKey = this.nk(`lock:${resourceKey}`);
4713
+ const token = import_crypto3.default.randomUUID();
4714
+ const deadline = Date.now() + acquireTimeout;
4715
+ let acquired = false;
4716
+ if (!this._redisDisabled) {
4717
+ try {
4718
+ const client = await this.getRedis();
4719
+ while (Date.now() <= deadline) {
4720
+ const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4721
+ if (res === "OK") {
4722
+ acquired = true;
4723
+ break;
4724
+ }
4725
+ const remaining = deadline - Date.now();
4726
+ if (remaining <= 0) break;
4727
+ await new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)));
4728
+ }
4729
+ if (!acquired) {
4730
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4731
+ }
4732
+ try {
4733
+ return await fn();
4734
+ } finally {
4735
+ try {
4736
+ const LUA_RELEASE_LOCK = `
4737
+ if redis.call("get", KEYS[1]) == ARGV[1] then
4738
+ return redis.call("del", KEYS[1])
4739
+ else
4740
+ return 0
4741
+ end
4742
+ `;
4743
+ await client.eval(LUA_RELEASE_LOCK, 1, lockKey, token);
4744
+ } catch {
4745
+ }
4746
+ }
4747
+ } catch (err) {
4748
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4749
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4750
+ resourceKey,
4751
+ error: err.message
4752
+ });
4753
+ }
4754
+ }
4755
+ let unlock = () => {
4756
+ };
4757
+ const lockPromise = new Promise((resolve) => {
4758
+ unlock = resolve;
4759
+ });
4760
+ while (Date.now() <= deadline) {
4761
+ const existing = this._localLocks.get(lockKey);
4762
+ if (!existing) {
4763
+ this._localLocks.set(lockKey, lockPromise);
4764
+ acquired = true;
4765
+ break;
4766
+ }
4767
+ const remaining = deadline - Date.now();
4768
+ if (remaining <= 0) break;
4769
+ await Promise.race([
4770
+ existing,
4771
+ new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)))
4772
+ ]);
4773
+ }
4774
+ if (!acquired) {
4775
+ throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4776
+ }
4777
+ try {
4778
+ return await fn();
4779
+ } finally {
4780
+ unlock();
4781
+ if (this._localLocks.get(lockKey) === lockPromise) {
4782
+ this._localLocks.delete(lockKey);
4783
+ }
4784
+ }
4785
+ }
4786
+ // ── OpenTelemetry Metrics Integration ──────────────────────────────────────
4787
+ _initOtelMetrics(meter) {
4788
+ try {
4789
+ this._otelMetrics.gets = meter.createCounter("tricache.gets.total", { description: "Total cache get operations" });
4790
+ this._otelMetrics.l1Hits = meter.createCounter("tricache.l1.hits", { description: "L1 RAM cache hits" });
4791
+ this._otelMetrics.l2Hits = meter.createCounter("tricache.l2.hits", { description: "L2 Redis cache hits" });
4792
+ this._otelMetrics.diskHits = meter.createCounter("tricache.disk.hits", { description: "L1.5 disk cache hits" });
4793
+ this._otelMetrics.fetches = meter.createCounter("tricache.fetches", { description: "Cache miss fetch calls" });
4794
+ this._otelMetrics.stampedes = meter.createCounter("tricache.stampedes.prevented", { description: "Coalesced duplicate inflight requests" });
4795
+ this._otelMetrics.sets = meter.createCounter("tricache.sets.total", { description: "Total set operations" });
4796
+ this._otelMetrics.deletes = meter.createCounter("tricache.deletes.total", { description: "Total delete operations" });
4797
+ this._otelMetrics.swrRevalidations = meter.createCounter("tricache.swr.revalidations", { description: "SWR background revalidations" });
4798
+ const gL1Entries = meter.createObservableGauge("tricache.l1.entries", { description: "Current L1 entry count" });
4799
+ const gL1Bytes = meter.createObservableGauge("tricache.l1.bytes", { description: "Current L1 memory usage in bytes" });
4800
+ const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
4801
+ const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
4802
+ const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
4803
+ meter.addBatchObservableCallback((observableResult) => {
4804
+ const stats = this.stats();
4805
+ const l1 = stats.l1;
4806
+ const disk = stats.disk;
4807
+ const checks = this.counters.bloomChecks;
4808
+ const fps = this.counters.bloomFalsePositives;
4809
+ const fpr = checks > 0 ? fps / checks : 0;
4810
+ const attrs = this._namespace ? { namespace: this._namespace } : void 0;
4811
+ observableResult.observe(gL1Entries, l1.entries, attrs);
4812
+ observableResult.observe(gL1Bytes, l1.sizeBytes, attrs);
4813
+ observableResult.observe(gDiskFiles, disk.files, attrs);
4814
+ observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
4815
+ observableResult.observe(gBloomFpr, fpr, attrs);
4816
+ }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
4817
+ } catch (err) {
4818
+ this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
4819
+ }
4820
+ }
3861
4821
  // ── Hot key introspection ─────────────────────────────────────────────
3862
4822
  /**
3863
4823
  * Return the top-N live L1 keys by historical access frequency.
@@ -3888,18 +4848,20 @@ var CacheService = class _CacheService {
3888
4848
  */
3889
4849
  _matchesGlob(key, pattern) {
3890
4850
  if (!pattern.includes("*")) return key === pattern;
3891
- const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
3892
- return re.test(key);
4851
+ return getGlobRegex(pattern).test(key);
3893
4852
  }
3894
4853
  /**
3895
4854
  * When an exact key `deletedKey` is removed, cascade to every dependent key
3896
4855
  * that was registered via `dependsOn` and whose source pattern matches.
4856
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
3897
4857
  */
3898
- _cascadeDependencies(deletedKey) {
4858
+ _cascadeDependencies(deletedKey, visited = /* @__PURE__ */ new Set()) {
4859
+ if (visited.has(deletedKey)) return;
4860
+ visited.add(deletedKey);
3899
4861
  for (const [pattern, dependents] of this.dependencyIndex) {
3900
4862
  if (!this._matchesGlob(deletedKey, pattern)) continue;
3901
4863
  for (const dep of dependents) {
3902
- if (dep === deletedKey) continue;
4864
+ if (visited.has(dep)) continue;
3903
4865
  this.l1.delete(dep);
3904
4866
  if (!this._diskDisabled) this.disk.delete(dep);
3905
4867
  void this.publishInvalidation("del", dep);
@@ -3907,6 +4869,7 @@ var CacheService = class _CacheService {
3907
4869
  trigger: deletedKey.slice(0, 60),
3908
4870
  dependent: dep.slice(0, 60)
3909
4871
  });
4872
+ this._cascadeDependencies(dep, visited);
3910
4873
  }
3911
4874
  }
3912
4875
  }
@@ -3950,9 +4913,13 @@ var CacheService = class _CacheService {
3950
4913
  },
3951
4914
  backplane: {
3952
4915
  enabled: this.opts.invalidationBackplane && !this._redisDisabled,
4916
+ mode: this.opts.backplaneMode,
3953
4917
  sent: c.invSent,
3954
4918
  received: c.invReceived,
3955
- skipped: c.invSkipped
4919
+ skipped: c.invSkipped,
4920
+ streamEntriesReceived: c.streamEntriesReceived,
4921
+ streamReplays: c.streamReplays,
4922
+ streamGaps: c.streamGaps
3956
4923
  },
3957
4924
  l2CircuitBreaker: {
3958
4925
  state: this.cb.currentState
@@ -4046,8 +5013,21 @@ var CacheService = class _CacheService {
4046
5013
  return lines.join("\n");
4047
5014
  }
4048
5015
  // ── Lifecycle ────────────────────────────────────────────────────────────
5016
+ /**
5017
+ * Dynamically rotate the active encryption key at runtime without restarting.
5018
+ * Installs the new key as primary for all subsequent writes, while preserving
5019
+ * the previous key for seamless fallback decryption of existing cache entries.
5020
+ */
5021
+ async rotateEncryptionKey(newKeyBase64, newMode) {
5022
+ this.enc.rotateKey(newKeyBase64, newMode);
5023
+ if (this._workerPool) {
5024
+ await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
5025
+ }
5026
+ this.logger.info("tricache: encryption key rotated dynamically", { mode: this.enc.mode });
5027
+ }
4049
5028
  /** Close Redis connections and stop all background timers. */
4050
5029
  async destroy() {
5030
+ this._destroyed = true;
4051
5031
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4052
5032
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4053
5033
  if (this.oomInterval) clearInterval(this.oomInterval);
@@ -4063,11 +5043,18 @@ var CacheService = class _CacheService {
4063
5043
  }
4064
5044
  if (this.subClient) {
4065
5045
  try {
4066
- await this.subClient.quit();
5046
+ this.subClient.disconnect();
4067
5047
  } catch {
4068
5048
  }
4069
5049
  this.subClient = null;
4070
5050
  }
5051
+ if (this.streamClient) {
5052
+ try {
5053
+ this.streamClient.disconnect();
5054
+ } catch {
5055
+ }
5056
+ this.streamClient = null;
5057
+ }
4071
5058
  if (this.redis) {
4072
5059
  try {
4073
5060
  await this.redis.disconnect();