tricache 0.6.7 → 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.
- package/LICENSE +1 -1
- package/README.md +480 -22
- package/bin/tricache.js +8 -0
- package/dist/cache-service-AJASH5FX.js +7 -0
- package/dist/cache-service-BblHuF3i.d.ts +1476 -0
- package/dist/chunk-3XQUQBOZ.js +4583 -0
- package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
- package/dist/chunk-UBSR5UYA.js +0 -0
- package/dist/cli.cjs +5181 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.js +130 -0
- package/dist/drizzle/index.cjs +5161 -0
- package/dist/drizzle/index.d.ts +44 -0
- package/dist/drizzle/index.js +46 -0
- package/dist/http/index.cjs +5289 -0
- package/dist/http/index.d.ts +33 -0
- package/dist/http/index.js +172 -0
- package/dist/index.cjs +1173 -194
- package/dist/index.d.ts +15 -1230
- package/dist/index.js +11 -3705
- package/dist/nestjs/index.cjs +5305 -0
- package/dist/nestjs/index.d.ts +210 -0
- package/dist/nestjs/index.js +250 -0
- package/dist/next/index.cjs +5327 -0
- package/dist/next/index.d.ts +204 -0
- package/dist/next/index.js +274 -0
- package/dist/prisma/index.cjs +122 -0
- package/dist/prisma/index.d.ts +60 -0
- package/dist/prisma/index.js +86 -0
- package/dist/serialize-worker.cjs +177 -13
- package/dist/serialize-worker.js +63 -12
- package/package.json +69 -21
- package/src/cache-service.ts +987 -190
- package/src/cli.ts +143 -0
- package/src/compression.ts +63 -0
- package/src/disk-tier.ts +71 -7
- package/src/drizzle/index.ts +86 -0
- package/src/encryption.ts +56 -5
- package/src/http/index.ts +223 -0
- package/src/index.ts +7 -0
- package/src/nestjs/decorators.ts +161 -0
- package/src/nestjs/index.ts +23 -0
- package/src/nestjs/tricache.module.ts +104 -0
- package/src/nestjs/tricache.store.ts +97 -0
- package/src/nestjs/types.ts +79 -0
- package/src/next/cache-handler.ts +244 -0
- package/src/next/index.ts +37 -0
- package/src/next/isr-handler.ts +105 -0
- package/src/next/types.ts +130 -0
- package/src/prisma/index.ts +151 -0
- package/src/serialize-worker.ts +77 -13
- package/src/smart-memory-cache.ts +22 -8
- package/src/types.ts +172 -2
- package/src/wasm/bloom-filter-wasm.ts +3 -2
- 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
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
|
112
|
-
|
|
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
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
|
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: (
|
|
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,
|
|
270
|
-
|
|
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 =
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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
|
|
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
|
|
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
|
/**
|
|
@@ -2676,20 +3016,18 @@ var CacheService = class _CacheService {
|
|
|
2676
3016
|
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
2677
3017
|
return _CacheService._nullSpan;
|
|
2678
3018
|
}
|
|
2679
|
-
|
|
2680
|
-
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2681
|
-
if (this.subClient) return;
|
|
2682
|
-
let sub;
|
|
3019
|
+
createDedicatedRedisClient() {
|
|
2683
3020
|
if (this.opts.redisClusterNodes?.length) {
|
|
2684
|
-
|
|
3021
|
+
return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
2685
3022
|
redisOptions: {
|
|
2686
3023
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2687
3024
|
connectTimeout: 1e4,
|
|
2688
|
-
maxRetriesPerRequest: null
|
|
3025
|
+
maxRetriesPerRequest: null,
|
|
3026
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2689
3027
|
}
|
|
2690
3028
|
});
|
|
2691
3029
|
} else if (this.opts.redisSentinel) {
|
|
2692
|
-
|
|
3030
|
+
return new import_ioredis.Redis({
|
|
2693
3031
|
sentinels: this.opts.redisSentinel.sentinels,
|
|
2694
3032
|
name: this.opts.redisSentinel.name,
|
|
2695
3033
|
tls: this.opts.redisTls ? {} : void 0,
|
|
@@ -2697,10 +3035,11 @@ var CacheService = class _CacheService {
|
|
|
2697
3035
|
lazyConnect: true,
|
|
2698
3036
|
maxRetriesPerRequest: null,
|
|
2699
3037
|
enableAutoPipelining: false,
|
|
2700
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
3038
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
3039
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2701
3040
|
});
|
|
2702
3041
|
} else {
|
|
2703
|
-
|
|
3042
|
+
return new import_ioredis.Redis({
|
|
2704
3043
|
host: this.opts.redisHost,
|
|
2705
3044
|
port: this.opts.redisPort,
|
|
2706
3045
|
tls: this.opts.redisTls ? {} : void 0,
|
|
@@ -2709,10 +3048,24 @@ var CacheService = class _CacheService {
|
|
|
2709
3048
|
maxRetriesPerRequest: null,
|
|
2710
3049
|
enableAutoPipelining: false,
|
|
2711
3050
|
family: 4,
|
|
2712
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
3051
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
3052
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2713
3053
|
});
|
|
2714
3054
|
}
|
|
2715
|
-
|
|
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
|
+
});
|
|
2716
3069
|
sub.on("close", () => {
|
|
2717
3070
|
if (this._subDisconnectedAt === null) {
|
|
2718
3071
|
this._subDisconnectedAt = Date.now();
|
|
@@ -2733,22 +3086,127 @@ var CacheService = class _CacheService {
|
|
|
2733
3086
|
this._subDisconnectedAt = null;
|
|
2734
3087
|
}
|
|
2735
3088
|
});
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
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
|
+
}
|
|
2745
3111
|
this.subClient = sub;
|
|
2746
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
|
+
}
|
|
2747
3205
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
2748
3206
|
_handleBackplaneMessage(message) {
|
|
2749
3207
|
try {
|
|
2750
3208
|
const msg = JSON.parse(message);
|
|
2751
|
-
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob") {
|
|
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") {
|
|
2752
3210
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
2753
3211
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
2754
3212
|
});
|
|
@@ -2759,35 +3217,133 @@ var CacheService = class _CacheService {
|
|
|
2759
3217
|
return;
|
|
2760
3218
|
}
|
|
2761
3219
|
this.counters.invReceived++;
|
|
2762
|
-
|
|
2763
|
-
this.l1.delete(msg.key);
|
|
2764
|
-
setImmediate(() => {
|
|
2765
|
-
if (!this._diskDisabled) this.disk.delete(msg.key);
|
|
2766
|
-
});
|
|
2767
|
-
this._cascadeDependencies(msg.key);
|
|
2768
|
-
} else if (msg.op === "del-glob") {
|
|
2769
|
-
this.l1.deletePattern(msg.key);
|
|
2770
|
-
}
|
|
2771
|
-
this.logger.debug("Backplane: peer invalidation applied", {
|
|
2772
|
-
op: msg.op,
|
|
2773
|
-
key: msg.key.slice(0, 60)
|
|
2774
|
-
});
|
|
3220
|
+
this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === "number" ? msg.tagVersion : void 0);
|
|
2775
3221
|
} catch {
|
|
2776
3222
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2777
3223
|
}
|
|
2778
3224
|
}
|
|
2779
|
-
async publishInvalidation(op, key) {
|
|
3225
|
+
async publishInvalidation(op, key, tagVersion) {
|
|
2780
3226
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2781
3227
|
try {
|
|
2782
3228
|
const client = await this.getRedis();
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
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
|
+
}
|
|
2787
3263
|
this.counters.invSent++;
|
|
2788
3264
|
} catch {
|
|
2789
3265
|
}
|
|
2790
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
|
+
}
|
|
2791
3347
|
/**
|
|
2792
3348
|
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
2793
3349
|
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
@@ -2814,8 +3370,18 @@ var CacheService = class _CacheService {
|
|
|
2814
3370
|
}
|
|
2815
3371
|
return keys;
|
|
2816
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
|
+
}
|
|
2817
3382
|
async getRedis() {
|
|
2818
3383
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
3384
|
+
if (this.redis) return this.redis;
|
|
2819
3385
|
if (this.redisConnecting) return this.redisConnecting;
|
|
2820
3386
|
this.redisConnecting = (async () => {
|
|
2821
3387
|
try {
|
|
@@ -2826,14 +3392,18 @@ var CacheService = class _CacheService {
|
|
|
2826
3392
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2827
3393
|
connectTimeout: 1e4,
|
|
2828
3394
|
maxRetriesPerRequest: 3,
|
|
2829
|
-
keepAlive: 3e4
|
|
3395
|
+
keepAlive: 3e4,
|
|
3396
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2830
3397
|
},
|
|
2831
3398
|
enableAutoPipelining: true,
|
|
2832
3399
|
retryDelayOnClusterDown: 200,
|
|
2833
3400
|
retryDelayOnFailover: 1e3
|
|
2834
3401
|
});
|
|
2835
3402
|
client.on("connect", () => this.logger.info("Redis Cluster connected"));
|
|
2836
|
-
client.on("error", (e) =>
|
|
3403
|
+
client.on("error", (e) => {
|
|
3404
|
+
this._checkAndLogResp3Hint(e);
|
|
3405
|
+
this.logger.error("Redis Cluster error", {}, e);
|
|
3406
|
+
});
|
|
2837
3407
|
client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
|
|
2838
3408
|
} else if (this.opts.redisSentinel) {
|
|
2839
3409
|
client = new import_ioredis.Redis({
|
|
@@ -2845,10 +3415,14 @@ var CacheService = class _CacheService {
|
|
|
2845
3415
|
maxRetriesPerRequest: 3,
|
|
2846
3416
|
enableAutoPipelining: true,
|
|
2847
3417
|
keepAlive: 3e4,
|
|
2848
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
3418
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
3419
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2849
3420
|
});
|
|
2850
3421
|
client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
|
|
2851
|
-
client.on("error", (e) =>
|
|
3422
|
+
client.on("error", (e) => {
|
|
3423
|
+
this._checkAndLogResp3Hint(e);
|
|
3424
|
+
this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e);
|
|
3425
|
+
});
|
|
2852
3426
|
client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
|
|
2853
3427
|
} else {
|
|
2854
3428
|
client = new import_ioredis.Redis({
|
|
@@ -2861,15 +3435,22 @@ var CacheService = class _CacheService {
|
|
|
2861
3435
|
enableAutoPipelining: true,
|
|
2862
3436
|
keepAlive: 3e4,
|
|
2863
3437
|
family: 4,
|
|
2864
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
3438
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
3439
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2865
3440
|
});
|
|
2866
3441
|
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
2867
|
-
client.on("error", (e) =>
|
|
3442
|
+
client.on("error", (e) => {
|
|
3443
|
+
this._checkAndLogResp3Hint(e);
|
|
3444
|
+
this.logger.error("Redis error", { host: this.opts.redisHost }, e);
|
|
3445
|
+
});
|
|
2868
3446
|
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
2869
3447
|
}
|
|
2870
3448
|
await new Promise((resolve, reject) => {
|
|
2871
3449
|
client.once("ready", resolve);
|
|
2872
|
-
client.once("error",
|
|
3450
|
+
client.once("error", (e) => {
|
|
3451
|
+
this._checkAndLogResp3Hint(e);
|
|
3452
|
+
reject(e);
|
|
3453
|
+
});
|
|
2873
3454
|
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
2874
3455
|
});
|
|
2875
3456
|
this.cb.onSuccess();
|
|
@@ -2879,6 +3460,7 @@ var CacheService = class _CacheService {
|
|
|
2879
3460
|
} catch (err) {
|
|
2880
3461
|
this.cb.onFailure();
|
|
2881
3462
|
this.redisConnecting = null;
|
|
3463
|
+
this._checkAndLogResp3Hint(err);
|
|
2882
3464
|
throw err;
|
|
2883
3465
|
}
|
|
2884
3466
|
})();
|
|
@@ -2893,6 +3475,7 @@ var CacheService = class _CacheService {
|
|
|
2893
3475
|
const packed = (0, import_msgpackr3.pack)(payload);
|
|
2894
3476
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
2895
3477
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3478
|
+
import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
|
|
2896
3479
|
import_fs3.default.writeFileSync(dest, final, { mode: 384 });
|
|
2897
3480
|
this.logger.info("Cache snapshot written", {
|
|
2898
3481
|
path: dest,
|
|
@@ -2984,44 +3567,58 @@ var CacheService = class _CacheService {
|
|
|
2984
3567
|
const optTags = opts.tags;
|
|
2985
3568
|
const l1Hit = this.l1.get(k);
|
|
2986
3569
|
if (l1Hit !== null) {
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
const
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
} else {
|
|
2996
|
-
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
|
+
}
|
|
2997
3578
|
}
|
|
3579
|
+
}
|
|
3580
|
+
if (isGenerationalStale) {
|
|
3581
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
2998
3582
|
} else {
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
if (ra || xb) {
|
|
3003
|
-
const now = l1Hit.fetchedAt ?? Date.now();
|
|
3004
|
-
const remaining = l1Hit.expiresAt - now;
|
|
3005
|
-
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
|
|
3006
|
-
const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
|
|
3007
|
-
const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
|
|
3008
|
-
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
3583
|
+
if (l1Hit.isStale) {
|
|
3584
|
+
const swrGraceMs2 = optSwr * 1e3;
|
|
3585
|
+
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
3009
3586
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3010
3587
|
this.revalidating.add(k);
|
|
3011
|
-
void this._revalidate(k, fetchFn,
|
|
3588
|
+
void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
|
|
3012
3589
|
this.counters.swrRevalidations++;
|
|
3013
|
-
this.logger.debug(
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
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
|
+
}
|
|
3017
3614
|
}
|
|
3018
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;
|
|
3019
3621
|
}
|
|
3020
|
-
this.counters.l1Hits++;
|
|
3021
|
-
this.opts.onHit?.(cacheKey, "l1");
|
|
3022
|
-
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3023
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
3024
|
-
return l1Hit.value;
|
|
3025
3622
|
}
|
|
3026
3623
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3027
3624
|
const swrGraceMs = optSwr * 1e3;
|
|
@@ -3029,22 +3626,52 @@ var CacheService = class _CacheService {
|
|
|
3029
3626
|
if (!this._redisDisabled) {
|
|
3030
3627
|
try {
|
|
3031
3628
|
const client = await this.getRedis();
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
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;
|
|
3040
3674
|
}
|
|
3041
|
-
const parsed = JSON.parse(decrypted);
|
|
3042
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
3043
|
-
this.counters.l2Hits++;
|
|
3044
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3045
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3046
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3047
|
-
return parsed;
|
|
3048
3675
|
}
|
|
3049
3676
|
} catch (err) {
|
|
3050
3677
|
this.cb.onFailure();
|
|
@@ -3054,18 +3681,33 @@ var CacheService = class _CacheService {
|
|
|
3054
3681
|
if (!this._diskDisabled) {
|
|
3055
3682
|
const diskHit = this.disk.load(k);
|
|
3056
3683
|
if (diskHit !== null) {
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
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
|
+
}
|
|
3069
3711
|
}
|
|
3070
3712
|
}
|
|
3071
3713
|
}
|
|
@@ -3100,19 +3742,37 @@ var CacheService = class _CacheService {
|
|
|
3100
3742
|
}
|
|
3101
3743
|
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
3102
3744
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
3103
|
-
|
|
3104
|
-
if (optTags?.length)
|
|
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);
|
|
3105
3757
|
if (!this._redisDisabled) {
|
|
3106
3758
|
try {
|
|
3107
3759
|
const client = await this.getRedis();
|
|
3108
3760
|
const serialized = JSON.stringify(data);
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
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();
|
|
3112
3773
|
} else {
|
|
3113
|
-
|
|
3774
|
+
await client.setex(k, ttlSec, toStore);
|
|
3114
3775
|
}
|
|
3115
|
-
await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
|
|
3116
3776
|
this.cb.onSuccess();
|
|
3117
3777
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
3118
3778
|
} catch {
|
|
@@ -3122,7 +3782,8 @@ var CacheService = class _CacheService {
|
|
|
3122
3782
|
} else {
|
|
3123
3783
|
this.logger.debug("Cached L1", { cacheKey });
|
|
3124
3784
|
}
|
|
3125
|
-
|
|
3785
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
3786
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
3126
3787
|
} finally {
|
|
3127
3788
|
this.inflight.delete(k);
|
|
3128
3789
|
span.end();
|
|
@@ -3131,6 +3792,27 @@ var CacheService = class _CacheService {
|
|
|
3131
3792
|
this.inflight.set(k, fetchPromise);
|
|
3132
3793
|
return fetchPromise;
|
|
3133
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
|
+
}
|
|
3134
3816
|
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
3135
3817
|
try {
|
|
3136
3818
|
const fetchStart = Date.now();
|
|
@@ -3138,18 +3820,34 @@ var CacheService = class _CacheService {
|
|
|
3138
3820
|
const delta = Date.now() - fetchStart;
|
|
3139
3821
|
const staleAt = Date.now() + ttlMs;
|
|
3140
3822
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
3141
|
-
|
|
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);
|
|
3142
3832
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3143
3833
|
try {
|
|
3144
3834
|
const client = await this.getRedis();
|
|
3145
3835
|
const s = JSON.stringify(data);
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
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();
|
|
3149
3848
|
} else {
|
|
3150
|
-
|
|
3849
|
+
await client.setex(cacheKey, ttlSec, stored);
|
|
3151
3850
|
}
|
|
3152
|
-
await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
|
|
3153
3851
|
} catch {
|
|
3154
3852
|
}
|
|
3155
3853
|
}
|
|
@@ -3178,8 +3876,18 @@ var CacheService = class _CacheService {
|
|
|
3178
3876
|
const p = priority ?? inferPriority(cacheKey);
|
|
3179
3877
|
const k = this.nk(cacheKey);
|
|
3180
3878
|
this.counters.sets++;
|
|
3181
|
-
|
|
3182
|
-
if (opts?.tags?.length)
|
|
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);
|
|
3183
3891
|
if (opts?.dependsOn?.length) {
|
|
3184
3892
|
for (const pattern of opts.dependsOn) {
|
|
3185
3893
|
const nsPattern = this.nk(pattern);
|
|
@@ -3195,13 +3903,21 @@ var CacheService = class _CacheService {
|
|
|
3195
3903
|
try {
|
|
3196
3904
|
const client = await this.getRedis();
|
|
3197
3905
|
const s = JSON.stringify(data);
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
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();
|
|
3201
3918
|
} else {
|
|
3202
|
-
|
|
3919
|
+
await client.setex(k, ttlSec, stored);
|
|
3203
3920
|
}
|
|
3204
|
-
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
3205
3921
|
this.cb.onSuccess();
|
|
3206
3922
|
} catch (err) {
|
|
3207
3923
|
this.cb.onFailure();
|
|
@@ -3310,7 +4026,7 @@ var CacheService = class _CacheService {
|
|
|
3310
4026
|
);
|
|
3311
4027
|
}
|
|
3312
4028
|
const now = Date.now();
|
|
3313
|
-
const ttlMs = (ttlSeconds ??
|
|
4029
|
+
const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1e3;
|
|
3314
4030
|
const entry = this._l1Counters.get(k);
|
|
3315
4031
|
if (entry && entry.expiresAt > now) {
|
|
3316
4032
|
entry.value++;
|
|
@@ -3350,6 +4066,7 @@ var CacheService = class _CacheService {
|
|
|
3350
4066
|
if (!this._diskDisabled) this.disk.clear();
|
|
3351
4067
|
this._l1Counters.clear();
|
|
3352
4068
|
this.tagIndex.clear();
|
|
4069
|
+
this.tagVersions.clear();
|
|
3353
4070
|
}
|
|
3354
4071
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3355
4072
|
try {
|
|
@@ -3397,9 +4114,10 @@ var CacheService = class _CacheService {
|
|
|
3397
4114
|
* for (const key of cache.keys()) console.log(key);
|
|
3398
4115
|
*/
|
|
3399
4116
|
*keys() {
|
|
3400
|
-
const
|
|
4117
|
+
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3401
4118
|
for (const key of this.l1.liveKeys()) {
|
|
3402
|
-
|
|
4119
|
+
if (prefix && !key.startsWith(prefix)) continue;
|
|
4120
|
+
yield prefix ? key.slice(prefix.length) : key;
|
|
3403
4121
|
}
|
|
3404
4122
|
}
|
|
3405
4123
|
/**
|
|
@@ -3410,7 +4128,15 @@ var CacheService = class _CacheService {
|
|
|
3410
4128
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
3411
4129
|
*/
|
|
3412
4130
|
*values() {
|
|
3413
|
-
|
|
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
|
+
}
|
|
3414
4140
|
}
|
|
3415
4141
|
/**
|
|
3416
4142
|
* Lazily yield every non-expired L1 [key, value] pair.
|
|
@@ -3420,10 +4146,10 @@ var CacheService = class _CacheService {
|
|
|
3420
4146
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
3421
4147
|
*/
|
|
3422
4148
|
*entries() {
|
|
3423
|
-
const
|
|
4149
|
+
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3424
4150
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
3425
|
-
|
|
3426
|
-
yield [
|
|
4151
|
+
if (prefix && !key.startsWith(prefix)) continue;
|
|
4152
|
+
yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry)];
|
|
3427
4153
|
}
|
|
3428
4154
|
}
|
|
3429
4155
|
/**
|
|
@@ -3488,6 +4214,63 @@ var CacheService = class _CacheService {
|
|
|
3488
4214
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
3489
4215
|
return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
3490
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
|
+
}
|
|
3491
4274
|
/**
|
|
3492
4275
|
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
3493
4276
|
* Preserves input ordering. Uses inflight coalescing per key.
|
|
@@ -3498,7 +4281,7 @@ var CacheService = class _CacheService {
|
|
|
3498
4281
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
3499
4282
|
*/
|
|
3500
4283
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
3501
|
-
const result =
|
|
4284
|
+
const result = Array.from({ length: keys.length });
|
|
3502
4285
|
const missIndexes = [];
|
|
3503
4286
|
const missKeys = [];
|
|
3504
4287
|
for (let i = 0; i < keys.length; i++) {
|
|
@@ -3525,13 +4308,7 @@ var CacheService = class _CacheService {
|
|
|
3525
4308
|
const raw = raws[j] ? raws[j][1] : null;
|
|
3526
4309
|
const idx = missIndexes[j];
|
|
3527
4310
|
if (raw) {
|
|
3528
|
-
|
|
3529
|
-
if (this.enc.isEnabled) {
|
|
3530
|
-
const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
|
|
3531
|
-
parsed = JSON.parse(decrypted);
|
|
3532
|
-
} else {
|
|
3533
|
-
parsed = JSON.parse(raw);
|
|
3534
|
-
}
|
|
4311
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3535
4312
|
const k = nsKeys[j];
|
|
3536
4313
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
3537
4314
|
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
@@ -3663,12 +4440,10 @@ var CacheService = class _CacheService {
|
|
|
3663
4440
|
const [err, raw] = results[i];
|
|
3664
4441
|
if (err || raw == null) continue;
|
|
3665
4442
|
try {
|
|
3666
|
-
const
|
|
3667
|
-
const parsed = JSON.parse(decrypted);
|
|
4443
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3668
4444
|
const remainingMs = 10 * 60 * 1e3;
|
|
3669
4445
|
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
3670
4446
|
loaded++;
|
|
3671
|
-
;
|
|
3672
4447
|
} catch {
|
|
3673
4448
|
}
|
|
3674
4449
|
}
|
|
@@ -3694,6 +4469,25 @@ var CacheService = class _CacheService {
|
|
|
3694
4469
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
3695
4470
|
*/
|
|
3696
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
|
+
}
|
|
3697
4491
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
3698
4492
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
3699
4493
|
for (const k of members) {
|
|
@@ -3734,6 +4528,32 @@ var CacheService = class _CacheService {
|
|
|
3734
4528
|
await this.invalidateTag(tags[0]);
|
|
3735
4529
|
return;
|
|
3736
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
|
+
}
|
|
3737
4557
|
const tagKeys = [];
|
|
3738
4558
|
const allMembers = /* @__PURE__ */ new Set();
|
|
3739
4559
|
for (const tag of tags) {
|
|
@@ -3768,6 +4588,12 @@ var CacheService = class _CacheService {
|
|
|
3768
4588
|
}
|
|
3769
4589
|
}
|
|
3770
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
|
+
}
|
|
3771
4597
|
/**
|
|
3772
4598
|
* Measure L1 / disk / Redis latency.
|
|
3773
4599
|
* Useful for health checks and dashboards.
|
|
@@ -3866,6 +4692,132 @@ var CacheService = class _CacheService {
|
|
|
3866
4692
|
this.counters.sets++;
|
|
3867
4693
|
return true;
|
|
3868
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
|
+
}
|
|
3869
4821
|
// ── Hot key introspection ─────────────────────────────────────────────
|
|
3870
4822
|
/**
|
|
3871
4823
|
* Return the top-N live L1 keys by historical access frequency.
|
|
@@ -3896,18 +4848,20 @@ var CacheService = class _CacheService {
|
|
|
3896
4848
|
*/
|
|
3897
4849
|
_matchesGlob(key, pattern) {
|
|
3898
4850
|
if (!pattern.includes("*")) return key === pattern;
|
|
3899
|
-
|
|
3900
|
-
return re.test(key);
|
|
4851
|
+
return getGlobRegex(pattern).test(key);
|
|
3901
4852
|
}
|
|
3902
4853
|
/**
|
|
3903
4854
|
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
3904
4855
|
* that was registered via `dependsOn` and whose source pattern matches.
|
|
4856
|
+
* Transitive dependencies are traversed with cycle protection via a visited Set.
|
|
3905
4857
|
*/
|
|
3906
|
-
_cascadeDependencies(deletedKey) {
|
|
4858
|
+
_cascadeDependencies(deletedKey, visited = /* @__PURE__ */ new Set()) {
|
|
4859
|
+
if (visited.has(deletedKey)) return;
|
|
4860
|
+
visited.add(deletedKey);
|
|
3907
4861
|
for (const [pattern, dependents] of this.dependencyIndex) {
|
|
3908
4862
|
if (!this._matchesGlob(deletedKey, pattern)) continue;
|
|
3909
4863
|
for (const dep of dependents) {
|
|
3910
|
-
if (dep
|
|
4864
|
+
if (visited.has(dep)) continue;
|
|
3911
4865
|
this.l1.delete(dep);
|
|
3912
4866
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
3913
4867
|
void this.publishInvalidation("del", dep);
|
|
@@ -3915,6 +4869,7 @@ var CacheService = class _CacheService {
|
|
|
3915
4869
|
trigger: deletedKey.slice(0, 60),
|
|
3916
4870
|
dependent: dep.slice(0, 60)
|
|
3917
4871
|
});
|
|
4872
|
+
this._cascadeDependencies(dep, visited);
|
|
3918
4873
|
}
|
|
3919
4874
|
}
|
|
3920
4875
|
}
|
|
@@ -3958,9 +4913,13 @@ var CacheService = class _CacheService {
|
|
|
3958
4913
|
},
|
|
3959
4914
|
backplane: {
|
|
3960
4915
|
enabled: this.opts.invalidationBackplane && !this._redisDisabled,
|
|
4916
|
+
mode: this.opts.backplaneMode,
|
|
3961
4917
|
sent: c.invSent,
|
|
3962
4918
|
received: c.invReceived,
|
|
3963
|
-
skipped: c.invSkipped
|
|
4919
|
+
skipped: c.invSkipped,
|
|
4920
|
+
streamEntriesReceived: c.streamEntriesReceived,
|
|
4921
|
+
streamReplays: c.streamReplays,
|
|
4922
|
+
streamGaps: c.streamGaps
|
|
3964
4923
|
},
|
|
3965
4924
|
l2CircuitBreaker: {
|
|
3966
4925
|
state: this.cb.currentState
|
|
@@ -4054,8 +5013,21 @@ var CacheService = class _CacheService {
|
|
|
4054
5013
|
return lines.join("\n");
|
|
4055
5014
|
}
|
|
4056
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
|
+
}
|
|
4057
5028
|
/** Close Redis connections and stop all background timers. */
|
|
4058
5029
|
async destroy() {
|
|
5030
|
+
this._destroyed = true;
|
|
4059
5031
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
4060
5032
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
4061
5033
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
@@ -4071,11 +5043,18 @@ var CacheService = class _CacheService {
|
|
|
4071
5043
|
}
|
|
4072
5044
|
if (this.subClient) {
|
|
4073
5045
|
try {
|
|
4074
|
-
|
|
5046
|
+
this.subClient.disconnect();
|
|
4075
5047
|
} catch {
|
|
4076
5048
|
}
|
|
4077
5049
|
this.subClient = null;
|
|
4078
5050
|
}
|
|
5051
|
+
if (this.streamClient) {
|
|
5052
|
+
try {
|
|
5053
|
+
this.streamClient.disconnect();
|
|
5054
|
+
} catch {
|
|
5055
|
+
}
|
|
5056
|
+
this.streamClient = null;
|
|
5057
|
+
}
|
|
4079
5058
|
if (this.redis) {
|
|
4080
5059
|
try {
|
|
4081
5060
|
await this.redis.disconnect();
|