tricache 0.5.1 → 0.6.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.
package/dist/index.js CHANGED
@@ -1,8 +1,132 @@
1
+ import {
2
+ CacheEncryption,
3
+ __require
4
+ } from "./chunk-F24NEZGQ.js";
5
+
1
6
  // src/cache-service.ts
2
- import { Redis as RedisClient } from "ioredis";
7
+ import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
3
8
  import { pack as pack3, unpack as unpack3 } from "msgpackr";
4
9
  import crypto2 from "crypto";
5
10
  import os from "os";
11
+
12
+ // src/worker-pool.ts
13
+ import { Worker } from "worker_threads";
14
+ import { fileURLToPath } from "url";
15
+ import { dirname, join } from "path";
16
+ import { existsSync } from "fs";
17
+ var _workerFile;
18
+ var _workerExecArgv = [];
19
+ try {
20
+ const dir = dirname(fileURLToPath(import.meta.url));
21
+ const jsPath = join(dir, "serialize-worker.js");
22
+ const tsPath = join(dir, "serialize-worker.ts");
23
+ if (existsSync(jsPath)) {
24
+ _workerFile = jsPath;
25
+ } else if (existsSync(tsPath)) {
26
+ _workerFile = tsPath;
27
+ _workerExecArgv = ["--import", "tsx"];
28
+ } else {
29
+ _workerFile = jsPath;
30
+ }
31
+ } catch {
32
+ _workerFile = join(__dirname, "serialize-worker.js");
33
+ }
34
+ var WorkerPool = class {
35
+ workers = [];
36
+ pending = [];
37
+ _nextId = 0;
38
+ _robin = 0;
39
+ _available = false;
40
+ constructor(opts) {
41
+ const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
42
+ const workerData = {
43
+ keyBase64: opts.keyBase64,
44
+ mode: opts.mode,
45
+ prevKeyBase64: opts.prevKeyBase64 ?? "",
46
+ prevMode: opts.prevMode
47
+ };
48
+ try {
49
+ for (let i = 0; i < size; i++) {
50
+ const worker = new Worker(_workerFile, {
51
+ workerData,
52
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
53
+ });
54
+ const pending = /* @__PURE__ */ new Map();
55
+ worker.on("message", (msg) => {
56
+ const entry = pending.get(msg.id);
57
+ if (!entry) return;
58
+ pending.delete(msg.id);
59
+ if (pending.size === 0) worker.unref();
60
+ if (msg.error !== void 0) {
61
+ entry.reject(new Error(msg.error));
62
+ } else {
63
+ entry.resolve(msg.result);
64
+ }
65
+ });
66
+ worker.on("error", (err) => {
67
+ for (const [, entry] of pending) entry.reject(err);
68
+ pending.clear();
69
+ worker.unref();
70
+ });
71
+ worker.unref();
72
+ this.workers.push(worker);
73
+ this.pending.push(pending);
74
+ }
75
+ this._available = true;
76
+ } catch {
77
+ this._destroy();
78
+ }
79
+ }
80
+ get isAvailable() {
81
+ return this._available;
82
+ }
83
+ /** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
84
+ encrypt(payload) {
85
+ return this._dispatch("encrypt", payload);
86
+ }
87
+ /** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
88
+ decrypt(payload) {
89
+ return this._dispatch("decrypt", payload);
90
+ }
91
+ _dispatch(type, payload) {
92
+ const id = this._nextId++;
93
+ const idx = this._robin;
94
+ const worker = this.workers[idx];
95
+ const pending = this.pending[idx];
96
+ this._robin = (this._robin + 1) % this.workers.length;
97
+ return new Promise((resolve, reject) => {
98
+ pending.set(id, { resolve, reject });
99
+ worker.ref();
100
+ worker.postMessage({ id, type, payload });
101
+ });
102
+ }
103
+ /** Terminate all worker threads. In-flight promises are rejected. */
104
+ async destroy() {
105
+ this._available = false;
106
+ this._destroy();
107
+ }
108
+ _destroy() {
109
+ for (let i = 0; i < this.workers.length; i++) {
110
+ for (const [, entry] of this.pending[i] ?? []) {
111
+ entry.reject(new Error("WorkerPool destroyed"));
112
+ }
113
+ this.pending[i]?.clear();
114
+ this.workers[i]?.terminate().catch(() => {
115
+ });
116
+ }
117
+ }
118
+ };
119
+ function availableCpus() {
120
+ try {
121
+ const os2 = __require("os");
122
+ return os2.availableParallelism?.() ?? os2.cpus().length;
123
+ } catch {
124
+ return 2;
125
+ }
126
+ }
127
+
128
+ // src/cache-service.ts
129
+ import v8 from "v8";
6
130
  import fs2 from "fs";
7
131
  import path2 from "path";
8
132
 
@@ -22,312 +146,6 @@ var CachePriority = /* @__PURE__ */ ((CachePriority2) => {
22
146
  return CachePriority2;
23
147
  })(CachePriority || {});
24
148
 
25
- // src/encryption.ts
26
- import { createCipheriv, createDecipheriv, randomFillSync } from "crypto";
27
- var IV_BYTES = 12;
28
- var TAG_BYTES = 16;
29
- var PREFIX_256 = "enc:v1:";
30
- var PREFIX_128 = "a128:v1:";
31
- var PREFIX_XOR = "xor:v1:";
32
- var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
33
- var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
34
- var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
35
- var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
36
- var MAGIC_LEN = 8;
37
- var CTR_IV_BYTES = 16;
38
- var PREFIX_CTR = "ctr:v1:";
39
- var IV_POOL_COUNT = 64;
40
- var CacheEncryption = class {
41
- _key = null;
42
- _mode;
43
- _prevKey = null;
44
- _prevMode = "aes-256-gcm";
45
- // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
46
- _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
47
- _ivOffset = IV_BYTES * IV_POOL_COUNT;
48
- // start exhausted → fill on first use
49
- /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
50
- _nextIV() {
51
- if (this._ivOffset >= this._ivPool.length) {
52
- randomFillSync(this._ivPool);
53
- this._ivOffset = 0;
54
- }
55
- const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES);
56
- this._ivOffset += IV_BYTES;
57
- return iv;
58
- }
59
- // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
60
- _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
61
- _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
62
- /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
63
- _nextCtrIV() {
64
- if (this._ctrIvOffset >= this._ctrIvPool.length) {
65
- randomFillSync(this._ctrIvPool);
66
- this._ctrIvOffset = 0;
67
- }
68
- const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
69
- this._ctrIvOffset += CTR_IV_BYTES;
70
- return iv;
71
- }
72
- /**
73
- * XOR `data` with the key, cycling through key bytes.
74
- * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
75
- *
76
- * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
77
- * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
78
- * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
79
- * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
80
- *
81
- * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
82
- */
83
- _xorBuffer(data) {
84
- const key = this._key;
85
- const klen = key.length;
86
- const len = data.length;
87
- const out = Buffer.allocUnsafe(len);
88
- if (klen % 4 === 0 && len >= 4 && data.byteOffset % 4 === 0 && out.byteOffset % 4 === 0 && key.byteOffset % 4 === 0) {
89
- const wordCount = len >>> 2;
90
- const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
91
- const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
92
- const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
93
- const kLen32 = key32.length;
94
- for (let i = 0; i < wordCount; i++) {
95
- out32[i] = data32[i] ^ key32[i % kLen32];
96
- }
97
- for (let i = wordCount << 2; i < len; i++) {
98
- out[i] = data[i] ^ key[i % klen];
99
- }
100
- return out;
101
- }
102
- for (let i = 0; i < len; i++) {
103
- out[i] = data[i] ^ key[i % klen];
104
- }
105
- return out;
106
- }
107
- constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
108
- this._mode = mode;
109
- if (!keyBase64) {
110
- if (process.env.NODE_ENV === "production") {
111
- logger.warn(
112
- "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
113
- { hint: "Set encryptionKey option or CACHE_ENCRYPTION_KEY env var" }
114
- );
115
- }
116
- return;
117
- }
118
- try {
119
- const buf = Buffer.from(keyBase64, "base64");
120
- const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
121
- if (requiredLen > 0 && buf.length !== requiredLen) {
122
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
123
- }
124
- if (buf.length < 1) {
125
- throw new Error("XOR key must be at least 1 byte");
126
- }
127
- this._key = buf;
128
- if (mode === "xor") {
129
- logger.warn(
130
- "Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
131
- );
132
- } else {
133
- logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
134
- }
135
- } catch (err) {
136
- logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
137
- }
138
- if (previousKeyBase64) {
139
- try {
140
- this._prevMode = previousMode ?? mode;
141
- this._prevKey = Buffer.from(previousKeyBase64, "base64");
142
- logger.debug("Previous encryption key loaded for key rotation fallback");
143
- } catch (err) {
144
- logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
145
- }
146
- }
147
- }
148
- get isEnabled() {
149
- return this._key !== null;
150
- }
151
- // ── String (Redis) ────────────────────────────────────────────────────────
152
- /**
153
- * Encrypt a string for Redis storage.
154
- * Returns a mode-prefixed base64 string when a key is configured;
155
- * otherwise returns the original string unchanged (backward-compatible).
156
- */
157
- encrypt(plaintext) {
158
- if (!this._key) return plaintext;
159
- if (this._mode === "xor") {
160
- const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
161
- return PREFIX_XOR + masked.toString("base64");
162
- }
163
- if (this._mode === "aes-128-ctr") {
164
- const iv2 = this._nextCtrIV();
165
- const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
166
- const enc2 = c2.update(plaintext, "utf8");
167
- const fin = c2.final();
168
- const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
169
- iv2.copy(out2, 0);
170
- enc2.copy(out2, CTR_IV_BYTES);
171
- if (fin.length > 0) fin.copy(out2, CTR_IV_BYTES + enc2.length);
172
- return PREFIX_CTR + out2.toString("base64");
173
- }
174
- const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
175
- const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
176
- const iv = this._nextIV();
177
- const c = createCipheriv(algo, this._key, iv);
178
- const enc = c.update(plaintext, "utf8");
179
- c.final();
180
- const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
181
- iv.copy(out, 0);
182
- c.getAuthTag().copy(out, IV_BYTES);
183
- enc.copy(out, IV_BYTES + TAG_BYTES);
184
- return prefix + out.toString("base64");
185
- }
186
- /**
187
- * Decrypt a Redis value.
188
- * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
189
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
190
- */
191
- decrypt(value) {
192
- try {
193
- return this._decryptWithKey(value, this._key, this._mode);
194
- } catch (primaryErr) {
195
- if (this._prevKey) {
196
- try {
197
- return this._decryptWithKey(value, this._prevKey, this._prevMode);
198
- } catch {
199
- }
200
- }
201
- throw primaryErr;
202
- }
203
- }
204
- _decryptWithKey(value, key, mode) {
205
- if (value.startsWith(PREFIX_XOR)) {
206
- if (!key) throw new Error("Cannot decrypt: encryption key is not set");
207
- const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
208
- const klen = key.length;
209
- const len = masked.length;
210
- const out = Buffer.allocUnsafe(len);
211
- for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
212
- return out.toString("utf8");
213
- }
214
- if (value.startsWith(PREFIX_CTR)) {
215
- if (!key) throw new Error("Cannot decrypt: encryption key is not set");
216
- const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
217
- const iv2 = combined2.subarray(0, CTR_IV_BYTES);
218
- const ct2 = combined2.subarray(CTR_IV_BYTES);
219
- const d2 = createDecipheriv("aes-128-ctr", key, iv2);
220
- const plain2 = d2.update(ct2);
221
- const fin = d2.final();
222
- return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
223
- }
224
- const is256 = value.startsWith(PREFIX_256);
225
- const is128 = value.startsWith(PREFIX_128);
226
- if (!is256 && !is128) return value;
227
- if (!key) throw new Error("Cannot decrypt: encryption key is not set");
228
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
229
- const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
230
- const combined = Buffer.from(value.slice(prefix.length), "base64");
231
- const iv = combined.subarray(0, IV_BYTES);
232
- const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
233
- const ct = combined.subarray(IV_BYTES + TAG_BYTES);
234
- const d = createDecipheriv(algo, key, iv);
235
- d.setAuthTag(tag);
236
- const plain = d.update(ct);
237
- d.final();
238
- return plain.toString("utf8");
239
- void mode;
240
- }
241
- // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
242
- /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
243
- encryptBuffer(data) {
244
- if (!this._key) return data;
245
- if (this._mode === "xor") {
246
- const masked = this._xorBuffer(data);
247
- const out2 = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
248
- MAGIC_XOR.copy(out2, 0);
249
- masked.copy(out2, MAGIC_LEN);
250
- return out2;
251
- }
252
- if (this._mode === "aes-128-ctr") {
253
- const iv2 = this._nextCtrIV();
254
- const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
255
- const enc2 = c2.update(data);
256
- const fin = c2.final();
257
- const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
258
- MAGIC_CTR.copy(out2, 0);
259
- iv2.copy(out2, MAGIC_LEN);
260
- enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
261
- if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
262
- return out2;
263
- }
264
- const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
265
- const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
266
- const iv = this._nextIV();
267
- const c = createCipheriv(algo, this._key, iv);
268
- const enc = c.update(data);
269
- c.final();
270
- const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
271
- magic.copy(out, 0);
272
- iv.copy(out, MAGIC_LEN);
273
- c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
274
- enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
275
- return out;
276
- }
277
- /**
278
- * Decrypt a raw Buffer from disk/snapshot.
279
- * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
280
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
281
- */
282
- decryptBuffer(data) {
283
- try {
284
- return this._decryptBufferWithKey(data, this._key);
285
- } catch (primaryErr) {
286
- if (this._prevKey) {
287
- try {
288
- return this._decryptBufferWithKey(data, this._prevKey);
289
- } catch {
290
- }
291
- }
292
- throw primaryErr;
293
- }
294
- }
295
- _decryptBufferWithKey(data, key) {
296
- if (data.length < MAGIC_LEN) return data;
297
- const magic = data.subarray(0, MAGIC_LEN);
298
- if (magic.equals(MAGIC_XOR)) {
299
- if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
300
- const raw = data.subarray(MAGIC_LEN);
301
- const klen = key.length;
302
- const out = Buffer.allocUnsafe(raw.length);
303
- for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
304
- return out;
305
- }
306
- if (magic.equals(MAGIC_CTR)) {
307
- if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
308
- const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
309
- const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
310
- const d2 = createDecipheriv("aes-128-ctr", key, iv2);
311
- const plain2 = d2.update(ct2);
312
- const fin = d2.final();
313
- return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
314
- }
315
- const is256 = magic.equals(MAGIC_256);
316
- const is128 = magic.equals(MAGIC_128);
317
- if (!is256 && !is128) return data;
318
- if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
319
- const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
320
- const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
321
- const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
322
- const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
323
- const d = createDecipheriv(algo, key, iv);
324
- d.setAuthTag(tag);
325
- const plain = d.update(ct);
326
- d.final();
327
- return plain;
328
- }
329
- };
330
-
331
149
  // src/smart-memory-cache.ts
332
150
  import { pack, unpack } from "msgpackr";
333
151
 
@@ -397,6 +215,8 @@ var WasmBloomFilter = class {
397
215
  // src/smart-memory-cache.ts
398
216
  var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
399
217
  var EVICTION_BATCH_PERCENT = 0.2;
218
+ var EVICTION_SAMPLE = 16;
219
+ var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
400
220
  var JsBloomFilter = class {
401
221
  bits;
402
222
  numBits;
@@ -584,6 +404,15 @@ var SmartMemoryCache = class {
584
404
  categoryHits = /* @__PURE__ */ new Map();
585
405
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
586
406
  _bloomDirtyCount = 0;
407
+ /**
408
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
409
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
410
+ * that is overwritten in-place rather than replaced with a new object literal.
411
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
412
+ * any other code can observe the pool state.
413
+ */
414
+ _evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
415
+ _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
587
416
  constructor(opts, existing) {
588
417
  this.opts = opts;
589
418
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
@@ -647,8 +476,9 @@ var SmartMemoryCache = class {
647
476
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
648
477
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
649
478
  if (!catOvf && !glbOvf) {
650
- const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
651
- const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
479
+ const wm = this.opts.evictionWatermark ?? 0.9;
480
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
481
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
652
482
  if (entryWatermark || byteWatermark) {
653
483
  this.smartEvict(category, false);
654
484
  }
@@ -684,9 +514,9 @@ var SmartMemoryCache = class {
684
514
  }
685
515
  smartEvict(targetCat, catOvf) {
686
516
  const now = Date.now();
687
- const SAMPLE = 16;
688
- const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT));
689
- const pool = [];
517
+ const pool = this._evictPool;
518
+ const gPool = this._evictGPool;
519
+ let poolLen = 0;
690
520
  if (catOvf) {
691
521
  const catKeySet = this.categoryKeys.get(targetCat);
692
522
  if (catKeySet) {
@@ -696,36 +526,62 @@ var SmartMemoryCache = class {
696
526
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
697
527
  catSeen++;
698
528
  const s = this.score(entry, 100, now, key);
699
- if (pool.length < EVICT) {
700
- pool.push({ key, score: s });
529
+ if (poolLen < EVICT_COUNT) {
530
+ pool[poolLen].key = key;
531
+ pool[poolLen].score = s;
532
+ poolLen++;
701
533
  } else {
702
534
  const j = Math.floor(Math.random() * catSeen);
703
- if (j < EVICT) pool[j] = { key, score: s };
535
+ if (j < EVICT_COUNT) {
536
+ pool[j].key = key;
537
+ pool[j].score = s;
538
+ }
704
539
  }
705
540
  }
706
541
  }
707
542
  }
708
- if (pool.length < EVICT) {
709
- const remaining = SAMPLE - pool.length;
543
+ if (poolLen < EVICT_COUNT) {
544
+ const remaining = EVICTION_SAMPLE - poolLen;
710
545
  let globalSeen = 0;
711
- const globalPool = [];
546
+ let gLen = 0;
712
547
  for (const [key, entry] of this.cache) {
713
548
  if (entry.priority === 4 && entry.expiresAt > now) continue;
714
549
  if (catOvf && this.getCategory(key) === targetCat) continue;
715
550
  globalSeen++;
716
551
  const s = this.score(entry, 0, now, key);
717
- if (globalPool.length < remaining) {
718
- globalPool.push({ key, score: s });
552
+ if (gLen < remaining) {
553
+ gPool[gLen].key = key;
554
+ gPool[gLen].score = s;
555
+ gLen++;
719
556
  } else {
720
557
  const j = Math.floor(Math.random() * globalSeen);
721
- if (j < remaining) globalPool[j] = { key, score: s };
558
+ if (j < remaining) {
559
+ gPool[j].key = key;
560
+ gPool[j].score = s;
561
+ }
722
562
  }
723
563
  }
724
- pool.push(...globalPool);
564
+ for (let i = 0; i < gLen; i++) {
565
+ pool[poolLen].key = gPool[i].key;
566
+ pool[poolLen].score = gPool[i].score;
567
+ poolLen++;
568
+ }
569
+ }
570
+ if (poolLen === 0) return;
571
+ for (let i = 1; i < poolLen; i++) {
572
+ const sk = pool[i].key, ss = pool[i].score;
573
+ let j = i - 1;
574
+ while (j >= 0 && pool[j].score > ss) {
575
+ pool[j + 1].key = pool[j].key;
576
+ pool[j + 1].score = pool[j].score;
577
+ j--;
578
+ }
579
+ pool[j + 1].key = sk;
580
+ pool[j + 1].score = ss;
725
581
  }
726
- if (pool.length === 0) return;
727
- pool.sort((a, b) => a.score - b.score);
728
- for (const { key } of pool.slice(0, EVICT)) {
582
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
583
+ for (let i = 0; i < toEvict; i++) {
584
+ const key = pool[i].key;
729
585
  const entry = this.cache.get(key);
730
586
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
731
587
  this._delete(key, "capacity");
@@ -933,7 +789,39 @@ var SmartMemoryCache = class {
933
789
  }
934
790
  return cleaned;
935
791
  }
936
- // ── Snapshot import/export ────────────────────────────────────────────────
792
+ /**
793
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
794
+ *
795
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
796
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
797
+ * Entries written before the disconnect started may have been invalidated by
798
+ * peers while the backplane was down; evicting them forces a controlled
799
+ * cold-start re-fetch from L2 rather than serving silently stale data.
800
+ *
801
+ * Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
802
+ * Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
803
+ * conservatively.
804
+ *
805
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
806
+ * this time are evicted.
807
+ * @returns Number of entries evicted.
808
+ */
809
+ evictSetBefore(cutoffMs) {
810
+ let evicted = 0;
811
+ for (const [key, entry] of this.cache) {
812
+ if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
813
+ const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
814
+ if (setAt < cutoffMs) {
815
+ this._delete(key, "manual");
816
+ evicted++;
817
+ }
818
+ }
819
+ if (evicted > 0) {
820
+ this.bloom.rebuild(this.cache.keys());
821
+ this._bloomDirtyCount = 0;
822
+ }
823
+ return evicted;
824
+ }
937
825
  exportEntries(forbiddenPrefixes) {
938
826
  const now = Date.now();
939
827
  const out = [];
@@ -1130,10 +1018,17 @@ var SmartMemoryCache = class {
1130
1018
  import fs from "fs";
1131
1019
  import path from "path";
1132
1020
  import crypto from "crypto";
1021
+ import { createRequire } from "module";
1133
1022
  import { pack as pack2, unpack as unpack2 } from "msgpackr";
1023
+ var _SqliteDB = null;
1024
+ try {
1025
+ const _req = createRequire(import.meta.url);
1026
+ _SqliteDB = _req("node:sqlite").DatabaseSync;
1027
+ } catch {
1028
+ }
1134
1029
  var AES_ALGO = "aes-256-gcm";
1135
- var IV_BYTES2 = 12;
1136
- var TAG_BYTES2 = 16;
1030
+ var IV_BYTES = 12;
1031
+ var TAG_BYTES = 16;
1137
1032
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1138
1033
  var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1139
1034
  var V2_HEADER_LEN = 16;
@@ -1147,6 +1042,20 @@ var DiskTier = class {
1147
1042
  // maintained in-memory; avoids walkCacheFiles() in stats
1148
1043
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1149
1044
  _nextJanitorBucket = 0;
1045
+ // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1046
+ _db = null;
1047
+ _stmtInsert = null;
1048
+ // INSERT OR REPLACE
1049
+ _stmtSelect = null;
1050
+ // SELECT by key_hash
1051
+ _stmtDelete = null;
1052
+ // DELETE by key_hash
1053
+ _stmtExpire = null;
1054
+ // SELECT expired rows
1055
+ _stmtDelExp = null;
1056
+ // DELETE expired rows
1057
+ _stmtStats = null;
1058
+ // COUNT + SUM(size)
1150
1059
  constructor(opts) {
1151
1060
  this.opts = opts;
1152
1061
  }
@@ -1156,13 +1065,70 @@ var DiskTier = class {
1156
1065
  try {
1157
1066
  fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
1158
1067
  this.dirReady = true;
1068
+ this._initSqlite();
1159
1069
  } catch (err) {
1160
1070
  this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
1161
1071
  }
1162
1072
  }
1073
+ /**
1074
+ * Initialise the SQLite metadata index. Called once after the cache directory
1075
+ * is confirmed to exist. On any failure the instance silently falls back to
1076
+ * file-only mode — all public methods handle `this._db === null`.
1077
+ *
1078
+ * Schema:
1079
+ * meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
1080
+ * idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
1081
+ *
1082
+ * WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
1083
+ * most one WAL frame — acceptable data loss for an L1.5 spill store).
1084
+ */
1085
+ _initSqlite() {
1086
+ if (!_SqliteDB) return;
1087
+ try {
1088
+ const dbPath = path.join(this.opts.dir, "meta.db");
1089
+ this._db = new _SqliteDB(dbPath);
1090
+ this._db.exec(`
1091
+ PRAGMA journal_mode = WAL;
1092
+ PRAGMA synchronous = NORMAL;
1093
+ PRAGMA temp_store = MEMORY;
1094
+ CREATE TABLE IF NOT EXISTS meta (
1095
+ key_hash TEXT PRIMARY KEY,
1096
+ file_path TEXT NOT NULL,
1097
+ expires_at INTEGER NOT NULL,
1098
+ size INTEGER NOT NULL DEFAULT 0
1099
+ );
1100
+ CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
1101
+ `);
1102
+ this._stmtInsert = this._db.prepare(
1103
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
1104
+ );
1105
+ this._stmtSelect = this._db.prepare(
1106
+ "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
1107
+ );
1108
+ this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
1109
+ this._stmtExpire = this._db.prepare(
1110
+ "SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
1111
+ );
1112
+ this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
1113
+ this._stmtStats = this._db.prepare(
1114
+ "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1115
+ );
1116
+ const row = this._stmtStats.get();
1117
+ this.fileCount = row.cnt;
1118
+ this.diskUsageBytes = row.bytes;
1119
+ this.usageCounted = true;
1120
+ this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1121
+ } catch (err) {
1122
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1123
+ this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1124
+ error: err.message
1125
+ });
1126
+ }
1127
+ }
1163
1128
  ensureUsageCounted() {
1164
1129
  if (this.usageCounted) return;
1165
1130
  this.usageCounted = true;
1131
+ if (this._db) return;
1166
1132
  try {
1167
1133
  this.ensureDir();
1168
1134
  let total = 0;
@@ -1253,7 +1219,7 @@ var DiskTier = class {
1253
1219
  encrypt(data) {
1254
1220
  const key = this.opts.encryptionKey;
1255
1221
  if (!key) return data;
1256
- const iv = crypto.randomBytes(IV_BYTES2);
1222
+ const iv = crypto.randomBytes(IV_BYTES);
1257
1223
  const c = crypto.createCipheriv(AES_ALGO, key, iv);
1258
1224
  const enc = Buffer.concat([c.update(data), c.final()]);
1259
1225
  const tag = c.getAuthTag();
@@ -1264,9 +1230,9 @@ var DiskTier = class {
1264
1230
  if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
1265
1231
  const key = this.opts.encryptionKey;
1266
1232
  if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
1267
- const iv = data.subarray(mLen, mLen + IV_BYTES2);
1268
- const tag = data.subarray(mLen + IV_BYTES2, mLen + IV_BYTES2 + TAG_BYTES2);
1269
- const ct = data.subarray(mLen + IV_BYTES2 + TAG_BYTES2);
1233
+ const iv = data.subarray(mLen, mLen + IV_BYTES);
1234
+ const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
1235
+ const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
1270
1236
  const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1271
1237
  d.setAuthTag(tag);
1272
1238
  return Buffer.concat([d.update(ct), d.final()]);
@@ -1279,7 +1245,7 @@ var DiskTier = class {
1279
1245
  encryptV2(data) {
1280
1246
  const key = this.opts.encryptionKey;
1281
1247
  if (!key) return data;
1282
- const iv = crypto.randomBytes(IV_BYTES2);
1248
+ const iv = crypto.randomBytes(IV_BYTES);
1283
1249
  const c = crypto.createCipheriv(AES_ALGO, key, iv);
1284
1250
  const enc = Buffer.concat([c.update(data), c.final()]);
1285
1251
  const tag = c.getAuthTag();
@@ -1293,9 +1259,9 @@ var DiskTier = class {
1293
1259
  decryptV2(inner) {
1294
1260
  const key = this.opts.encryptionKey;
1295
1261
  if (!key) return inner;
1296
- const iv = inner.subarray(0, IV_BYTES2);
1297
- const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
1298
- const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
1262
+ const iv = inner.subarray(0, IV_BYTES);
1263
+ const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
1264
+ const ct = inner.subarray(IV_BYTES + TAG_BYTES);
1299
1265
  const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1300
1266
  d.setAuthTag(tag);
1301
1267
  return Buffer.concat([d.update(ct), d.final()]);
@@ -1350,10 +1316,17 @@ var DiskTier = class {
1350
1316
  try {
1351
1317
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
1352
1318
  await fs.promises.writeFile(filePath, final, { mode: 384 });
1319
+ if (this._db) {
1320
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1321
+ }
1353
1322
  this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1354
1323
  } catch (err) {
1355
1324
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1356
1325
  this.fileCount = Math.max(0, this.fileCount - 1);
1326
+ if (this._db) try {
1327
+ this._stmtDelete.run(hash);
1328
+ } catch {
1329
+ }
1357
1330
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1358
1331
  }
1359
1332
  }
@@ -1363,27 +1336,48 @@ var DiskTier = class {
1363
1336
  this.ensureDir();
1364
1337
  if (!this.dirReady) return null;
1365
1338
  const hash = this.keyToHash(key);
1366
- const filePath = this.findFilePath(hash);
1367
- if (!filePath) return null;
1339
+ let filePath;
1340
+ if (this._db) {
1341
+ const row = this._stmtSelect.get(hash);
1342
+ if (!row) return null;
1343
+ if (row.expires_at <= Date.now()) {
1344
+ this._stmtDelete.run(hash);
1345
+ try {
1346
+ const sz = fs.statSync(row.file_path).size;
1347
+ fs.unlinkSync(row.file_path);
1348
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1349
+ this.fileCount = Math.max(0, this.fileCount - 1);
1350
+ } catch {
1351
+ }
1352
+ return null;
1353
+ }
1354
+ filePath = row.file_path;
1355
+ } else {
1356
+ filePath = this.findFilePath(hash);
1357
+ if (!filePath) return null;
1358
+ }
1368
1359
  try {
1369
- const filename = path.basename(filePath);
1370
- if (filename.length === 77 && filename[64] === "_") {
1371
- const expiresAt = parseInt(filename.slice(65), 16);
1372
- if (expiresAt <= Date.now()) {
1373
- try {
1374
- const sz = fs.statSync(filePath).size;
1375
- fs.unlinkSync(filePath);
1376
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1377
- this.fileCount = Math.max(0, this.fileCount - 1);
1378
- } catch {
1360
+ if (!this._db) {
1361
+ const filename = path.basename(filePath);
1362
+ if (filename.length === 77 && filename[64] === "_") {
1363
+ const expiresAt = parseInt(filename.slice(65), 16);
1364
+ if (expiresAt <= Date.now()) {
1365
+ try {
1366
+ const sz = fs.statSync(filePath).size;
1367
+ fs.unlinkSync(filePath);
1368
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1369
+ this.fileCount = Math.max(0, this.fileCount - 1);
1370
+ } catch {
1371
+ }
1372
+ return null;
1379
1373
  }
1380
- return null;
1381
1374
  }
1382
1375
  }
1383
1376
  const stat = fs.statSync(filePath);
1384
1377
  if (stat.size > this.opts.entryMaxBytes) {
1385
1378
  fs.unlinkSync(filePath);
1386
1379
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1380
+ if (this._db) this._stmtDelete.run(hash);
1387
1381
  return null;
1388
1382
  }
1389
1383
  const raw = fs.readFileSync(filePath);
@@ -1393,6 +1387,7 @@ var DiskTier = class {
1393
1387
  this.fileCount = Math.max(0, this.fileCount - 1);
1394
1388
  } catch {
1395
1389
  }
1390
+ if (this._db) this._stmtDelete.run(hash);
1396
1391
  let decrypted;
1397
1392
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1398
1393
  const expiresAt = Number(raw.readBigUInt64LE(8));
@@ -1417,6 +1412,10 @@ var DiskTier = class {
1417
1412
  this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1418
1413
  return entry;
1419
1414
  } catch (err) {
1415
+ if (this._db) try {
1416
+ this._stmtDelete.run(hash);
1417
+ } catch {
1418
+ }
1420
1419
  this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1421
1420
  return null;
1422
1421
  }
@@ -1424,7 +1423,14 @@ var DiskTier = class {
1424
1423
  /** Explicitly delete a key from disk (cache invalidation). */
1425
1424
  delete(key) {
1426
1425
  const hash = this.keyToHash(key);
1427
- const filePath = this.findFilePath(hash);
1426
+ let filePath;
1427
+ if (this._db) {
1428
+ const row = this._stmtSelect.get(hash);
1429
+ filePath = row?.file_path ?? null;
1430
+ this._stmtDelete.run(hash);
1431
+ } else {
1432
+ filePath = this.findFilePath(hash);
1433
+ }
1428
1434
  if (!filePath) return;
1429
1435
  try {
1430
1436
  const stat = fs.statSync(filePath);
@@ -1438,6 +1444,20 @@ var DiskTier = class {
1438
1444
  purgeExpired() {
1439
1445
  this.ensureDir();
1440
1446
  if (!this.dirReady) return 0;
1447
+ if (this._db) {
1448
+ const now2 = Date.now();
1449
+ const expired = this._stmtExpire.all(now2);
1450
+ for (const row of expired) {
1451
+ try {
1452
+ fs.unlinkSync(row.file_path);
1453
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1454
+ this.fileCount = Math.max(0, this.fileCount - 1);
1455
+ } catch {
1456
+ }
1457
+ }
1458
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1459
+ return expired.length;
1460
+ }
1441
1461
  const now = Date.now();
1442
1462
  let purged = 0;
1443
1463
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
@@ -1513,22 +1533,64 @@ var DiskTier = class {
1513
1533
  return purged;
1514
1534
  }
1515
1535
  /**
1516
- * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1517
- * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1518
- * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1519
- * of landing as one large synchronous burst every 5 minutes.
1536
+ * Purge expired entries. Two modes depending on availability of SQLite:
1520
1537
  *
1521
- * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1522
- * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1538
+ * SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
1539
+ * One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
1540
+ * wheel. All expired entries are found and deleted in a single pass — the
1541
+ * 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
1542
+ * incremented so tests that inspect the counter continue to work.
1543
+ *
1544
+ * File-only fallback:
1545
+ * Original staggered bucket wheel — purges exactly one of 256 subdirectory
1546
+ * buckets per call, spreading the O(fileCount) work across 256 ticks.
1523
1547
  *
1524
1548
  * Returns the number of entries deleted in this tick.
1525
1549
  */
1526
1550
  purgeNextBucket() {
1527
1551
  this.ensureDir();
1528
1552
  if (!this.dirReady) return 0;
1529
- const bucket = this._nextJanitorBucket.toString(16).padStart(2, "0");
1530
1553
  this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1531
- const bucketPath = path.join(this.opts.dir, bucket);
1554
+ if (this._db) {
1555
+ const now2 = Date.now();
1556
+ const expired = this._stmtExpire.all(now2);
1557
+ for (const row of expired) {
1558
+ try {
1559
+ fs.unlinkSync(row.file_path);
1560
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1561
+ this.fileCount = Math.max(0, this.fileCount - 1);
1562
+ } catch {
1563
+ }
1564
+ }
1565
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1566
+ const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
1567
+ const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
1568
+ let orphanFiles;
1569
+ try {
1570
+ orphanFiles = fs.readdirSync(orphanBucketP);
1571
+ } catch {
1572
+ return expired.length;
1573
+ }
1574
+ for (const file of orphanFiles) {
1575
+ if (file.length === 77 && file[64] === "_") {
1576
+ const expiresAt = parseInt(file.slice(65), 16);
1577
+ if (expiresAt <= now2) {
1578
+ const fp = path.join(orphanBucketP, file);
1579
+ try {
1580
+ const sz = fs.statSync(fp).size;
1581
+ fs.unlinkSync(fp);
1582
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1583
+ this.fileCount = Math.max(0, this.fileCount - 1);
1584
+ } catch {
1585
+ }
1586
+ }
1587
+ }
1588
+ }
1589
+ return expired.length;
1590
+ }
1591
+ const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
1592
+ const bucketHex = bucket.toString(16).padStart(2, "0");
1593
+ const bucketPath = path.join(this.opts.dir, bucketHex);
1532
1594
  let files;
1533
1595
  try {
1534
1596
  files = fs.readdirSync(bucketPath);
@@ -1625,11 +1687,35 @@ var DiskTier = class {
1625
1687
  } catch {
1626
1688
  }
1627
1689
  }
1690
+ if (this._db) {
1691
+ this._db.exec("DELETE FROM meta");
1692
+ this.diskUsageBytes = 0;
1693
+ this.fileCount = 0;
1694
+ }
1628
1695
  return cleared;
1629
1696
  }
1630
1697
  get stats() {
1698
+ if (this._db) {
1699
+ const row = this._stmtStats.get();
1700
+ this.fileCount = row.cnt;
1701
+ this.diskUsageBytes = row.bytes;
1702
+ }
1631
1703
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1632
1704
  }
1705
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1706
+ get indexMode() {
1707
+ return this._db ? "sqlite" : "file-only";
1708
+ }
1709
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1710
+ close() {
1711
+ if (this._db) {
1712
+ try {
1713
+ this._db.close();
1714
+ } catch {
1715
+ }
1716
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1717
+ }
1718
+ }
1633
1719
  };
1634
1720
 
1635
1721
  // src/cache-service.ts
@@ -1687,6 +1773,89 @@ function deepFreeze(obj) {
1687
1773
  for (const v of Object.values(obj)) deepFreeze(v);
1688
1774
  return obj;
1689
1775
  }
1776
+ var LatencyTracker = class {
1777
+ samples;
1778
+ maxKeys;
1779
+ bufs = /* @__PURE__ */ new Map();
1780
+ meta = /* @__PURE__ */ new Map();
1781
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
1782
+ scratch;
1783
+ constructor(samples, maxKeys) {
1784
+ this.samples = samples;
1785
+ this.maxKeys = maxKeys;
1786
+ this.scratch = new Float64Array(samples);
1787
+ }
1788
+ record(key, deltaMs) {
1789
+ let buf = this.bufs.get(key);
1790
+ let m = this.meta.get(key);
1791
+ if (buf === void 0) {
1792
+ if (this.bufs.size >= this.maxKeys) {
1793
+ const oldest = this.bufs.keys().next().value;
1794
+ this.bufs.delete(oldest);
1795
+ this.meta.delete(oldest);
1796
+ }
1797
+ buf = new Float64Array(this.samples);
1798
+ m = { head: 0, count: 0, p95: 0, dirty: false };
1799
+ this.bufs.set(key, buf);
1800
+ this.meta.set(key, m);
1801
+ }
1802
+ buf[m.head] = deltaMs;
1803
+ m.head = (m.head + 1) % this.samples;
1804
+ if (m.count < this.samples) m.count++;
1805
+ m.dirty = true;
1806
+ }
1807
+ /**
1808
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
1809
+ * Uses the shared scratch buffer — no heap allocation.
1810
+ */
1811
+ _computeP95(buf, m) {
1812
+ const n = m.count;
1813
+ this.scratch.set(buf.subarray(0, n));
1814
+ const view = this.scratch.subarray(0, n);
1815
+ view.sort();
1816
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
1817
+ m.dirty = false;
1818
+ }
1819
+ /**
1820
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
1821
+ * fewer than 5 samples have been collected (not enough data yet).
1822
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
1823
+ */
1824
+ p95(key) {
1825
+ const buf = this.bufs.get(key);
1826
+ const m = this.meta.get(key);
1827
+ if (!buf || !m || m.count < 5) return null;
1828
+ if (m.dirty) this._computeP95(buf, m);
1829
+ return m.p95;
1830
+ }
1831
+ get trackedKeys() {
1832
+ return this.bufs.size;
1833
+ }
1834
+ /**
1835
+ * Top-20 slowest keys by p95, sorted descending.
1836
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
1837
+ *
1838
+ * Only dirty keys (those with new samples since the last call) pay the sort
1839
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
1840
+ * metrics() calls with no intervening fetches are essentially free.
1841
+ */
1842
+ snapshot(prefixLen, multiplierSec, minMs, maxMs) {
1843
+ const out = [];
1844
+ for (const [key, buf] of this.bufs) {
1845
+ const m = this.meta.get(key);
1846
+ if (m.count < 5) continue;
1847
+ if (m.dirty) this._computeP95(buf, m);
1848
+ const p95 = m.p95;
1849
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
1850
+ out.push({
1851
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
1852
+ p95Ms: Math.round(p95),
1853
+ adaptedTtlSec: Math.round(adaptedMs / 1e3)
1854
+ });
1855
+ }
1856
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
1857
+ }
1858
+ };
1690
1859
  function inferPriority(cacheKey) {
1691
1860
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1692
1861
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1694,11 +1863,25 @@ function inferPriority(cacheKey) {
1694
1863
  return 2 /* NORMAL */;
1695
1864
  }
1696
1865
  var GLOBAL_KEY = "__tricache_instance__";
1866
+ function detectServerlessRuntime() {
1867
+ if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
1868
+ if (process.env["K_SERVICE"]) return "Google Cloud Run";
1869
+ if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
1870
+ if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
1871
+ if (process.env["FLY_APP_NAME"]) return "Fly.io";
1872
+ if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
1873
+ if (process.env["VERCEL"]) return "Vercel";
1874
+ return null;
1875
+ }
1697
1876
  var CacheService = class _CacheService {
1698
1877
  logger;
1699
1878
  enc;
1700
1879
  l1;
1701
1880
  disk;
1881
+ /** When true, all disk-tier and snapshot operations are skipped. */
1882
+ _diskDisabled = false;
1883
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
1884
+ _workerPool = null;
1702
1885
  opts;
1703
1886
  /** Pre-computed once — opts.namespace never changes after construction. */
1704
1887
  _namespace;
@@ -1724,9 +1907,12 @@ var CacheService = class _CacheService {
1724
1907
  oomInterval = null;
1725
1908
  metricsInterval = null;
1726
1909
  _shutdownHandler = null;
1910
+ latencyTracker = null;
1727
1911
  instanceId;
1728
1912
  backplaneChannel;
1729
1913
  subClient = null;
1914
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
1915
+ _subDisconnectedAt = null;
1730
1916
  counters = {
1731
1917
  gets: 0,
1732
1918
  l1Hits: 0,
@@ -1794,17 +1980,50 @@ var CacheService = class _CacheService {
1794
1980
  staleIfError: options.staleIfError ?? 0,
1795
1981
  l2WriteMode: options.l2WriteMode ?? "read-write",
1796
1982
  instanceName: options.instanceName ?? "",
1983
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
1797
1984
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1798
1985
  tracer: options.tracer,
1799
1986
  notFoundTtl: options.notFoundTtl ?? 0,
1800
1987
  warmKeys: options.warmKeys,
1801
1988
  onHit: options.onHit,
1802
1989
  onMiss: options.onMiss,
1803
- frozen: options.frozen ?? false
1990
+ frozen: options.frozen ?? false,
1991
+ adaptiveTtl: options.adaptiveTtl ?? false,
1992
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
1993
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
1994
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
1995
+ workerThreads: options.workerThreads ?? false,
1996
+ workerThresholdBytes: options.workerThresholdBytes ?? 131072,
1997
+ // 128 KB
1998
+ workerPoolSize: options.workerPoolSize ?? 0,
1999
+ // 0 = auto (min(4, cpus))
2000
+ backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
2001
+ disableDisk: options.disableDisk ?? false,
2002
+ redisClusterNodes: options.redisClusterNodes,
2003
+ redisSentinel: options.redisSentinel
1804
2004
  };
1805
2005
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1806
2006
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1807
2007
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
2008
+ if (this.opts.adaptiveTtl) {
2009
+ const samples = options.adaptiveTtlSamples ?? 32;
2010
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
2011
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
2012
+ }
2013
+ let diskDisabled = this.opts.disableDisk;
2014
+ if (options.disableDisk === void 0) {
2015
+ const serverless = detectServerlessRuntime();
2016
+ if (serverless !== null) {
2017
+ diskDisabled = true;
2018
+ logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
2019
+ runtime: serverless,
2020
+ hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
2021
+ });
2022
+ }
2023
+ } else if (diskDisabled) {
2024
+ logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
2025
+ }
2026
+ this._diskDisabled = diskDisabled;
1808
2027
  this.disk = new DiskTier({
1809
2028
  dir: this.opts.diskCacheDir,
1810
2029
  maxBytes: this.opts.diskMaxBytes,
@@ -1814,12 +2033,14 @@ var CacheService = class _CacheService {
1814
2033
  logger
1815
2034
  });
1816
2035
  this._namespace = ns;
1817
- this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost;
2036
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
1818
2037
  this.l1 = new SmartMemoryCache({
1819
2038
  maxBytes: this.opts.l1MaxBytes,
1820
2039
  maxEntries: this.opts.l1MaxEntries,
1821
2040
  categories: this.opts.categoryLimits,
2041
+ evictionWatermark: this.opts.l1EvictionWatermark,
1822
2042
  diskSpill: (key, entry) => {
2043
+ if (this._diskDisabled) return;
1823
2044
  setImmediate(() => {
1824
2045
  void this.disk.save(key, entry);
1825
2046
  });
@@ -1829,28 +2050,53 @@ var CacheService = class _CacheService {
1829
2050
  });
1830
2051
  if (!this.snapshotLoaded) {
1831
2052
  this.snapshotLoaded = true;
1832
- this.loadSnapshot();
2053
+ if (!this._diskDisabled) this.loadSnapshot();
1833
2054
  }
1834
2055
  this._shutdownHandler = () => {
1835
- this.writeSnapshot();
2056
+ if (!this._diskDisabled) this.writeSnapshot();
1836
2057
  process.exit(0);
1837
2058
  };
1838
2059
  process.once("SIGTERM", this._shutdownHandler);
1839
2060
  process.once("SIGINT", this._shutdownHandler);
2061
+ if (this.opts.workerThreads && this.enc.isEnabled) {
2062
+ try {
2063
+ const encRef = this.enc;
2064
+ this._workerPool = new WorkerPool({
2065
+ keyBase64: encRef._key ? encRef._key.toString("base64") : "",
2066
+ mode: encRef._mode,
2067
+ prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
2068
+ prevMode: encRef._prevMode,
2069
+ size: this.opts.workerPoolSize || void 0
2070
+ });
2071
+ if (this._workerPool.isAvailable) {
2072
+ logger.info("tricache: worker-thread encryption pool active", {
2073
+ threshold: `${this.opts.workerThresholdBytes / 1024} KB`
2074
+ });
2075
+ } else {
2076
+ this._workerPool = null;
2077
+ logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
2078
+ }
2079
+ } catch {
2080
+ this._workerPool = null;
2081
+ logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
2082
+ }
2083
+ }
1840
2084
  this.cleanupInterval = setInterval(() => {
1841
2085
  const cleaned = this.l1.cleanup();
1842
2086
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
1843
2087
  }, 5 * 60 * 1e3);
1844
2088
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
1845
- this.diskJanitorInterval = setInterval(() => {
1846
- const purged = this.disk.purgeNextBucket();
1847
- if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
1848
- }, 3e4);
1849
- if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
2089
+ if (!this._diskDisabled) {
2090
+ this.diskJanitorInterval = setInterval(() => {
2091
+ const purged = this.disk.purgeNextBucket();
2092
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
2093
+ }, 3e4);
2094
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
2095
+ }
1850
2096
  if (this.opts.oomProtection) {
1851
2097
  this.oomInterval = setInterval(() => {
1852
- const mem = process.memoryUsage();
1853
- const used = mem.heapUsed / mem.heapTotal;
2098
+ const heap = v8.getHeapStatistics();
2099
+ const used = heap.used_heap_size / heap.heap_size_limit;
1854
2100
  if (used >= this.opts.oomHeapThreshold) {
1855
2101
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
1856
2102
  this.counters.oomEvictions++;
@@ -1958,18 +2204,60 @@ var CacheService = class _CacheService {
1958
2204
  initBackplane() {
1959
2205
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1960
2206
  if (this.subClient) return;
1961
- const sub = new RedisClient({
1962
- host: this.opts.redisHost,
1963
- port: this.opts.redisPort,
1964
- tls: this.opts.redisTls ? {} : void 0,
1965
- connectTimeout: 1e4,
1966
- lazyConnect: true,
1967
- maxRetriesPerRequest: null,
1968
- enableAutoPipelining: false,
1969
- family: 4,
1970
- retryStrategy: (times) => Math.min(times * 50, 2e3)
1971
- });
2207
+ let sub;
2208
+ if (this.opts.redisClusterNodes?.length) {
2209
+ sub = new RedisCluster(this.opts.redisClusterNodes, {
2210
+ redisOptions: {
2211
+ tls: this.opts.redisTls ? {} : void 0,
2212
+ connectTimeout: 1e4,
2213
+ maxRetriesPerRequest: null
2214
+ }
2215
+ });
2216
+ } else if (this.opts.redisSentinel) {
2217
+ sub = new RedisClient({
2218
+ sentinels: this.opts.redisSentinel.sentinels,
2219
+ name: this.opts.redisSentinel.name,
2220
+ tls: this.opts.redisTls ? {} : void 0,
2221
+ connectTimeout: 1e4,
2222
+ lazyConnect: true,
2223
+ maxRetriesPerRequest: null,
2224
+ enableAutoPipelining: false,
2225
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2226
+ });
2227
+ } else {
2228
+ sub = new RedisClient({
2229
+ host: this.opts.redisHost,
2230
+ port: this.opts.redisPort,
2231
+ tls: this.opts.redisTls ? {} : void 0,
2232
+ connectTimeout: 1e4,
2233
+ lazyConnect: true,
2234
+ maxRetriesPerRequest: null,
2235
+ enableAutoPipelining: false,
2236
+ family: 4,
2237
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2238
+ });
2239
+ }
1972
2240
  sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
2241
+ sub.on("close", () => {
2242
+ if (this._subDisconnectedAt === null) {
2243
+ this._subDisconnectedAt = Date.now();
2244
+ this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
2245
+ }
2246
+ });
2247
+ sub.on("ready", () => {
2248
+ if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
2249
+ const gapMs = Date.now() - this._subDisconnectedAt;
2250
+ if (gapMs > this.opts.backplaneMaxStalenessMs) {
2251
+ const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
2252
+ this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
2253
+ gapMs,
2254
+ evicted,
2255
+ hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
2256
+ });
2257
+ }
2258
+ this._subDisconnectedAt = null;
2259
+ }
2260
+ });
1973
2261
  sub.on("message", (_channel, message) => {
1974
2262
  this._handleBackplaneMessage(message);
1975
2263
  });
@@ -1992,7 +2280,9 @@ var CacheService = class _CacheService {
1992
2280
  this.counters.invReceived++;
1993
2281
  if (msg.op === "del") {
1994
2282
  this.l1.delete(msg.key);
1995
- setImmediate(() => this.disk.delete(msg.key));
2283
+ setImmediate(() => {
2284
+ if (!this._diskDisabled) this.disk.delete(msg.key);
2285
+ });
1996
2286
  this._cascadeDependencies(msg.key);
1997
2287
  } else if (msg.op === "del-glob") {
1998
2288
  this.l1.deletePattern(msg.key);
@@ -2016,26 +2306,85 @@ var CacheService = class _CacheService {
2016
2306
  } catch {
2017
2307
  }
2018
2308
  }
2309
+ /**
2310
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
2311
+ * For Cluster, iterates every master node independently (SCAN is node-local).
2312
+ */
2313
+ async _scanKeys(client, pattern) {
2314
+ const keys = [];
2315
+ if (client instanceof RedisCluster) {
2316
+ const masters = client.nodes("master");
2317
+ await Promise.all(masters.map(
2318
+ (node) => new Promise((resolve, reject) => {
2319
+ const stream = node.scanStream({ match: pattern, count: 100 });
2320
+ stream.on("data", (chunk) => keys.push(...chunk));
2321
+ stream.on("end", resolve);
2322
+ stream.on("error", reject);
2323
+ })
2324
+ ));
2325
+ } else {
2326
+ await new Promise((resolve, reject) => {
2327
+ const stream = client.scanStream({ match: pattern, count: 100 });
2328
+ stream.on("data", (chunk) => keys.push(...chunk));
2329
+ stream.on("end", resolve);
2330
+ stream.on("error", reject);
2331
+ });
2332
+ }
2333
+ return keys;
2334
+ }
2019
2335
  async getRedis() {
2020
2336
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
2021
2337
  if (this.redisConnecting) return this.redisConnecting;
2022
2338
  this.redisConnecting = (async () => {
2023
2339
  try {
2024
- const client = new RedisClient({
2025
- host: this.opts.redisHost,
2026
- port: this.opts.redisPort,
2027
- tls: this.opts.redisTls ? {} : void 0,
2028
- connectTimeout: 1e4,
2029
- lazyConnect: false,
2030
- maxRetriesPerRequest: 3,
2031
- enableAutoPipelining: true,
2032
- keepAlive: 3e4,
2033
- family: 4,
2034
- retryStrategy: (times) => Math.min(times * 50, 2e3)
2035
- });
2036
- client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2037
- client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
2038
- client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2340
+ let client;
2341
+ if (this.opts.redisClusterNodes?.length) {
2342
+ client = new RedisCluster(this.opts.redisClusterNodes, {
2343
+ redisOptions: {
2344
+ tls: this.opts.redisTls ? {} : void 0,
2345
+ connectTimeout: 1e4,
2346
+ maxRetriesPerRequest: 3,
2347
+ keepAlive: 3e4
2348
+ },
2349
+ enableAutoPipelining: true,
2350
+ retryDelayOnClusterDown: 200,
2351
+ retryDelayOnFailover: 1e3
2352
+ });
2353
+ client.on("connect", () => this.logger.info("Redis Cluster connected"));
2354
+ client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
2355
+ client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
2356
+ } else if (this.opts.redisSentinel) {
2357
+ client = new RedisClient({
2358
+ sentinels: this.opts.redisSentinel.sentinels,
2359
+ name: this.opts.redisSentinel.name,
2360
+ tls: this.opts.redisTls ? {} : void 0,
2361
+ connectTimeout: 1e4,
2362
+ lazyConnect: false,
2363
+ maxRetriesPerRequest: 3,
2364
+ enableAutoPipelining: true,
2365
+ keepAlive: 3e4,
2366
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2367
+ });
2368
+ client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
2369
+ client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
2370
+ client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
2371
+ } else {
2372
+ client = new RedisClient({
2373
+ host: this.opts.redisHost,
2374
+ port: this.opts.redisPort,
2375
+ tls: this.opts.redisTls ? {} : void 0,
2376
+ connectTimeout: 1e4,
2377
+ lazyConnect: false,
2378
+ maxRetriesPerRequest: 3,
2379
+ enableAutoPipelining: true,
2380
+ keepAlive: 3e4,
2381
+ family: 4,
2382
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
2383
+ });
2384
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
2385
+ client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
2386
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
2387
+ }
2039
2388
  await new Promise((resolve, reject) => {
2040
2389
  client.once("ready", resolve);
2041
2390
  client.once("error", reject);
@@ -2145,12 +2494,18 @@ var CacheService = class _CacheService {
2145
2494
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2146
2495
  const k = this.nk(cacheKey);
2147
2496
  this.counters.gets++;
2497
+ const optSwr = opts.swr ?? 0;
2498
+ const optPriority = opts.priority;
2499
+ const optRefreshAhead = opts.refreshAhead;
2500
+ const optXfetchBeta = opts.xfetchBeta;
2501
+ const optNotFoundTtl = opts.notFoundTtl;
2502
+ const optTags = opts.tags;
2148
2503
  const l1Hit = this.l1.get(k);
2149
2504
  if (l1Hit !== null) {
2150
2505
  if (l1Hit.isStale) {
2151
- const swrGraceMs2 = (opts.swr ?? 0) * 1e3;
2506
+ const swrGraceMs2 = optSwr * 1e3;
2152
2507
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
2153
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2508
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2154
2509
  this.revalidating.add(k);
2155
2510
  void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
2156
2511
  this.counters.swrRevalidations++;
@@ -2160,16 +2515,18 @@ var CacheService = class _CacheService {
2160
2515
  }
2161
2516
  } else {
2162
2517
  this.logger.debug("L1 hit");
2163
- if (opts.refreshAhead || opts.xfetchBeta) {
2518
+ const ra = optRefreshAhead;
2519
+ const xb = optXfetchBeta;
2520
+ if (ra || xb) {
2164
2521
  const now = l1Hit.fetchedAt ?? Date.now();
2165
2522
  const remaining = l1Hit.expiresAt - now;
2166
2523
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
2167
- const shouldRefreshAhead = !!opts.refreshAhead ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
2168
- const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
2524
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
2525
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
2169
2526
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2170
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2527
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2171
2528
  this.revalidating.add(k);
2172
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
2529
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
2173
2530
  this.counters.swrRevalidations++;
2174
2531
  this.logger.debug(
2175
2532
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -2185,15 +2542,20 @@ var CacheService = class _CacheService {
2185
2542
  return l1Hit.value;
2186
2543
  }
2187
2544
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2188
- const swrGraceMs = (opts.swr ?? 0) * 1e3;
2189
- const priority = opts.priority ?? inferPriority(cacheKey);
2545
+ const swrGraceMs = optSwr * 1e3;
2546
+ const priority = optPriority ?? inferPriority(cacheKey);
2190
2547
  if (!this._redisDisabled) {
2191
2548
  try {
2192
2549
  const client = await this.getRedis();
2193
2550
  const raw = await client.get(k);
2194
2551
  this.cb.onSuccess();
2195
2552
  if (raw) {
2196
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2553
+ let decrypted;
2554
+ if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
2555
+ decrypted = await this._workerPool.decrypt(raw);
2556
+ } else {
2557
+ decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2558
+ }
2197
2559
  const parsed = JSON.parse(decrypted);
2198
2560
  this.l1.set(k, parsed, ttlMs, priority);
2199
2561
  this.counters.l2Hits++;
@@ -2207,20 +2569,22 @@ var CacheService = class _CacheService {
2207
2569
  this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
2208
2570
  }
2209
2571
  }
2210
- const diskHit = this.disk.load(k);
2211
- if (diskHit !== null) {
2212
- const promoted = this.l1.importEntries(
2213
- [{ key: k, entry: diskHit }],
2214
- this.opts.forbiddenSnapshotPrefixes
2215
- );
2216
- if (promoted > 0) {
2217
- const l1Check = this.l1.get(k);
2218
- if (l1Check !== null) {
2219
- this.counters.diskHits++;
2220
- this.opts.onHit?.(cacheKey, "disk");
2221
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
2222
- span.setAttribute("cache.hit", "disk").end();
2223
- return l1Check.value;
2572
+ if (!this._diskDisabled) {
2573
+ const diskHit = this.disk.load(k);
2574
+ if (diskHit !== null) {
2575
+ const promoted = this.l1.importEntries(
2576
+ [{ key: k, entry: diskHit }],
2577
+ this.opts.forbiddenSnapshotPrefixes
2578
+ );
2579
+ if (promoted > 0) {
2580
+ const l1Check = this.l1.get(k);
2581
+ if (l1Check !== null) {
2582
+ this.counters.diskHits++;
2583
+ this.opts.onHit?.(cacheKey, "disk");
2584
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
2585
+ span.setAttribute("cache.hit", "disk").end();
2586
+ return l1Check.value;
2587
+ }
2224
2588
  }
2225
2589
  }
2226
2590
  }
@@ -2239,17 +2603,33 @@ var CacheService = class _CacheService {
2239
2603
  const fetchStart = Date.now();
2240
2604
  const data = await fetchFn();
2241
2605
  const delta = Date.now() - fetchStart;
2242
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
2243
- const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
2606
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
2607
+ let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
2608
+ if (this.latencyTracker && data != null) {
2609
+ this.latencyTracker.record(k, delta);
2610
+ const p95 = this.latencyTracker.p95(k);
2611
+ if (p95 !== null) {
2612
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
2613
+ effectiveTtl = Math.max(
2614
+ this.opts.adaptiveTtlMinMs,
2615
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
2616
+ );
2617
+ }
2618
+ }
2244
2619
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
2245
2620
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
2246
2621
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2247
- if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1e3));
2622
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
2248
2623
  if (!this._redisDisabled) {
2249
2624
  try {
2250
2625
  const client = await this.getRedis();
2251
2626
  const serialized = JSON.stringify(data);
2252
- const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2627
+ let toStore;
2628
+ if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
2629
+ toStore = await this._workerPool.encrypt(serialized);
2630
+ } else {
2631
+ toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2632
+ }
2253
2633
  await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
2254
2634
  this.cb.onSuccess();
2255
2635
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
@@ -2275,12 +2655,18 @@ var CacheService = class _CacheService {
2275
2655
  const data = await fetchFn();
2276
2656
  const delta = Date.now() - fetchStart;
2277
2657
  const staleAt = Date.now() + ttlMs;
2658
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2278
2659
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
2279
2660
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2280
2661
  try {
2281
2662
  const client = await this.getRedis();
2282
2663
  const s = JSON.stringify(data);
2283
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2664
+ let stored;
2665
+ if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
2666
+ stored = await this._workerPool.encrypt(s);
2667
+ } else {
2668
+ stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2669
+ }
2284
2670
  await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
2285
2671
  } catch {
2286
2672
  }
@@ -2327,7 +2713,12 @@ var CacheService = class _CacheService {
2327
2713
  try {
2328
2714
  const client = await this.getRedis();
2329
2715
  const s = JSON.stringify(data);
2330
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2716
+ let stored;
2717
+ if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
2718
+ stored = await this._workerPool.encrypt(s);
2719
+ } else {
2720
+ stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2721
+ }
2331
2722
  await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
2332
2723
  this.cb.onSuccess();
2333
2724
  } catch (err) {
@@ -2385,7 +2776,9 @@ var CacheService = class _CacheService {
2385
2776
  this.l1.deletePattern(k);
2386
2777
  } else {
2387
2778
  this.l1.delete(k);
2388
- setImmediate(() => this.disk.delete(k));
2779
+ setImmediate(() => {
2780
+ if (!this._diskDisabled) this.disk.delete(k);
2781
+ });
2389
2782
  this._cascadeDependencies(k);
2390
2783
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2391
2784
  }
@@ -2393,13 +2786,7 @@ var CacheService = class _CacheService {
2393
2786
  try {
2394
2787
  const client = await this.getRedis();
2395
2788
  if (isPattern) {
2396
- const stream = client.scanStream({ match: k, count: 100 });
2397
- const keys = [];
2398
- await new Promise((resolve, reject) => {
2399
- stream.on("data", (chunk) => keys.push(...chunk));
2400
- stream.on("end", resolve);
2401
- stream.on("error", reject);
2402
- });
2789
+ const keys = await this._scanKeys(client, k);
2403
2790
  if (keys.length > 0) await client.del(...keys);
2404
2791
  } else {
2405
2792
  await client.del(k);
@@ -2456,7 +2843,7 @@ var CacheService = class _CacheService {
2456
2843
  this.l1.deletePattern(k);
2457
2844
  } else {
2458
2845
  this.l1.clear();
2459
- this.disk.clear();
2846
+ if (!this._diskDisabled) this.disk.clear();
2460
2847
  this._l1Counters.clear();
2461
2848
  this.tagIndex.clear();
2462
2849
  }
@@ -2464,13 +2851,7 @@ var CacheService = class _CacheService {
2464
2851
  try {
2465
2852
  const client = await this.getRedis();
2466
2853
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
2467
- const stream = client.scanStream({ match: pattern, count: 100 });
2468
- const keys = [];
2469
- await new Promise((resolve, reject) => {
2470
- stream.on("data", (chunk) => keys.push(...chunk));
2471
- stream.on("end", resolve);
2472
- stream.on("error", reject);
2473
- });
2854
+ const keys = await this._scanKeys(client, pattern);
2474
2855
  if (keys.length > 0) await client.del(...keys);
2475
2856
  } catch (err) {
2476
2857
  this.logger.debug("clear: Redis unavailable", { error: err.message });
@@ -2698,13 +3079,7 @@ var CacheService = class _CacheService {
2698
3079
  try {
2699
3080
  const client = await this.getRedis();
2700
3081
  const nsPattern = this.nk(pattern);
2701
- const matchedKeys = [];
2702
- const stream = client.scanStream({ match: nsPattern, count: 100 });
2703
- await new Promise((resolve, reject) => {
2704
- stream.on("data", (chunk) => matchedKeys.push(...chunk));
2705
- stream.on("end", resolve);
2706
- stream.on("error", reject);
2707
- });
3082
+ const matchedKeys = await this._scanKeys(client, nsPattern);
2708
3083
  if (matchedKeys.length === 0) {
2709
3084
  this.cb.onSuccess();
2710
3085
  return 0;
@@ -2754,7 +3129,7 @@ var CacheService = class _CacheService {
2754
3129
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
2755
3130
  for (const k of members) {
2756
3131
  this.l1.delete(k);
2757
- this.disk.delete(k);
3132
+ if (!this._diskDisabled) this.disk.delete(k);
2758
3133
  }
2759
3134
  this.tagIndex.delete(tagKey);
2760
3135
  if (!this._redisDisabled) {
@@ -2965,7 +3340,7 @@ var CacheService = class _CacheService {
2965
3340
  for (const dep of dependents) {
2966
3341
  if (dep === deletedKey) continue;
2967
3342
  this.l1.delete(dep);
2968
- this.disk.delete(dep);
3343
+ if (!this._diskDisabled) this.disk.delete(dep);
2969
3344
  void this.publishInvalidation("del", dep);
2970
3345
  this.logger.debug("Dependency cascade: invalidated dependent key", {
2971
3346
  trigger: deletedKey.slice(0, 60),
@@ -3027,7 +3402,20 @@ var CacheService = class _CacheService {
3027
3402
  sizeBytes: this.l1.memoryUsage,
3028
3403
  maxBytes: this.opts.l1MaxBytes
3029
3404
  },
3030
- disk: this.disk.stats
3405
+ disk: { ...this.disk.stats, disabled: this._diskDisabled },
3406
+ ...this.latencyTracker && {
3407
+ adaptiveTtl: {
3408
+ enabled: true,
3409
+ trackedKeys: this.latencyTracker.trackedKeys,
3410
+ slowestKeys: this.latencyTracker.snapshot(
3411
+ this._namespace ? this._namespace.length + 1 : 0,
3412
+ // strip "namespace:" prefix
3413
+ this.opts.adaptiveTtlMultiplier,
3414
+ this.opts.adaptiveTtlMinMs,
3415
+ this.opts.adaptiveTtlMaxMs
3416
+ )
3417
+ }
3418
+ }
3031
3419
  };
3032
3420
  }
3033
3421
  /**
@@ -3104,6 +3492,10 @@ var CacheService = class _CacheService {
3104
3492
  process.off("SIGINT", this._shutdownHandler);
3105
3493
  this._shutdownHandler = null;
3106
3494
  }
3495
+ if (this._workerPool) {
3496
+ await this._workerPool.destroy();
3497
+ this._workerPool = null;
3498
+ }
3107
3499
  if (this.subClient) {
3108
3500
  try {
3109
3501
  await this.subClient.quit();
@@ -3118,6 +3510,7 @@ var CacheService = class _CacheService {
3118
3510
  }
3119
3511
  this.redis = null;
3120
3512
  }
3513
+ if (!this._diskDisabled) this.disk.close();
3121
3514
  }
3122
3515
  };
3123
3516
  export {