tricache 0.4.0 → 0.5.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/README.md +63 -27
- package/dist/cache-service.d.ts +366 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1494 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +83 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +324 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +88 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +371 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +51 -23
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +18 -1146
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -2697
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +178 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +753 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +428 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +20 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm/bloom-filter-wasm.d.ts +29 -0
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -0
- package/dist/wasm/bloom-filter-wasm.js +99 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +10 -11
- package/src/cache-service.ts +36 -4
- package/src/smart-memory-cache.ts +36 -27
- package/src/types.ts +6 -0
package/dist/index.js
CHANGED
|
@@ -1,2697 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
import { createCipheriv, createDecipheriv, randomFillSync } from "crypto";
|
|
27
|
-
var IV_BYTES = 12;
|
|
28
|
-
var TAG_BYTES = 16;
|
|
29
|
-
var PREFIX_256 = "enc:v1:";
|
|
30
|
-
var PREFIX_128 = "a128:v1:";
|
|
31
|
-
var PREFIX_XOR = "xor:v1:";
|
|
32
|
-
var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
|
|
33
|
-
var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
|
|
34
|
-
var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
|
|
35
|
-
var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
|
|
36
|
-
var MAGIC_LEN = 8;
|
|
37
|
-
var CTR_IV_BYTES = 16;
|
|
38
|
-
var PREFIX_CTR = "ctr:v1:";
|
|
39
|
-
var IV_POOL_COUNT = 64;
|
|
40
|
-
var CacheEncryption = class {
|
|
41
|
-
_key = null;
|
|
42
|
-
_mode;
|
|
43
|
-
_prevKey = null;
|
|
44
|
-
_prevMode = "aes-256-gcm";
|
|
45
|
-
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
46
|
-
_ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
47
|
-
_ivOffset = IV_BYTES * IV_POOL_COUNT;
|
|
48
|
-
// start exhausted → fill on first use
|
|
49
|
-
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
50
|
-
_nextIV() {
|
|
51
|
-
if (this._ivOffset >= this._ivPool.length) {
|
|
52
|
-
randomFillSync(this._ivPool);
|
|
53
|
-
this._ivOffset = 0;
|
|
54
|
-
}
|
|
55
|
-
const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES);
|
|
56
|
-
this._ivOffset += IV_BYTES;
|
|
57
|
-
return iv;
|
|
58
|
-
}
|
|
59
|
-
// Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
|
|
60
|
-
_ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
|
|
61
|
-
_ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
|
|
62
|
-
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
63
|
-
_nextCtrIV() {
|
|
64
|
-
if (this._ctrIvOffset >= this._ctrIvPool.length) {
|
|
65
|
-
randomFillSync(this._ctrIvPool);
|
|
66
|
-
this._ctrIvOffset = 0;
|
|
67
|
-
}
|
|
68
|
-
const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
|
|
69
|
-
this._ctrIvOffset += CTR_IV_BYTES;
|
|
70
|
-
return iv;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* XOR `data` with the key, cycling through key bytes.
|
|
74
|
-
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
75
|
-
*
|
|
76
|
-
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
77
|
-
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
78
|
-
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
79
|
-
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
80
|
-
*
|
|
81
|
-
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
82
|
-
*/
|
|
83
|
-
_xorBuffer(data) {
|
|
84
|
-
const key = this._key;
|
|
85
|
-
const klen = key.length;
|
|
86
|
-
const len = data.length;
|
|
87
|
-
const out = Buffer.allocUnsafe(len);
|
|
88
|
-
if (klen % 4 === 0 && len >= 4 && data.byteOffset % 4 === 0 && out.byteOffset % 4 === 0 && key.byteOffset % 4 === 0) {
|
|
89
|
-
const wordCount = len >>> 2;
|
|
90
|
-
const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
|
|
91
|
-
const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
|
|
92
|
-
const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
|
|
93
|
-
const kLen32 = key32.length;
|
|
94
|
-
for (let i = 0; i < wordCount; i++) {
|
|
95
|
-
out32[i] = data32[i] ^ key32[i % kLen32];
|
|
96
|
-
}
|
|
97
|
-
for (let i = wordCount << 2; i < len; i++) {
|
|
98
|
-
out[i] = data[i] ^ key[i % klen];
|
|
99
|
-
}
|
|
100
|
-
return out;
|
|
101
|
-
}
|
|
102
|
-
for (let i = 0; i < len; i++) {
|
|
103
|
-
out[i] = data[i] ^ key[i % klen];
|
|
104
|
-
}
|
|
105
|
-
return out;
|
|
106
|
-
}
|
|
107
|
-
constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
108
|
-
this._mode = mode;
|
|
109
|
-
if (!keyBase64) {
|
|
110
|
-
if (process.env.NODE_ENV === "production") {
|
|
111
|
-
logger.warn(
|
|
112
|
-
"SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
|
|
113
|
-
{ hint: "Set encryptionKey option or CACHE_ENCRYPTION_KEY env var" }
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
try {
|
|
119
|
-
const buf = Buffer.from(keyBase64, "base64");
|
|
120
|
-
const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
|
|
121
|
-
if (requiredLen > 0 && buf.length !== requiredLen) {
|
|
122
|
-
throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
|
|
123
|
-
}
|
|
124
|
-
if (buf.length < 1) {
|
|
125
|
-
throw new Error("XOR key must be at least 1 byte");
|
|
126
|
-
}
|
|
127
|
-
this._key = buf;
|
|
128
|
-
if (mode === "xor") {
|
|
129
|
-
logger.warn(
|
|
130
|
-
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
131
|
-
);
|
|
132
|
-
} else {
|
|
133
|
-
logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
|
|
134
|
-
}
|
|
135
|
-
} catch (err) {
|
|
136
|
-
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
137
|
-
}
|
|
138
|
-
if (previousKeyBase64) {
|
|
139
|
-
try {
|
|
140
|
-
this._prevMode = previousMode ?? mode;
|
|
141
|
-
this._prevKey = Buffer.from(previousKeyBase64, "base64");
|
|
142
|
-
logger.debug("Previous encryption key loaded for key rotation fallback");
|
|
143
|
-
} catch (err) {
|
|
144
|
-
logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
get isEnabled() {
|
|
149
|
-
return this._key !== null;
|
|
150
|
-
}
|
|
151
|
-
// ── String (Redis) ────────────────────────────────────────────────────────
|
|
152
|
-
/**
|
|
153
|
-
* Encrypt a string for Redis storage.
|
|
154
|
-
* Returns a mode-prefixed base64 string when a key is configured;
|
|
155
|
-
* otherwise returns the original string unchanged (backward-compatible).
|
|
156
|
-
*/
|
|
157
|
-
encrypt(plaintext) {
|
|
158
|
-
if (!this._key) return plaintext;
|
|
159
|
-
if (this._mode === "xor") {
|
|
160
|
-
const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
|
|
161
|
-
return PREFIX_XOR + masked.toString("base64");
|
|
162
|
-
}
|
|
163
|
-
if (this._mode === "aes-128-ctr") {
|
|
164
|
-
const iv2 = this._nextCtrIV();
|
|
165
|
-
const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
|
|
166
|
-
const enc2 = c2.update(plaintext, "utf8");
|
|
167
|
-
c2.final();
|
|
168
|
-
const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length);
|
|
169
|
-
iv2.copy(out2, 0);
|
|
170
|
-
enc2.copy(out2, CTR_IV_BYTES);
|
|
171
|
-
return PREFIX_CTR + out2.toString("base64");
|
|
172
|
-
}
|
|
173
|
-
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
174
|
-
const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
|
|
175
|
-
const iv = this._nextIV();
|
|
176
|
-
const c = createCipheriv(algo, this._key, iv);
|
|
177
|
-
const enc = c.update(plaintext, "utf8");
|
|
178
|
-
c.final();
|
|
179
|
-
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
180
|
-
iv.copy(out, 0);
|
|
181
|
-
c.getAuthTag().copy(out, IV_BYTES);
|
|
182
|
-
enc.copy(out, IV_BYTES + TAG_BYTES);
|
|
183
|
-
return prefix + out.toString("base64");
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Decrypt a Redis value.
|
|
187
|
-
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
188
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
189
|
-
*/
|
|
190
|
-
decrypt(value) {
|
|
191
|
-
try {
|
|
192
|
-
return this._decryptWithKey(value, this._key, this._mode);
|
|
193
|
-
} catch (primaryErr) {
|
|
194
|
-
if (this._prevKey) {
|
|
195
|
-
try {
|
|
196
|
-
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
197
|
-
} catch {
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
throw primaryErr;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
_decryptWithKey(value, key, mode) {
|
|
204
|
-
if (value.startsWith(PREFIX_XOR)) {
|
|
205
|
-
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
206
|
-
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
207
|
-
const klen = key.length;
|
|
208
|
-
const len = masked.length;
|
|
209
|
-
const out = Buffer.allocUnsafe(len);
|
|
210
|
-
for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
|
|
211
|
-
return out.toString("utf8");
|
|
212
|
-
}
|
|
213
|
-
if (value.startsWith(PREFIX_CTR)) {
|
|
214
|
-
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
215
|
-
const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
|
|
216
|
-
const iv2 = combined2.subarray(0, CTR_IV_BYTES);
|
|
217
|
-
const ct2 = combined2.subarray(CTR_IV_BYTES);
|
|
218
|
-
const d2 = createDecipheriv("aes-128-ctr", key, iv2);
|
|
219
|
-
const plain2 = d2.update(ct2);
|
|
220
|
-
d2.final();
|
|
221
|
-
return plain2.toString("utf8");
|
|
222
|
-
}
|
|
223
|
-
const is256 = value.startsWith(PREFIX_256);
|
|
224
|
-
const is128 = value.startsWith(PREFIX_128);
|
|
225
|
-
if (!is256 && !is128) return value;
|
|
226
|
-
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
227
|
-
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
228
|
-
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
229
|
-
const combined = Buffer.from(value.slice(prefix.length), "base64");
|
|
230
|
-
const iv = combined.subarray(0, IV_BYTES);
|
|
231
|
-
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
232
|
-
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
233
|
-
const d = createDecipheriv(algo, key, iv);
|
|
234
|
-
d.setAuthTag(tag);
|
|
235
|
-
const plain = d.update(ct);
|
|
236
|
-
d.final();
|
|
237
|
-
return plain.toString("utf8");
|
|
238
|
-
void mode;
|
|
239
|
-
}
|
|
240
|
-
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
241
|
-
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
242
|
-
encryptBuffer(data) {
|
|
243
|
-
if (!this._key) return data;
|
|
244
|
-
if (this._mode === "xor") {
|
|
245
|
-
const masked = this._xorBuffer(data);
|
|
246
|
-
const out2 = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
|
|
247
|
-
MAGIC_XOR.copy(out2, 0);
|
|
248
|
-
masked.copy(out2, MAGIC_LEN);
|
|
249
|
-
return out2;
|
|
250
|
-
}
|
|
251
|
-
if (this._mode === "aes-128-ctr") {
|
|
252
|
-
const iv2 = this._nextCtrIV();
|
|
253
|
-
const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
|
|
254
|
-
const enc2 = c2.update(data);
|
|
255
|
-
c2.final();
|
|
256
|
-
const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length);
|
|
257
|
-
MAGIC_CTR.copy(out2, 0);
|
|
258
|
-
iv2.copy(out2, MAGIC_LEN);
|
|
259
|
-
enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
|
|
260
|
-
return out2;
|
|
261
|
-
}
|
|
262
|
-
const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
|
|
263
|
-
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
264
|
-
const iv = this._nextIV();
|
|
265
|
-
const c = createCipheriv(algo, this._key, iv);
|
|
266
|
-
const enc = c.update(data);
|
|
267
|
-
c.final();
|
|
268
|
-
const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
|
|
269
|
-
magic.copy(out, 0);
|
|
270
|
-
iv.copy(out, MAGIC_LEN);
|
|
271
|
-
c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
|
|
272
|
-
enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
273
|
-
return out;
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* Decrypt a raw Buffer from disk/snapshot.
|
|
277
|
-
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
278
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
279
|
-
*/
|
|
280
|
-
decryptBuffer(data) {
|
|
281
|
-
try {
|
|
282
|
-
return this._decryptBufferWithKey(data, this._key);
|
|
283
|
-
} catch (primaryErr) {
|
|
284
|
-
if (this._prevKey) {
|
|
285
|
-
try {
|
|
286
|
-
return this._decryptBufferWithKey(data, this._prevKey);
|
|
287
|
-
} catch {
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
throw primaryErr;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
_decryptBufferWithKey(data, key) {
|
|
294
|
-
if (data.length < MAGIC_LEN) return data;
|
|
295
|
-
const magic = data.subarray(0, MAGIC_LEN);
|
|
296
|
-
if (magic.equals(MAGIC_XOR)) {
|
|
297
|
-
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
298
|
-
const raw = data.subarray(MAGIC_LEN);
|
|
299
|
-
const klen = key.length;
|
|
300
|
-
const out = Buffer.allocUnsafe(raw.length);
|
|
301
|
-
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
|
|
302
|
-
return out;
|
|
303
|
-
}
|
|
304
|
-
if (magic.equals(MAGIC_CTR)) {
|
|
305
|
-
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
306
|
-
const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
307
|
-
const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
308
|
-
const d2 = createDecipheriv("aes-128-ctr", key, iv2);
|
|
309
|
-
const plain2 = d2.update(ct2);
|
|
310
|
-
d2.final();
|
|
311
|
-
return plain2;
|
|
312
|
-
}
|
|
313
|
-
const is256 = magic.equals(MAGIC_256);
|
|
314
|
-
const is128 = magic.equals(MAGIC_128);
|
|
315
|
-
if (!is256 && !is128) return data;
|
|
316
|
-
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
317
|
-
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
318
|
-
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
319
|
-
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
320
|
-
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
321
|
-
const d = createDecipheriv(algo, key, iv);
|
|
322
|
-
d.setAuthTag(tag);
|
|
323
|
-
const plain = d.update(ct);
|
|
324
|
-
d.final();
|
|
325
|
-
return plain;
|
|
326
|
-
}
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
// src/smart-memory-cache.ts
|
|
330
|
-
import { pack, unpack } from "msgpackr";
|
|
331
|
-
|
|
332
|
-
// src/wasm/bloom-filter-wasm.ts
|
|
333
|
-
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
334
|
-
var KEY_STAGING_OFFSET = 2e4;
|
|
335
|
-
var MAX_KEY_BYTES = 512;
|
|
336
|
-
function instantiateSync() {
|
|
337
|
-
const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, "base64");
|
|
338
|
-
const compiled = new WebAssembly.Module(wasmBytes);
|
|
339
|
-
return new WebAssembly.Instance(compiled, {});
|
|
340
|
-
}
|
|
341
|
-
var WasmBloomFilter = class {
|
|
342
|
-
exports;
|
|
343
|
-
mem;
|
|
344
|
-
encoder = new TextEncoder();
|
|
345
|
-
numBits = 1e5;
|
|
346
|
-
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
347
|
-
_maxCapacity;
|
|
348
|
-
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
349
|
-
_insertionCount = 0;
|
|
350
|
-
constructor() {
|
|
351
|
-
const instance = instantiateSync();
|
|
352
|
-
this.exports = instance.exports;
|
|
353
|
-
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
354
|
-
const k = 7, p = 0.01;
|
|
355
|
-
this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
356
|
-
}
|
|
357
|
-
writeKey(key) {
|
|
358
|
-
const max = Math.min(key.length, MAX_KEY_BYTES);
|
|
359
|
-
if (max === 0) return 0;
|
|
360
|
-
for (let i = 0; i < max; i++) {
|
|
361
|
-
const c = key.charCodeAt(i);
|
|
362
|
-
if (c > 127) {
|
|
363
|
-
const encoded = this.encoder.encode(key);
|
|
364
|
-
const len = Math.min(encoded.length, MAX_KEY_BYTES);
|
|
365
|
-
this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
|
|
366
|
-
return len;
|
|
367
|
-
}
|
|
368
|
-
this.mem[KEY_STAGING_OFFSET + i] = c;
|
|
369
|
-
}
|
|
370
|
-
return max;
|
|
371
|
-
}
|
|
372
|
-
add(key) {
|
|
373
|
-
const len = this.writeKey(key);
|
|
374
|
-
if (len === 0) return;
|
|
375
|
-
this.exports.add(KEY_STAGING_OFFSET, len);
|
|
376
|
-
this._insertionCount++;
|
|
377
|
-
}
|
|
378
|
-
mightContain(key) {
|
|
379
|
-
const len = this.writeKey(key);
|
|
380
|
-
if (len === 0) return true;
|
|
381
|
-
return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
|
|
382
|
-
}
|
|
383
|
-
reset() {
|
|
384
|
-
this.exports.reset();
|
|
385
|
-
this._insertionCount = 0;
|
|
386
|
-
}
|
|
387
|
-
rebuild(keys) {
|
|
388
|
-
this.reset();
|
|
389
|
-
for (const key of keys) this.add(key);
|
|
390
|
-
}
|
|
391
|
-
get stats() {
|
|
392
|
-
const bitsSet = this.exports.countBits();
|
|
393
|
-
return { bitsSet, fillFactor: bitsSet / this.numBits };
|
|
394
|
-
}
|
|
395
|
-
/** Number of add() calls since last reset/rebuild. */
|
|
396
|
-
get insertions() {
|
|
397
|
-
return this._insertionCount;
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
401
|
-
* Exact formula for k=7 hash rounds, m=100 000 bits:
|
|
402
|
-
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
|
|
403
|
-
*/
|
|
404
|
-
get maxCapacity() {
|
|
405
|
-
return this._maxCapacity;
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
// src/smart-memory-cache.ts
|
|
410
|
-
var EVICTION_BATCH_PERCENT = 0.2;
|
|
411
|
-
var JsBloomFilter = class {
|
|
412
|
-
bits;
|
|
413
|
-
numBits;
|
|
414
|
-
k;
|
|
415
|
-
/** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
|
|
416
|
-
_maxCapacity;
|
|
417
|
-
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
418
|
-
_insertionCount = 0;
|
|
419
|
-
constructor(numBits = 1e5, k = 7) {
|
|
420
|
-
this.numBits = numBits;
|
|
421
|
-
this.k = k;
|
|
422
|
-
this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
|
|
423
|
-
const p = 0.01;
|
|
424
|
-
this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
425
|
-
}
|
|
426
|
-
fnv1a32(s) {
|
|
427
|
-
let h = 2166136261;
|
|
428
|
-
for (let i = 0; i < s.length; i++) {
|
|
429
|
-
h ^= s.charCodeAt(i);
|
|
430
|
-
h = Math.imul(h, 16777619) >>> 0;
|
|
431
|
-
}
|
|
432
|
-
return h >>> 0;
|
|
433
|
-
}
|
|
434
|
-
djb2(s) {
|
|
435
|
-
let h = 5381;
|
|
436
|
-
for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) >>> 0;
|
|
437
|
-
return h >>> 0;
|
|
438
|
-
}
|
|
439
|
-
setBit(i) {
|
|
440
|
-
this.bits[i >>> 3] |= 1 << (i & 7);
|
|
441
|
-
}
|
|
442
|
-
getBit(i) {
|
|
443
|
-
return (this.bits[i >>> 3] & 1 << (i & 7)) !== 0;
|
|
444
|
-
}
|
|
445
|
-
add(key) {
|
|
446
|
-
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
447
|
-
for (let i = 0; i < this.k; i++) this.setBit((h1 + i * h2 >>> 0) % this.numBits);
|
|
448
|
-
this._insertionCount++;
|
|
449
|
-
}
|
|
450
|
-
mightContain(key) {
|
|
451
|
-
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
452
|
-
for (let i = 0; i < this.k; i++) if (!this.getBit((h1 + i * h2 >>> 0) % this.numBits)) return false;
|
|
453
|
-
return true;
|
|
454
|
-
}
|
|
455
|
-
reset() {
|
|
456
|
-
this.bits.fill(0);
|
|
457
|
-
this._insertionCount = 0;
|
|
458
|
-
}
|
|
459
|
-
rebuild(keys) {
|
|
460
|
-
this.bits.fill(0);
|
|
461
|
-
this._insertionCount = 0;
|
|
462
|
-
for (const k of keys) this.add(k);
|
|
463
|
-
}
|
|
464
|
-
/** Number of add() calls since last reset/rebuild. */
|
|
465
|
-
get insertions() {
|
|
466
|
-
return this._insertionCount;
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
470
|
-
* Exact formula for the configured k and target p=1 %:
|
|
471
|
-
* n_max = -m * ln(1 - p^(1/k)) / k
|
|
472
|
-
*/
|
|
473
|
-
get maxCapacity() {
|
|
474
|
-
return this._maxCapacity;
|
|
475
|
-
}
|
|
476
|
-
get stats() {
|
|
477
|
-
let bitsSet = 0;
|
|
478
|
-
for (const byte of this.bits) {
|
|
479
|
-
let b = byte;
|
|
480
|
-
while (b) {
|
|
481
|
-
bitsSet++;
|
|
482
|
-
b &= b - 1;
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
return { bitsSet, fillFactor: bitsSet / this.numBits };
|
|
486
|
-
}
|
|
487
|
-
};
|
|
488
|
-
function createBloomFilter(logger) {
|
|
489
|
-
try {
|
|
490
|
-
const wasm = new WasmBloomFilter();
|
|
491
|
-
logger.debug("SmartMemoryCache: WASM BloomFilter active");
|
|
492
|
-
return wasm;
|
|
493
|
-
} catch (err) {
|
|
494
|
-
logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
|
|
495
|
-
return new JsBloomFilter();
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
var SKETCH_ROWS = 4;
|
|
499
|
-
var SKETCH_WIDTH = 512;
|
|
500
|
-
var SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
501
|
-
var SKETCH_DECAY_THRESHOLD = 1e5;
|
|
502
|
-
var CountMinSketch = class {
|
|
503
|
-
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
504
|
-
inserts = 0;
|
|
505
|
-
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
506
|
-
fnv32(key) {
|
|
507
|
-
let h = 2166136261;
|
|
508
|
-
for (let i = 0; i < key.length; i++) {
|
|
509
|
-
h ^= key.charCodeAt(i);
|
|
510
|
-
h = Math.imul(h, 16777619) >>> 0;
|
|
511
|
-
}
|
|
512
|
-
return h;
|
|
513
|
-
}
|
|
514
|
-
/** Four independent bit-mixes from one FNV-1a seed. */
|
|
515
|
-
hashes(key) {
|
|
516
|
-
const h = this.fnv32(key);
|
|
517
|
-
const h1 = (h ^ h >>> 16) >>> 0;
|
|
518
|
-
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
519
|
-
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
520
|
-
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
521
|
-
return [h1, h2, h3, h4];
|
|
522
|
-
}
|
|
523
|
-
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
524
|
-
increment(key) {
|
|
525
|
-
const [h1, h2, h3, h4] = this.hashes(key);
|
|
526
|
-
const t = this.table;
|
|
527
|
-
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
|
|
528
|
-
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
|
|
529
|
-
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
|
|
530
|
-
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
|
|
531
|
-
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
532
|
-
}
|
|
533
|
-
/** Minimum-across-rows frequency estimate. */
|
|
534
|
-
estimate(key) {
|
|
535
|
-
const [h1, h2, h3, h4] = this.hashes(key);
|
|
536
|
-
const t = this.table;
|
|
537
|
-
return Math.min(
|
|
538
|
-
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
|
|
539
|
-
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
|
|
540
|
-
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
|
|
541
|
-
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
|
|
542
|
-
);
|
|
543
|
-
}
|
|
544
|
-
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
545
|
-
decay() {
|
|
546
|
-
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
547
|
-
this.inserts = 0;
|
|
548
|
-
}
|
|
549
|
-
};
|
|
550
|
-
var SmartMemoryCache = class {
|
|
551
|
-
cache = /* @__PURE__ */ new Map();
|
|
552
|
-
opts;
|
|
553
|
-
bloom;
|
|
554
|
-
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
555
|
-
categoryPrefixes;
|
|
556
|
-
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
557
|
-
sketch = new CountMinSketch();
|
|
558
|
-
totalSize = 0;
|
|
559
|
-
categoryCount = /* @__PURE__ */ new Map();
|
|
560
|
-
categorySize = /* @__PURE__ */ new Map();
|
|
561
|
-
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
562
|
-
categoryKeys = /* @__PURE__ */ new Map();
|
|
563
|
-
// ── Observability counters ──────────────────────────────────────────────────────
|
|
564
|
-
bloomChecks = 0;
|
|
565
|
-
bloomFalsePos = 0;
|
|
566
|
-
compressions = 0;
|
|
567
|
-
categoryHits = /* @__PURE__ */ new Map();
|
|
568
|
-
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
569
|
-
_bloomDirtyCount = 0;
|
|
570
|
-
constructor(opts, existing) {
|
|
571
|
-
this.opts = opts;
|
|
572
|
-
this.bloom = createBloomFilter(opts.logger);
|
|
573
|
-
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
574
|
-
if (existing) {
|
|
575
|
-
for (const [k, v] of existing) this.cache.set(k, v);
|
|
576
|
-
this.recalculateStats();
|
|
577
|
-
for (const key of this.cache.keys()) this.bloom.add(key);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
// ── Internal helpers ──────────────────────────────────────────────────────
|
|
581
|
-
recalculateStats() {
|
|
582
|
-
this.totalSize = 0;
|
|
583
|
-
this.categoryCount.clear();
|
|
584
|
-
this.categorySize.clear();
|
|
585
|
-
this.categoryKeys.clear();
|
|
586
|
-
for (const [key, entry] of this.cache) {
|
|
587
|
-
this.totalSize += entry.size;
|
|
588
|
-
const cat = this.getCategory(key);
|
|
589
|
-
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
590
|
-
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
|
|
591
|
-
let ks = this.categoryKeys.get(cat);
|
|
592
|
-
if (!ks) {
|
|
593
|
-
ks = /* @__PURE__ */ new Set();
|
|
594
|
-
this.categoryKeys.set(cat, ks);
|
|
595
|
-
}
|
|
596
|
-
ks.add(key);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
getCategory(key) {
|
|
600
|
-
for (const prefix of this.categoryPrefixes) {
|
|
601
|
-
if (key.startsWith(prefix)) return prefix;
|
|
602
|
-
}
|
|
603
|
-
return "default";
|
|
604
|
-
}
|
|
605
|
-
getCategoryLimit(cat) {
|
|
606
|
-
return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
607
|
-
}
|
|
608
|
-
_delete(key, reason = "manual") {
|
|
609
|
-
const entry = this.cache.get(key);
|
|
610
|
-
if (!entry) return false;
|
|
611
|
-
const cat = this.getCategory(key);
|
|
612
|
-
this.totalSize -= entry.size;
|
|
613
|
-
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
614
|
-
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
615
|
-
this.categoryKeys.get(cat)?.delete(key);
|
|
616
|
-
this._bloomDirtyCount++;
|
|
617
|
-
const deleted = this.cache.delete(key);
|
|
618
|
-
if (deleted && this.opts.onEviction) {
|
|
619
|
-
try {
|
|
620
|
-
this.opts.onEviction(key, reason);
|
|
621
|
-
} catch {
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
return deleted;
|
|
625
|
-
}
|
|
626
|
-
ensureCapacity(category, neededSize) {
|
|
627
|
-
const lim = this.getCategoryLimit(category);
|
|
628
|
-
const catCnt = this.categoryCount.get(category) ?? 0;
|
|
629
|
-
const catSz = this.categorySize.get(category) ?? 0;
|
|
630
|
-
const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
631
|
-
const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
632
|
-
if (!catOvf && !glbOvf) return;
|
|
633
|
-
this.smartEvict(category, catOvf);
|
|
634
|
-
}
|
|
635
|
-
score(entry, catBonus, now, key) {
|
|
636
|
-
const age = now - entry.lastAccess;
|
|
637
|
-
const ttl = Math.max(0, entry.expiresAt - now);
|
|
638
|
-
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
639
|
-
return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
|
|
640
|
-
}
|
|
641
|
-
/**
|
|
642
|
-
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
643
|
-
* saturated the filter past its ~1 % FP capacity.
|
|
644
|
-
*
|
|
645
|
-
* Trigger: (insertions − live entries) > maxCapacity
|
|
646
|
-
*
|
|
647
|
-
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
648
|
-
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
649
|
-
* cache holds more entries than the filter's rated capacity — which would
|
|
650
|
-
* stall the write path entirely.
|
|
651
|
-
*
|
|
652
|
-
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
653
|
-
*/
|
|
654
|
-
maybeRebuildBloom() {
|
|
655
|
-
if (this._bloomDirtyCount > this.bloom.maxCapacity >>> 2 || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
|
|
656
|
-
this.bloom.rebuild(this.cache.keys());
|
|
657
|
-
this._bloomDirtyCount = 0;
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
smartEvict(targetCat, catOvf) {
|
|
661
|
-
const now = Date.now();
|
|
662
|
-
const SAMPLE = 16;
|
|
663
|
-
const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT));
|
|
664
|
-
const pool = [];
|
|
665
|
-
if (catOvf) {
|
|
666
|
-
const catKeySet = this.categoryKeys.get(targetCat);
|
|
667
|
-
if (catKeySet) {
|
|
668
|
-
let catSeen = 0;
|
|
669
|
-
for (const key of catKeySet) {
|
|
670
|
-
const entry = this.cache.get(key);
|
|
671
|
-
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
672
|
-
catSeen++;
|
|
673
|
-
const s = this.score(entry, 100, now, key);
|
|
674
|
-
if (pool.length < EVICT) {
|
|
675
|
-
pool.push({ key, score: s });
|
|
676
|
-
} else {
|
|
677
|
-
const j = Math.floor(Math.random() * catSeen);
|
|
678
|
-
if (j < EVICT) pool[j] = { key, score: s };
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
if (pool.length < EVICT) {
|
|
684
|
-
const remaining = SAMPLE - pool.length;
|
|
685
|
-
let globalSeen = 0;
|
|
686
|
-
const globalPool = [];
|
|
687
|
-
for (const [key, entry] of this.cache) {
|
|
688
|
-
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
689
|
-
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
690
|
-
globalSeen++;
|
|
691
|
-
const s = this.score(entry, 0, now, key);
|
|
692
|
-
if (globalPool.length < remaining) {
|
|
693
|
-
globalPool.push({ key, score: s });
|
|
694
|
-
} else {
|
|
695
|
-
const j = Math.floor(Math.random() * globalSeen);
|
|
696
|
-
if (j < remaining) globalPool[j] = { key, score: s };
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
pool.push(...globalPool);
|
|
700
|
-
}
|
|
701
|
-
if (pool.length === 0) return;
|
|
702
|
-
pool.sort((a, b) => a.score - b.score);
|
|
703
|
-
for (const { key } of pool.slice(0, EVICT)) {
|
|
704
|
-
const entry = this.cache.get(key);
|
|
705
|
-
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
706
|
-
this._delete(key, "capacity");
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
// ── Public API ────────────────────────────────────────────────────────────
|
|
710
|
-
get(key) {
|
|
711
|
-
this.bloomChecks++;
|
|
712
|
-
if (!this.bloom.mightContain(key)) return null;
|
|
713
|
-
const entry = this.cache.get(key);
|
|
714
|
-
if (!entry) {
|
|
715
|
-
this.bloomFalsePos++;
|
|
716
|
-
return null;
|
|
717
|
-
}
|
|
718
|
-
const now = Date.now();
|
|
719
|
-
if (entry.expiresAt < now) {
|
|
720
|
-
this._delete(key, "ttl");
|
|
721
|
-
return null;
|
|
722
|
-
}
|
|
723
|
-
entry.hits++;
|
|
724
|
-
entry.lastAccess = now;
|
|
725
|
-
this.sketch.increment(key);
|
|
726
|
-
const cat = this.getCategory(key);
|
|
727
|
-
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
728
|
-
const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
|
|
729
|
-
const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
|
|
730
|
-
return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
|
|
731
|
-
}
|
|
732
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta) {
|
|
733
|
-
const packed = pack(data);
|
|
734
|
-
const size = packed.byteLength;
|
|
735
|
-
this.compressions++;
|
|
736
|
-
this.sketch.increment(key);
|
|
737
|
-
const cat = this.getCategory(key);
|
|
738
|
-
const lim = this.getCategoryLimit(cat);
|
|
739
|
-
if (size > lim.maxSizeBytes * 0.5) {
|
|
740
|
-
this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
const existingEntry = this.cache.get(key);
|
|
744
|
-
if (existingEntry) {
|
|
745
|
-
this.totalSize -= existingEntry.size;
|
|
746
|
-
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
747
|
-
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
748
|
-
this.cache.delete(key);
|
|
749
|
-
}
|
|
750
|
-
this.ensureCapacity(cat, size);
|
|
751
|
-
const now = Date.now();
|
|
752
|
-
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
753
|
-
this.bloom.add(key);
|
|
754
|
-
this.maybeRebuildBloom();
|
|
755
|
-
this.totalSize += size;
|
|
756
|
-
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
757
|
-
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
|
|
758
|
-
let ks = this.categoryKeys.get(cat);
|
|
759
|
-
if (!ks) {
|
|
760
|
-
ks = /* @__PURE__ */ new Set();
|
|
761
|
-
this.categoryKeys.set(cat, ks);
|
|
762
|
-
}
|
|
763
|
-
ks.add(key);
|
|
764
|
-
}
|
|
765
|
-
delete(key) {
|
|
766
|
-
const deleted = this._delete(key, "manual");
|
|
767
|
-
if (deleted) this.maybeRebuildBloom();
|
|
768
|
-
return deleted;
|
|
769
|
-
}
|
|
770
|
-
keysMatchingPattern(pattern) {
|
|
771
|
-
if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
|
|
772
|
-
const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
|
|
773
|
-
const out = [];
|
|
774
|
-
for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
|
|
775
|
-
return out;
|
|
776
|
-
}
|
|
777
|
-
deletePattern(pattern) {
|
|
778
|
-
let n = 0;
|
|
779
|
-
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
|
|
780
|
-
if (n > 0) this.maybeRebuildBloom();
|
|
781
|
-
return n;
|
|
782
|
-
}
|
|
783
|
-
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
784
|
-
clear(prefix) {
|
|
785
|
-
if (prefix) {
|
|
786
|
-
const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
|
|
787
|
-
return this.deletePattern(pattern);
|
|
788
|
-
}
|
|
789
|
-
const count = this.cache.size;
|
|
790
|
-
this.cache.clear();
|
|
791
|
-
this.totalSize = 0;
|
|
792
|
-
this.categoryCount.clear();
|
|
793
|
-
this.categorySize.clear();
|
|
794
|
-
this.categoryKeys.clear();
|
|
795
|
-
this.categoryHits.clear();
|
|
796
|
-
this.bloom.reset();
|
|
797
|
-
this._bloomDirtyCount = 0;
|
|
798
|
-
return count;
|
|
799
|
-
}
|
|
800
|
-
/**
|
|
801
|
-
* Evict entries that violate current category or global limits.
|
|
802
|
-
* Returns the number of entries evicted.
|
|
803
|
-
*/
|
|
804
|
-
rebalance() {
|
|
805
|
-
const now = Date.now();
|
|
806
|
-
let evicted = 0;
|
|
807
|
-
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
808
|
-
const catKeys = this.categoryKeys.get(cat);
|
|
809
|
-
if (!catKeys || catKeys.size === 0) continue;
|
|
810
|
-
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
811
|
-
let catSz = this.categorySize.get(cat) ?? 0;
|
|
812
|
-
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
|
|
813
|
-
const candidates = [];
|
|
814
|
-
for (const key of catKeys) {
|
|
815
|
-
const entry = this.cache.get(key);
|
|
816
|
-
if (!entry) continue;
|
|
817
|
-
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
818
|
-
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
819
|
-
}
|
|
820
|
-
candidates.sort((a, b) => a.score - b.score);
|
|
821
|
-
for (const { key } of candidates) {
|
|
822
|
-
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
823
|
-
catSz = this.categorySize.get(cat) ?? 0;
|
|
824
|
-
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
|
|
825
|
-
const entry = this.cache.get(key);
|
|
826
|
-
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
827
|
-
this._delete(key, "rebalance");
|
|
828
|
-
evicted++;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
832
|
-
const before = this.cache.size;
|
|
833
|
-
this.smartEvict("default", false);
|
|
834
|
-
if (this.cache.size >= before) break;
|
|
835
|
-
evicted += before - this.cache.size;
|
|
836
|
-
}
|
|
837
|
-
if (evicted > 0) this.maybeRebuildBloom();
|
|
838
|
-
return evicted;
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
842
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
843
|
-
*/
|
|
844
|
-
ttl(key) {
|
|
845
|
-
const entry = this.cache.get(key);
|
|
846
|
-
if (!entry) return null;
|
|
847
|
-
const remaining = entry.expiresAt - Date.now();
|
|
848
|
-
return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
|
|
849
|
-
}
|
|
850
|
-
/**
|
|
851
|
-
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
852
|
-
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
853
|
-
* exceeds the configured threshold.
|
|
854
|
-
*
|
|
855
|
-
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
856
|
-
* @returns Number of entries evicted
|
|
857
|
-
*/
|
|
858
|
-
evictPercentage(pct) {
|
|
859
|
-
if (pct <= 0 || this.cache.size === 0) return 0;
|
|
860
|
-
const now = Date.now();
|
|
861
|
-
const candidates = [];
|
|
862
|
-
for (const [key, entry] of this.cache) {
|
|
863
|
-
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
864
|
-
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
865
|
-
}
|
|
866
|
-
candidates.sort((a, b) => a.score - b.score);
|
|
867
|
-
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
868
|
-
let evicted = 0;
|
|
869
|
-
for (const { key } of candidates.slice(0, count)) {
|
|
870
|
-
const entry = this.cache.get(key);
|
|
871
|
-
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
872
|
-
this._delete(key, "oom");
|
|
873
|
-
evicted++;
|
|
874
|
-
}
|
|
875
|
-
return evicted;
|
|
876
|
-
}
|
|
877
|
-
cleanup() {
|
|
878
|
-
const now = Date.now();
|
|
879
|
-
let cleaned = 0;
|
|
880
|
-
for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
|
|
881
|
-
this._delete(key, "ttl");
|
|
882
|
-
cleaned++;
|
|
883
|
-
}
|
|
884
|
-
if (cleaned > 0) {
|
|
885
|
-
this.bloom.rebuild(this.cache.keys());
|
|
886
|
-
this._bloomDirtyCount = 0;
|
|
887
|
-
}
|
|
888
|
-
return cleaned;
|
|
889
|
-
}
|
|
890
|
-
// ── Snapshot import/export ────────────────────────────────────────────────
|
|
891
|
-
exportEntries(forbiddenPrefixes) {
|
|
892
|
-
const now = Date.now();
|
|
893
|
-
const out = [];
|
|
894
|
-
for (const [key, entry] of this.cache) {
|
|
895
|
-
if (entry.expiresAt <= now) continue;
|
|
896
|
-
if (entry.priority === 4) continue;
|
|
897
|
-
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
898
|
-
out.push({ key, entry: { ...entry } });
|
|
899
|
-
}
|
|
900
|
-
return out;
|
|
901
|
-
}
|
|
902
|
-
importEntries(entries, forbiddenPrefixes) {
|
|
903
|
-
const now = Date.now();
|
|
904
|
-
let loaded = 0;
|
|
905
|
-
for (const { key, entry } of entries) {
|
|
906
|
-
if (entry.expiresAt <= now) continue;
|
|
907
|
-
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
908
|
-
if (this.cache.has(key)) continue;
|
|
909
|
-
const rawData = entry.data;
|
|
910
|
-
const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
911
|
-
const value = unpack(data);
|
|
912
|
-
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
913
|
-
this.bloom.add(key);
|
|
914
|
-
loaded++;
|
|
915
|
-
}
|
|
916
|
-
this.recalculateStats();
|
|
917
|
-
return loaded;
|
|
918
|
-
}
|
|
919
|
-
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
920
|
-
/**
|
|
921
|
-
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
922
|
-
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
923
|
-
* are silently skipped.
|
|
924
|
-
*/
|
|
925
|
-
*liveEntries() {
|
|
926
|
-
const now = Date.now();
|
|
927
|
-
for (const [key, entry] of this.cache) {
|
|
928
|
-
if (entry.expiresAt > now) yield [key, entry];
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
/**
|
|
932
|
-
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
933
|
-
* Use this instead of liveEntries() when you only need keys.
|
|
934
|
-
*/
|
|
935
|
-
*liveKeys() {
|
|
936
|
-
const now = Date.now();
|
|
937
|
-
for (const [key, entry] of this.cache) {
|
|
938
|
-
if (entry.expiresAt > now) yield key;
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* Yields only the resolved values of live entries.
|
|
943
|
-
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
944
|
-
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
945
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
946
|
-
*/
|
|
947
|
-
*liveValues() {
|
|
948
|
-
const now = Date.now();
|
|
949
|
-
for (const entry of this.cache.values()) {
|
|
950
|
-
if (entry.expiresAt > now)
|
|
951
|
-
yield entry.value !== void 0 ? entry.value : entry.data;
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
955
|
-
get size() {
|
|
956
|
-
return this.cache.size;
|
|
957
|
-
}
|
|
958
|
-
get memoryUsage() {
|
|
959
|
-
return this.totalSize;
|
|
960
|
-
}
|
|
961
|
-
getStats() {
|
|
962
|
-
const categories = {};
|
|
963
|
-
for (const [cat, cnt] of this.categoryCount) {
|
|
964
|
-
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
965
|
-
}
|
|
966
|
-
return {
|
|
967
|
-
entries: this.cache.size,
|
|
968
|
-
sizeBytes: this.totalSize,
|
|
969
|
-
sizeKB: Math.round(this.totalSize / 1024),
|
|
970
|
-
categories,
|
|
971
|
-
bloom: {
|
|
972
|
-
checks: this.bloomChecks,
|
|
973
|
-
falsePositives: this.bloomFalsePos
|
|
974
|
-
},
|
|
975
|
-
compression: {
|
|
976
|
-
compressed: this.compressions,
|
|
977
|
-
uncompressed: 0,
|
|
978
|
-
// all entries are now msgpackr-packed
|
|
979
|
-
bytesSaved: 0
|
|
980
|
-
// no longer tracked (unified format removes the split path)
|
|
981
|
-
}
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
/**
|
|
985
|
-
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
986
|
-
* Does NOT count as a hit or perform SWR logic.
|
|
987
|
-
*/
|
|
988
|
-
getEntry(key) {
|
|
989
|
-
const entry = this.cache.get(key);
|
|
990
|
-
if (!entry) return void 0;
|
|
991
|
-
if (entry.expiresAt <= Date.now()) return void 0;
|
|
992
|
-
return entry;
|
|
993
|
-
}
|
|
994
|
-
/**
|
|
995
|
-
* Return true if the key exists in L1 and has not expired.
|
|
996
|
-
* Uses the bloom filter as a fast negative check.
|
|
997
|
-
*/
|
|
998
|
-
has(key) {
|
|
999
|
-
if (!this.bloom.mightContain(key)) return false;
|
|
1000
|
-
const entry = this.cache.get(key);
|
|
1001
|
-
if (!entry) return false;
|
|
1002
|
-
if (entry.expiresAt <= Date.now()) {
|
|
1003
|
-
this._delete(key, "ttl");
|
|
1004
|
-
return false;
|
|
1005
|
-
}
|
|
1006
|
-
return true;
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1010
|
-
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1011
|
-
*/
|
|
1012
|
-
touch(key, newTtlMs) {
|
|
1013
|
-
const entry = this.cache.get(key);
|
|
1014
|
-
if (!entry) return false;
|
|
1015
|
-
const now = Date.now();
|
|
1016
|
-
if (entry.expiresAt <= now) {
|
|
1017
|
-
this._delete(key, "ttl");
|
|
1018
|
-
return false;
|
|
1019
|
-
}
|
|
1020
|
-
entry.expiresAt = now + newTtlMs;
|
|
1021
|
-
return true;
|
|
1022
|
-
}
|
|
1023
|
-
/**
|
|
1024
|
-
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1025
|
-
* Returns `false` if the key is absent or already expired.
|
|
1026
|
-
*/
|
|
1027
|
-
bumpExpiry(key, additionalMs) {
|
|
1028
|
-
const entry = this.cache.get(key);
|
|
1029
|
-
if (!entry) return false;
|
|
1030
|
-
if (entry.expiresAt <= Date.now()) return false;
|
|
1031
|
-
entry.expiresAt += additionalMs;
|
|
1032
|
-
return true;
|
|
1033
|
-
}
|
|
1034
|
-
bloomMightContain(key) {
|
|
1035
|
-
return this.bloom.mightContain(key);
|
|
1036
|
-
}
|
|
1037
|
-
bloomStats() {
|
|
1038
|
-
return this.bloom.stats;
|
|
1039
|
-
}
|
|
1040
|
-
/**
|
|
1041
|
-
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1042
|
-
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1043
|
-
* Useful for diagnosing which keys are driving cache pressure.
|
|
1044
|
-
*
|
|
1045
|
-
* @param n - Maximum number of entries to return. Default: 10.
|
|
1046
|
-
*/
|
|
1047
|
-
hotKeys(n) {
|
|
1048
|
-
const now = Date.now();
|
|
1049
|
-
const out = [];
|
|
1050
|
-
for (const [key, entry] of this.cache) {
|
|
1051
|
-
if (entry.expiresAt <= now) continue;
|
|
1052
|
-
out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
|
|
1053
|
-
}
|
|
1054
|
-
out.sort((a, b) => b.hits - a.hits);
|
|
1055
|
-
return out.slice(0, n);
|
|
1056
|
-
}
|
|
1057
|
-
};
|
|
1058
|
-
|
|
1059
|
-
// src/disk-tier.ts
|
|
1060
|
-
import fs from "fs";
|
|
1061
|
-
import path from "path";
|
|
1062
|
-
import crypto from "crypto";
|
|
1063
|
-
import { pack as pack2, unpack as unpack2 } from "msgpackr";
|
|
1064
|
-
var AES_ALGO = "aes-256-gcm";
|
|
1065
|
-
var IV_BYTES2 = 12;
|
|
1066
|
-
var TAG_BYTES2 = 16;
|
|
1067
|
-
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1068
|
-
var DISK_TIER_VERSION = 1;
|
|
1069
|
-
var DiskTier = class {
|
|
1070
|
-
opts;
|
|
1071
|
-
dirReady = false;
|
|
1072
|
-
diskUsageBytes = 0;
|
|
1073
|
-
usageCounted = false;
|
|
1074
|
-
fileCount = 0;
|
|
1075
|
-
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1076
|
-
constructor(opts) {
|
|
1077
|
-
this.opts = opts;
|
|
1078
|
-
}
|
|
1079
|
-
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1080
|
-
ensureDir() {
|
|
1081
|
-
if (this.dirReady) return;
|
|
1082
|
-
try {
|
|
1083
|
-
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
1084
|
-
this.dirReady = true;
|
|
1085
|
-
} catch (err) {
|
|
1086
|
-
this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
ensureUsageCounted() {
|
|
1090
|
-
if (this.usageCounted) return;
|
|
1091
|
-
this.usageCounted = true;
|
|
1092
|
-
try {
|
|
1093
|
-
this.ensureDir();
|
|
1094
|
-
let total = 0;
|
|
1095
|
-
const files = this.walkCacheFiles();
|
|
1096
|
-
this.fileCount = files.length;
|
|
1097
|
-
for (const filePath of files) {
|
|
1098
|
-
try {
|
|
1099
|
-
total += fs.statSync(filePath).size;
|
|
1100
|
-
} catch {
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
this.diskUsageBytes = total;
|
|
1104
|
-
} catch {
|
|
1105
|
-
this.diskUsageBytes = 0;
|
|
1106
|
-
this.fileCount = 0;
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
/**
|
|
1110
|
-
* Map a cache key to its on-disk path.
|
|
1111
|
-
*
|
|
1112
|
-
* Files are sharded into two-character hex prefix subdirectories to avoid
|
|
1113
|
-
* putting thousands of flat files into a single directory node — which
|
|
1114
|
-
* degrades EXT4/NTFS performance at scale.
|
|
1115
|
-
*
|
|
1116
|
-
* key → SHA-256 hex e3b0c442...
|
|
1117
|
-
* path → {dir}/e3/e3b0c442...
|
|
1118
|
-
*/
|
|
1119
|
-
keyToPath(key) {
|
|
1120
|
-
const hash = crypto.createHash("sha256").update(key, "utf8").digest("hex");
|
|
1121
|
-
return path.join(this.opts.dir, hash.slice(0, 2), hash);
|
|
1122
|
-
}
|
|
1123
|
-
/**
|
|
1124
|
-
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
1125
|
-
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
1126
|
-
* files written by older versions).
|
|
1127
|
-
*/
|
|
1128
|
-
walkCacheFiles() {
|
|
1129
|
-
const results = [];
|
|
1130
|
-
let topEntries;
|
|
1131
|
-
try {
|
|
1132
|
-
topEntries = fs.readdirSync(this.opts.dir);
|
|
1133
|
-
} catch {
|
|
1134
|
-
return results;
|
|
1135
|
-
}
|
|
1136
|
-
for (const top of topEntries) {
|
|
1137
|
-
const topPath = path.join(this.opts.dir, top);
|
|
1138
|
-
try {
|
|
1139
|
-
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
1140
|
-
for (const file of fs.readdirSync(topPath)) {
|
|
1141
|
-
results.push(path.join(topPath, file));
|
|
1142
|
-
}
|
|
1143
|
-
} catch {
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
return results;
|
|
1147
|
-
}
|
|
1148
|
-
isForbidden(key) {
|
|
1149
|
-
return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
|
|
1150
|
-
}
|
|
1151
|
-
encrypt(data) {
|
|
1152
|
-
const key = this.opts.encryptionKey;
|
|
1153
|
-
if (!key) return data;
|
|
1154
|
-
const iv = crypto.randomBytes(IV_BYTES2);
|
|
1155
|
-
const c = crypto.createCipheriv(AES_ALGO, key, iv);
|
|
1156
|
-
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
1157
|
-
const tag = c.getAuthTag();
|
|
1158
|
-
return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
|
|
1159
|
-
}
|
|
1160
|
-
decrypt(data) {
|
|
1161
|
-
const mLen = DISK_MAGIC.length;
|
|
1162
|
-
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
1163
|
-
const key = this.opts.encryptionKey;
|
|
1164
|
-
if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
|
|
1165
|
-
const iv = data.subarray(mLen, mLen + IV_BYTES2);
|
|
1166
|
-
const tag = data.subarray(mLen + IV_BYTES2, mLen + IV_BYTES2 + TAG_BYTES2);
|
|
1167
|
-
const ct = data.subarray(mLen + IV_BYTES2 + TAG_BYTES2);
|
|
1168
|
-
const d = crypto.createDecipheriv(AES_ALGO, key, iv);
|
|
1169
|
-
d.setAuthTag(tag);
|
|
1170
|
-
return Buffer.concat([d.update(ct), d.final()]);
|
|
1171
|
-
}
|
|
1172
|
-
// ── Public API ────────────────────────────────────────────────────────────
|
|
1173
|
-
/**
|
|
1174
|
-
* Spill an evicted L1 entry to disk.
|
|
1175
|
-
*
|
|
1176
|
-
* Returns a Promise that resolves when the file is durably written. Callers
|
|
1177
|
-
* that treat the spill as fire-and-forget should do:
|
|
1178
|
-
* `void disk.save(key, entry)`
|
|
1179
|
-
*
|
|
1180
|
-
* Implementation notes:
|
|
1181
|
-
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
1182
|
-
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
1183
|
-
* on any external resource.
|
|
1184
|
-
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
1185
|
-
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
1186
|
-
*/
|
|
1187
|
-
async save(key, entry) {
|
|
1188
|
-
if (this.isForbidden(key)) return;
|
|
1189
|
-
if (entry.expiresAt <= Date.now()) return;
|
|
1190
|
-
this.ensureDir();
|
|
1191
|
-
if (!this.dirReady) return;
|
|
1192
|
-
this.ensureUsageCounted();
|
|
1193
|
-
if (this.diskUsageBytes >= this.opts.maxBytes) return;
|
|
1194
|
-
let final;
|
|
1195
|
-
try {
|
|
1196
|
-
const payload = {
|
|
1197
|
-
version: DISK_TIER_VERSION,
|
|
1198
|
-
key,
|
|
1199
|
-
entry: {
|
|
1200
|
-
...entry,
|
|
1201
|
-
data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
|
|
1202
|
-
},
|
|
1203
|
-
writtenAt: Date.now()
|
|
1204
|
-
};
|
|
1205
|
-
const packed = pack2(payload);
|
|
1206
|
-
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1207
|
-
final = this.encrypt(packed);
|
|
1208
|
-
} catch (err) {
|
|
1209
|
-
this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
|
|
1210
|
-
return;
|
|
1211
|
-
}
|
|
1212
|
-
const filePath = this.keyToPath(key);
|
|
1213
|
-
this.diskUsageBytes += final.length;
|
|
1214
|
-
this.fileCount++;
|
|
1215
|
-
try {
|
|
1216
|
-
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
1217
|
-
await fs.promises.writeFile(filePath, final, { mode: 384 });
|
|
1218
|
-
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1219
|
-
} catch (err) {
|
|
1220
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1221
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1222
|
-
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
1226
|
-
load(key) {
|
|
1227
|
-
if (this.isForbidden(key)) return null;
|
|
1228
|
-
this.ensureDir();
|
|
1229
|
-
if (!this.dirReady) return null;
|
|
1230
|
-
const filePath = this.keyToPath(key);
|
|
1231
|
-
try {
|
|
1232
|
-
if (!fs.existsSync(filePath)) return null;
|
|
1233
|
-
const stat = fs.statSync(filePath);
|
|
1234
|
-
if (stat.size > this.opts.entryMaxBytes) {
|
|
1235
|
-
fs.unlinkSync(filePath);
|
|
1236
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1237
|
-
return null;
|
|
1238
|
-
}
|
|
1239
|
-
const raw = fs.readFileSync(filePath);
|
|
1240
|
-
try {
|
|
1241
|
-
fs.unlinkSync(filePath);
|
|
1242
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1243
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1244
|
-
} catch {
|
|
1245
|
-
}
|
|
1246
|
-
let decrypted;
|
|
1247
|
-
try {
|
|
1248
|
-
decrypted = this.decrypt(raw);
|
|
1249
|
-
} catch {
|
|
1250
|
-
return null;
|
|
1251
|
-
}
|
|
1252
|
-
const payload = unpack2(decrypted);
|
|
1253
|
-
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
1254
|
-
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
1255
|
-
const entry = payload.entry;
|
|
1256
|
-
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
1257
|
-
this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
1258
|
-
return entry;
|
|
1259
|
-
} catch (err) {
|
|
1260
|
-
this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
|
|
1261
|
-
return null;
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
/** Explicitly delete a key from disk (cache invalidation). */
|
|
1265
|
-
delete(key) {
|
|
1266
|
-
const filePath = this.keyToPath(key);
|
|
1267
|
-
try {
|
|
1268
|
-
if (fs.existsSync(filePath)) {
|
|
1269
|
-
const stat = fs.statSync(filePath);
|
|
1270
|
-
fs.unlinkSync(filePath);
|
|
1271
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1272
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1273
|
-
}
|
|
1274
|
-
} catch {
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
/** Purge all expired entries. Returns number deleted. */
|
|
1278
|
-
purgeExpired() {
|
|
1279
|
-
this.ensureDir();
|
|
1280
|
-
if (!this.dirReady) return 0;
|
|
1281
|
-
let purged = 0;
|
|
1282
|
-
for (const filePath of this.walkCacheFiles()) {
|
|
1283
|
-
try {
|
|
1284
|
-
const stat = fs.statSync(filePath);
|
|
1285
|
-
if (stat.size > this.opts.entryMaxBytes) {
|
|
1286
|
-
fs.unlinkSync(filePath);
|
|
1287
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1288
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1289
|
-
purged++;
|
|
1290
|
-
continue;
|
|
1291
|
-
}
|
|
1292
|
-
const raw = fs.readFileSync(filePath);
|
|
1293
|
-
let dec;
|
|
1294
|
-
try {
|
|
1295
|
-
dec = this.decrypt(raw);
|
|
1296
|
-
} catch {
|
|
1297
|
-
fs.unlinkSync(filePath);
|
|
1298
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1299
|
-
purged++;
|
|
1300
|
-
continue;
|
|
1301
|
-
}
|
|
1302
|
-
const payload = unpack2(dec);
|
|
1303
|
-
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
|
|
1304
|
-
fs.unlinkSync(filePath);
|
|
1305
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1306
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1307
|
-
purged++;
|
|
1308
|
-
}
|
|
1309
|
-
} catch {
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
return purged;
|
|
1313
|
-
}
|
|
1314
|
-
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1315
|
-
clear() {
|
|
1316
|
-
this.ensureDir();
|
|
1317
|
-
if (!this.dirReady) return 0;
|
|
1318
|
-
let cleared = 0;
|
|
1319
|
-
for (const filePath of this.walkCacheFiles()) {
|
|
1320
|
-
try {
|
|
1321
|
-
const stat = fs.statSync(filePath);
|
|
1322
|
-
fs.unlinkSync(filePath);
|
|
1323
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1324
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1325
|
-
cleared++;
|
|
1326
|
-
} catch {
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
return cleared;
|
|
1330
|
-
}
|
|
1331
|
-
get stats() {
|
|
1332
|
-
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
1333
|
-
}
|
|
1334
|
-
};
|
|
1335
|
-
|
|
1336
|
-
// src/cache-service.ts
|
|
1337
|
-
var SNAPSHOT_VERSION = 1;
|
|
1338
|
-
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
1339
|
-
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
1340
|
-
var DEFAULT_CATEGORY_LIMITS = {
|
|
1341
|
-
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
1342
|
-
};
|
|
1343
|
-
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
1344
|
-
var L2CircuitBreaker = class {
|
|
1345
|
-
constructor(threshold, cooldownMs) {
|
|
1346
|
-
this.threshold = threshold;
|
|
1347
|
-
this.cooldownMs = cooldownMs;
|
|
1348
|
-
}
|
|
1349
|
-
threshold;
|
|
1350
|
-
cooldownMs;
|
|
1351
|
-
state = 0 /* CLOSED */;
|
|
1352
|
-
failures = 0;
|
|
1353
|
-
openedAt = 0;
|
|
1354
|
-
/** Call before each Redis attempt. Returns false when the circuit is open. */
|
|
1355
|
-
isAllowed() {
|
|
1356
|
-
if (this.state === 0 /* CLOSED */) return true;
|
|
1357
|
-
if (this.state === 2 /* HALF_OPEN */) return true;
|
|
1358
|
-
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1359
|
-
this.state = 2 /* HALF_OPEN */;
|
|
1360
|
-
return true;
|
|
1361
|
-
}
|
|
1362
|
-
return false;
|
|
1363
|
-
}
|
|
1364
|
-
/** Call on Redis success. */
|
|
1365
|
-
onSuccess() {
|
|
1366
|
-
this.failures = 0;
|
|
1367
|
-
this.state = 0 /* CLOSED */;
|
|
1368
|
-
}
|
|
1369
|
-
/** Call on Redis failure. */
|
|
1370
|
-
onFailure() {
|
|
1371
|
-
this.failures++;
|
|
1372
|
-
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1373
|
-
this.state = 1 /* OPEN */;
|
|
1374
|
-
this.openedAt = Date.now();
|
|
1375
|
-
this.failures = 0;
|
|
1376
|
-
}
|
|
1377
|
-
}
|
|
1378
|
-
get isOpen() {
|
|
1379
|
-
return this.state === 1 /* OPEN */;
|
|
1380
|
-
}
|
|
1381
|
-
get currentState() {
|
|
1382
|
-
return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
|
|
1383
|
-
}
|
|
1384
|
-
};
|
|
1385
|
-
function inferPriority(cacheKey) {
|
|
1386
|
-
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
1387
|
-
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
1388
|
-
if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
|
|
1389
|
-
return 2 /* NORMAL */;
|
|
1390
|
-
}
|
|
1391
|
-
var GLOBAL_KEY = "__tricache_instance__";
|
|
1392
|
-
var CacheService = class _CacheService {
|
|
1393
|
-
logger;
|
|
1394
|
-
enc;
|
|
1395
|
-
l1;
|
|
1396
|
-
disk;
|
|
1397
|
-
opts;
|
|
1398
|
-
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
1399
|
-
_namespace;
|
|
1400
|
-
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
1401
|
-
_redisDisabled;
|
|
1402
|
-
inflight = /* @__PURE__ */ new Map();
|
|
1403
|
-
revalidating = /* @__PURE__ */ new Set();
|
|
1404
|
-
_l1Counters = /* @__PURE__ */ new Map();
|
|
1405
|
-
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
1406
|
-
tagIndex = /* @__PURE__ */ new Map();
|
|
1407
|
-
/**
|
|
1408
|
-
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
1409
|
-
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
1410
|
-
*/
|
|
1411
|
-
dependencyIndex = /* @__PURE__ */ new Map();
|
|
1412
|
-
redis = null;
|
|
1413
|
-
redisConnecting = null;
|
|
1414
|
-
cb;
|
|
1415
|
-
snapshotLoaded = false;
|
|
1416
|
-
cleanupInterval = null;
|
|
1417
|
-
oomInterval = null;
|
|
1418
|
-
metricsInterval = null;
|
|
1419
|
-
_shutdownHandler = null;
|
|
1420
|
-
instanceId;
|
|
1421
|
-
backplaneChannel;
|
|
1422
|
-
subClient = null;
|
|
1423
|
-
counters = {
|
|
1424
|
-
gets: 0,
|
|
1425
|
-
l1Hits: 0,
|
|
1426
|
-
diskHits: 0,
|
|
1427
|
-
l2Hits: 0,
|
|
1428
|
-
fetches: 0,
|
|
1429
|
-
stampedes: 0,
|
|
1430
|
-
sets: 0,
|
|
1431
|
-
deletes: 0,
|
|
1432
|
-
swrRevalidations: 0,
|
|
1433
|
-
invSent: 0,
|
|
1434
|
-
invReceived: 0,
|
|
1435
|
-
invSkipped: 0,
|
|
1436
|
-
oomEvictions: 0,
|
|
1437
|
-
oomLastAt: null,
|
|
1438
|
-
startedAt: Date.now()
|
|
1439
|
-
};
|
|
1440
|
-
// ── Constructor (use CacheService.create() for the recommended singleton) ──
|
|
1441
|
-
constructor(options = {}) {
|
|
1442
|
-
const logger = options.logger ?? consoleLogger;
|
|
1443
|
-
this.logger = logger;
|
|
1444
|
-
const ns = options.namespace?.trim() ?? "";
|
|
1445
|
-
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
1446
|
-
this.enc = new CacheEncryption(
|
|
1447
|
-
encKeyRaw,
|
|
1448
|
-
logger,
|
|
1449
|
-
options.encryptionMode,
|
|
1450
|
-
options.previousEncryptionKey,
|
|
1451
|
-
options.previousEncryptionMode
|
|
1452
|
-
);
|
|
1453
|
-
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
1454
|
-
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
1455
|
-
this.opts = {
|
|
1456
|
-
namespace: ns,
|
|
1457
|
-
logger,
|
|
1458
|
-
l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
|
|
1459
|
-
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
1460
|
-
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits ?? {} },
|
|
1461
|
-
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
1462
|
-
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
1463
|
-
// two instances with different namespaces never share cache files.
|
|
1464
|
-
diskCacheDir: options.diskCacheDir ?? path2.join(
|
|
1465
|
-
os.tmpdir(),
|
|
1466
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
1467
|
-
),
|
|
1468
|
-
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
1469
|
-
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
1470
|
-
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
1471
|
-
redisPort: options.redisPort ?? 6379,
|
|
1472
|
-
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
1473
|
-
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
1474
|
-
encryptionKey: encKeyRaw,
|
|
1475
|
-
snapshotPath: options.snapshotPath ?? path2.join(
|
|
1476
|
-
os.tmpdir(),
|
|
1477
|
-
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
1478
|
-
),
|
|
1479
|
-
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
1480
|
-
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
1481
|
-
oomProtection: options.oomProtection ?? true,
|
|
1482
|
-
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
1483
|
-
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
1484
|
-
oomEvictPercent: options.oomEvictPercent ?? 0.2,
|
|
1485
|
-
onMetrics: options.onMetrics,
|
|
1486
|
-
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1487
|
-
staleIfError: options.staleIfError ?? 0,
|
|
1488
|
-
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1489
|
-
instanceName: options.instanceName ?? "",
|
|
1490
|
-
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1491
|
-
tracer: options.tracer,
|
|
1492
|
-
notFoundTtl: options.notFoundTtl ?? 0
|
|
1493
|
-
};
|
|
1494
|
-
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1495
|
-
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
1496
|
-
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
1497
|
-
this.disk = new DiskTier({
|
|
1498
|
-
dir: this.opts.diskCacheDir,
|
|
1499
|
-
maxBytes: this.opts.diskMaxBytes,
|
|
1500
|
-
entryMaxBytes: this.opts.diskEntryMaxBytes,
|
|
1501
|
-
forbiddenPrefixes,
|
|
1502
|
-
encryptionKey: this.enc.isEnabled ? this.enc["_key"] : null,
|
|
1503
|
-
logger
|
|
1504
|
-
});
|
|
1505
|
-
this._namespace = ns;
|
|
1506
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost;
|
|
1507
|
-
this.l1 = new SmartMemoryCache({
|
|
1508
|
-
maxBytes: this.opts.l1MaxBytes,
|
|
1509
|
-
maxEntries: this.opts.l1MaxEntries,
|
|
1510
|
-
categories: this.opts.categoryLimits,
|
|
1511
|
-
diskSpill: (key, entry) => {
|
|
1512
|
-
void this.disk.save(key, entry);
|
|
1513
|
-
},
|
|
1514
|
-
onEviction: options.onEviction,
|
|
1515
|
-
logger
|
|
1516
|
-
});
|
|
1517
|
-
if (!this.snapshotLoaded) {
|
|
1518
|
-
this.snapshotLoaded = true;
|
|
1519
|
-
this.loadSnapshot();
|
|
1520
|
-
}
|
|
1521
|
-
this._shutdownHandler = () => {
|
|
1522
|
-
this.writeSnapshot();
|
|
1523
|
-
process.exit(0);
|
|
1524
|
-
};
|
|
1525
|
-
process.once("SIGTERM", this._shutdownHandler);
|
|
1526
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
1527
|
-
this.cleanupInterval = setInterval(() => {
|
|
1528
|
-
const cleaned = this.l1.cleanup();
|
|
1529
|
-
const diskPurged = this.disk.purgeExpired();
|
|
1530
|
-
if (cleaned > 0 || diskPurged > 0) {
|
|
1531
|
-
this.logger.debug("Periodic cache cleanup", { cleaned, diskPurged });
|
|
1532
|
-
}
|
|
1533
|
-
}, 5 * 60 * 1e3);
|
|
1534
|
-
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
1535
|
-
if (this.opts.oomProtection) {
|
|
1536
|
-
this.oomInterval = setInterval(() => {
|
|
1537
|
-
const mem = process.memoryUsage();
|
|
1538
|
-
const used = mem.heapUsed / mem.heapTotal;
|
|
1539
|
-
if (used >= this.opts.oomHeapThreshold) {
|
|
1540
|
-
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
1541
|
-
this.counters.oomEvictions++;
|
|
1542
|
-
this.counters.oomLastAt = Date.now();
|
|
1543
|
-
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
1544
|
-
heapUsedPct: Math.round(used * 100),
|
|
1545
|
-
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
1546
|
-
evicted
|
|
1547
|
-
});
|
|
1548
|
-
}
|
|
1549
|
-
}, this.opts.oomCheckIntervalMs);
|
|
1550
|
-
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
1551
|
-
}
|
|
1552
|
-
if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
|
|
1553
|
-
this.metricsInterval = setInterval(() => {
|
|
1554
|
-
try {
|
|
1555
|
-
this.opts.onMetrics(this.metrics());
|
|
1556
|
-
} catch {
|
|
1557
|
-
}
|
|
1558
|
-
}, this.opts.metricsIntervalMs);
|
|
1559
|
-
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
1560
|
-
}
|
|
1561
|
-
this.instanceId = crypto2.randomBytes(8).toString("hex");
|
|
1562
|
-
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
1563
|
-
this.initBackplane();
|
|
1564
|
-
}
|
|
1565
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
1566
|
-
/**
|
|
1567
|
-
* Get (or create) the process-level singleton CacheService instance.
|
|
1568
|
-
*
|
|
1569
|
-
* Options are only applied on first call — subsequent calls return the
|
|
1570
|
-
* existing instance regardless of options passed.
|
|
1571
|
-
*
|
|
1572
|
-
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
1573
|
-
* with different namespaces return independent instances.
|
|
1574
|
-
*/
|
|
1575
|
-
static create(options) {
|
|
1576
|
-
const g = globalThis;
|
|
1577
|
-
const key = _CacheService.globalKey(options);
|
|
1578
|
-
if (!g[key]) g[key] = new _CacheService(options);
|
|
1579
|
-
return g[key];
|
|
1580
|
-
}
|
|
1581
|
-
/**
|
|
1582
|
-
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
1583
|
-
* Useful when config is fetched from a secret store at startup.
|
|
1584
|
-
*
|
|
1585
|
-
* @example
|
|
1586
|
-
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
1587
|
-
*/
|
|
1588
|
-
static async createAsync(options) {
|
|
1589
|
-
const resolved = await options;
|
|
1590
|
-
return _CacheService.create(resolved);
|
|
1591
|
-
}
|
|
1592
|
-
/** Replace the singleton (useful in tests). */
|
|
1593
|
-
static reset(options) {
|
|
1594
|
-
const g = globalThis;
|
|
1595
|
-
const key = _CacheService.globalKey(options);
|
|
1596
|
-
const existing = g[key];
|
|
1597
|
-
if (existing) existing.destroy();
|
|
1598
|
-
g[key] = new _CacheService(options);
|
|
1599
|
-
return g[key];
|
|
1600
|
-
}
|
|
1601
|
-
/** Derive the globalThis key for a given set of options. */
|
|
1602
|
-
static globalKey(options) {
|
|
1603
|
-
const ns = options?.namespace?.trim() ?? "";
|
|
1604
|
-
return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
|
|
1605
|
-
}
|
|
1606
|
-
// ── Redis connection ──────────────────────────────────────────────────────
|
|
1607
|
-
/**
|
|
1608
|
-
* Prepend the configured namespace to a raw cache key.
|
|
1609
|
-
* Returns the key unchanged when namespace is empty.
|
|
1610
|
-
*
|
|
1611
|
-
* This is the only place the namespace prefix is applied — callers always
|
|
1612
|
-
* receive and provide un-prefixed keys in the public API.
|
|
1613
|
-
*/
|
|
1614
|
-
nk(key) {
|
|
1615
|
-
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
1616
|
-
}
|
|
1617
|
-
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
1618
|
-
_jitterTtl(ttlMs) {
|
|
1619
|
-
const j = this.opts.ttlJitterFactor;
|
|
1620
|
-
if (j === 0) return ttlMs;
|
|
1621
|
-
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
1622
|
-
}
|
|
1623
|
-
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
1624
|
-
_startSpan(name) {
|
|
1625
|
-
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
1626
|
-
return { setAttribute() {
|
|
1627
|
-
return this;
|
|
1628
|
-
}, setStatus() {
|
|
1629
|
-
return this;
|
|
1630
|
-
}, end() {
|
|
1631
|
-
} };
|
|
1632
|
-
}
|
|
1633
|
-
initBackplane() {
|
|
1634
|
-
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1635
|
-
if (this.subClient) return;
|
|
1636
|
-
const sub = new RedisClient({
|
|
1637
|
-
host: this.opts.redisHost,
|
|
1638
|
-
port: this.opts.redisPort,
|
|
1639
|
-
tls: this.opts.redisTls ? {} : void 0,
|
|
1640
|
-
connectTimeout: 1e4,
|
|
1641
|
-
lazyConnect: true,
|
|
1642
|
-
maxRetriesPerRequest: null,
|
|
1643
|
-
enableAutoPipelining: false,
|
|
1644
|
-
family: 4,
|
|
1645
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
1646
|
-
});
|
|
1647
|
-
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
1648
|
-
sub.on("message", (_channel, message) => {
|
|
1649
|
-
this._handleBackplaneMessage(message);
|
|
1650
|
-
});
|
|
1651
|
-
sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
1652
|
-
channel: this.backplaneChannel,
|
|
1653
|
-
instanceId: this.instanceId
|
|
1654
|
-
})).catch((err) => this.logger.warn("Backplane: subscribe failed", {
|
|
1655
|
-
error: err.message
|
|
1656
|
-
}));
|
|
1657
|
-
this.subClient = sub;
|
|
1658
|
-
}
|
|
1659
|
-
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
1660
|
-
_handleBackplaneMessage(message) {
|
|
1661
|
-
try {
|
|
1662
|
-
const msg = JSON.parse(message);
|
|
1663
|
-
if (msg.src === this.instanceId) {
|
|
1664
|
-
this.counters.invSkipped++;
|
|
1665
|
-
return;
|
|
1666
|
-
}
|
|
1667
|
-
this.counters.invReceived++;
|
|
1668
|
-
if (msg.op === "del") {
|
|
1669
|
-
this.l1.delete(msg.key);
|
|
1670
|
-
setImmediate(() => this.disk.delete(msg.key));
|
|
1671
|
-
} else if (msg.op === "del-glob") {
|
|
1672
|
-
this.l1.deletePattern(msg.key);
|
|
1673
|
-
}
|
|
1674
|
-
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1675
|
-
op: msg.op,
|
|
1676
|
-
key: msg.key.slice(0, 60)
|
|
1677
|
-
});
|
|
1678
|
-
} catch {
|
|
1679
|
-
}
|
|
1680
|
-
}
|
|
1681
|
-
async publishInvalidation(op, key) {
|
|
1682
|
-
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1683
|
-
try {
|
|
1684
|
-
const client = await this.getRedis();
|
|
1685
|
-
await client.publish(
|
|
1686
|
-
this.backplaneChannel,
|
|
1687
|
-
JSON.stringify({ op, key, src: this.instanceId })
|
|
1688
|
-
);
|
|
1689
|
-
this.counters.invSent++;
|
|
1690
|
-
} catch {
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
|
-
async getRedis() {
|
|
1694
|
-
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
1695
|
-
if (this.redisConnecting) return this.redisConnecting;
|
|
1696
|
-
this.redisConnecting = (async () => {
|
|
1697
|
-
try {
|
|
1698
|
-
const client = new RedisClient({
|
|
1699
|
-
host: this.opts.redisHost,
|
|
1700
|
-
port: this.opts.redisPort,
|
|
1701
|
-
tls: this.opts.redisTls ? {} : void 0,
|
|
1702
|
-
connectTimeout: 1e4,
|
|
1703
|
-
lazyConnect: false,
|
|
1704
|
-
maxRetriesPerRequest: 3,
|
|
1705
|
-
enableAutoPipelining: true,
|
|
1706
|
-
keepAlive: 3e4,
|
|
1707
|
-
family: 4,
|
|
1708
|
-
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
1709
|
-
});
|
|
1710
|
-
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
1711
|
-
client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
|
|
1712
|
-
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
1713
|
-
await new Promise((resolve, reject) => {
|
|
1714
|
-
client.once("ready", resolve);
|
|
1715
|
-
client.once("error", reject);
|
|
1716
|
-
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1717
|
-
});
|
|
1718
|
-
this.cb.onSuccess();
|
|
1719
|
-
this.redis = client;
|
|
1720
|
-
this.redisConnecting = null;
|
|
1721
|
-
return client;
|
|
1722
|
-
} catch (err) {
|
|
1723
|
-
this.cb.onFailure();
|
|
1724
|
-
this.redisConnecting = null;
|
|
1725
|
-
throw err;
|
|
1726
|
-
}
|
|
1727
|
-
})();
|
|
1728
|
-
return this.redisConnecting;
|
|
1729
|
-
}
|
|
1730
|
-
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
1731
|
-
writeSnapshot(altPath) {
|
|
1732
|
-
try {
|
|
1733
|
-
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
1734
|
-
if (entries.length === 0) return;
|
|
1735
|
-
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
1736
|
-
const packed = pack3(payload);
|
|
1737
|
-
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
1738
|
-
const dest = altPath ?? this.opts.snapshotPath;
|
|
1739
|
-
fs2.writeFileSync(dest, final, { mode: 384 });
|
|
1740
|
-
this.logger.info("Cache snapshot written", {
|
|
1741
|
-
path: dest,
|
|
1742
|
-
entries: entries.length,
|
|
1743
|
-
sizeKB: Math.round(final.length / 1024),
|
|
1744
|
-
encrypted: this.enc.isEnabled
|
|
1745
|
-
});
|
|
1746
|
-
} catch (err) {
|
|
1747
|
-
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
1748
|
-
}
|
|
1749
|
-
}
|
|
1750
|
-
loadSnapshot() {
|
|
1751
|
-
const snapshotPath = this.opts.snapshotPath;
|
|
1752
|
-
try {
|
|
1753
|
-
if (!fs2.existsSync(snapshotPath)) return;
|
|
1754
|
-
const stat = fs2.statSync(snapshotPath);
|
|
1755
|
-
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
1756
|
-
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
1757
|
-
fs2.unlinkSync(snapshotPath);
|
|
1758
|
-
return;
|
|
1759
|
-
}
|
|
1760
|
-
const raw = fs2.readFileSync(snapshotPath);
|
|
1761
|
-
fs2.unlinkSync(snapshotPath);
|
|
1762
|
-
let buf;
|
|
1763
|
-
try {
|
|
1764
|
-
buf = this.enc.decryptBuffer(raw);
|
|
1765
|
-
} catch (e) {
|
|
1766
|
-
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
1767
|
-
return;
|
|
1768
|
-
}
|
|
1769
|
-
const snapshot = unpack3(buf);
|
|
1770
|
-
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
1771
|
-
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
1772
|
-
return;
|
|
1773
|
-
}
|
|
1774
|
-
const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
|
|
1775
|
-
if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
|
|
1776
|
-
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
1777
|
-
return;
|
|
1778
|
-
}
|
|
1779
|
-
if (!Array.isArray(snapshot.entries)) {
|
|
1780
|
-
this.logger.warn("Snapshot rejected: entries is not an array");
|
|
1781
|
-
return;
|
|
1782
|
-
}
|
|
1783
|
-
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
1784
|
-
this.logger.info("Cache snapshot loaded (L1 is warm)", {
|
|
1785
|
-
loaded,
|
|
1786
|
-
total: snapshot.entries.length,
|
|
1787
|
-
sizeKB: this.l1.getStats().sizeKB
|
|
1788
|
-
});
|
|
1789
|
-
} catch (err) {
|
|
1790
|
-
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
1791
|
-
try {
|
|
1792
|
-
fs2.unlinkSync(snapshotPath);
|
|
1793
|
-
} catch {
|
|
1794
|
-
}
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
1798
|
-
/**
|
|
1799
|
-
* Get a value from cache, or fetch and cache it.
|
|
1800
|
-
*
|
|
1801
|
-
* @param cacheKey - Unique key identifying this value
|
|
1802
|
-
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
1803
|
-
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
1804
|
-
* @param opts.priority - Override the auto-inferred eviction priority
|
|
1805
|
-
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
1806
|
-
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
1807
|
-
* is triggered proactively while the caller still receives the
|
|
1808
|
-
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
1809
|
-
* Requires `fetchFn` to be stable across calls.
|
|
1810
|
-
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
1811
|
-
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
1812
|
-
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
1813
|
-
* decide probabilistically rather than at a fixed threshold.
|
|
1814
|
-
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
1815
|
-
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
1816
|
-
*/
|
|
1817
|
-
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
1818
|
-
const span = this._startSpan("tricache.get");
|
|
1819
|
-
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1820
|
-
const k = this.nk(cacheKey);
|
|
1821
|
-
this.counters.gets++;
|
|
1822
|
-
const l1Hit = this.l1.get(k);
|
|
1823
|
-
if (l1Hit !== null) {
|
|
1824
|
-
if (l1Hit.isStale) {
|
|
1825
|
-
const swrGraceMs2 = (opts.swr ?? 0) * 1e3;
|
|
1826
|
-
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
1827
|
-
const priority2 = opts.priority ?? inferPriority(cacheKey);
|
|
1828
|
-
this.revalidating.add(k);
|
|
1829
|
-
void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
|
|
1830
|
-
this.counters.swrRevalidations++;
|
|
1831
|
-
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
1832
|
-
} else {
|
|
1833
|
-
this.logger.debug("L1 hit");
|
|
1834
|
-
}
|
|
1835
|
-
} else {
|
|
1836
|
-
this.logger.debug("L1 hit");
|
|
1837
|
-
if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
|
|
1838
|
-
const now = Date.now();
|
|
1839
|
-
const remaining = l1Hit.expiresAt - now;
|
|
1840
|
-
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
|
|
1841
|
-
const priority2 = opts.priority ?? inferPriority(cacheKey);
|
|
1842
|
-
const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
|
|
1843
|
-
const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
|
|
1844
|
-
if (shouldRefreshAhead || shouldXFetch) {
|
|
1845
|
-
this.revalidating.add(k);
|
|
1846
|
-
void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
|
|
1847
|
-
this.counters.swrRevalidations++;
|
|
1848
|
-
this.logger.debug(
|
|
1849
|
-
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
1850
|
-
{ cacheKey, remainingMs: remaining, ttlMs: entryTtl }
|
|
1851
|
-
);
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
}
|
|
1855
|
-
this.counters.l1Hits++;
|
|
1856
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
1857
|
-
return l1Hit.value;
|
|
1858
|
-
}
|
|
1859
|
-
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1860
|
-
const swrGraceMs = (opts.swr ?? 0) * 1e3;
|
|
1861
|
-
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
1862
|
-
if (!this._redisDisabled) {
|
|
1863
|
-
try {
|
|
1864
|
-
const client = await this.getRedis();
|
|
1865
|
-
const raw = await client.get(k);
|
|
1866
|
-
this.cb.onSuccess();
|
|
1867
|
-
if (raw) {
|
|
1868
|
-
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
1869
|
-
const parsed = JSON.parse(decrypted);
|
|
1870
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
1871
|
-
this.counters.l2Hits++;
|
|
1872
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
1873
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
1874
|
-
return parsed;
|
|
1875
|
-
}
|
|
1876
|
-
} catch (err) {
|
|
1877
|
-
this.cb.onFailure();
|
|
1878
|
-
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
1879
|
-
}
|
|
1880
|
-
}
|
|
1881
|
-
const diskHit = this.disk.load(k);
|
|
1882
|
-
if (diskHit !== null) {
|
|
1883
|
-
const promoted = this.l1.importEntries(
|
|
1884
|
-
[{ key: k, entry: diskHit }],
|
|
1885
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
1886
|
-
);
|
|
1887
|
-
if (promoted > 0) {
|
|
1888
|
-
const l1Check = this.l1.get(k);
|
|
1889
|
-
if (l1Check !== null) {
|
|
1890
|
-
this.counters.diskHits++;
|
|
1891
|
-
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
1892
|
-
span.setAttribute("cache.hit", "disk").end();
|
|
1893
|
-
return l1Check.value;
|
|
1894
|
-
}
|
|
1895
|
-
}
|
|
1896
|
-
}
|
|
1897
|
-
span.setAttribute("cache.hit", "miss");
|
|
1898
|
-
const existing = this.inflight.get(k);
|
|
1899
|
-
if (existing) {
|
|
1900
|
-
this.counters.stampedes++;
|
|
1901
|
-
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
1902
|
-
span.end();
|
|
1903
|
-
return existing;
|
|
1904
|
-
}
|
|
1905
|
-
const fetchPromise = (async () => {
|
|
1906
|
-
try {
|
|
1907
|
-
this.counters.fetches++;
|
|
1908
|
-
const fetchStart = Date.now();
|
|
1909
|
-
const data = await fetchFn();
|
|
1910
|
-
const delta = Date.now() - fetchStart;
|
|
1911
|
-
const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
1912
|
-
const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
1913
|
-
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
1914
|
-
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
1915
|
-
this.l1.set(k, data, storeTtl, priority, staleAt, delta);
|
|
1916
|
-
if (!this._redisDisabled) {
|
|
1917
|
-
try {
|
|
1918
|
-
const client = await this.getRedis();
|
|
1919
|
-
const serialized = JSON.stringify(data);
|
|
1920
|
-
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1921
|
-
await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
|
|
1922
|
-
this.cb.onSuccess();
|
|
1923
|
-
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
1924
|
-
} catch {
|
|
1925
|
-
this.cb.onFailure();
|
|
1926
|
-
this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
|
|
1927
|
-
}
|
|
1928
|
-
} else {
|
|
1929
|
-
this.logger.debug("Cached L1", { cacheKey });
|
|
1930
|
-
}
|
|
1931
|
-
return data;
|
|
1932
|
-
} finally {
|
|
1933
|
-
this.inflight.delete(k);
|
|
1934
|
-
span.end();
|
|
1935
|
-
}
|
|
1936
|
-
})();
|
|
1937
|
-
this.inflight.set(k, fetchPromise);
|
|
1938
|
-
return fetchPromise;
|
|
1939
|
-
}
|
|
1940
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
1941
|
-
try {
|
|
1942
|
-
const fetchStart = Date.now();
|
|
1943
|
-
const data = await fetchFn();
|
|
1944
|
-
const delta = Date.now() - fetchStart;
|
|
1945
|
-
const staleAt = Date.now() + ttlMs;
|
|
1946
|
-
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
|
|
1947
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1948
|
-
try {
|
|
1949
|
-
const client = await this.getRedis();
|
|
1950
|
-
const s = JSON.stringify(data);
|
|
1951
|
-
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1952
|
-
await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
|
|
1953
|
-
} catch {
|
|
1954
|
-
}
|
|
1955
|
-
}
|
|
1956
|
-
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
1957
|
-
} catch (err) {
|
|
1958
|
-
if (this.opts.staleIfError > 0) {
|
|
1959
|
-
const additionalMs = this.opts.staleIfError * 1e3;
|
|
1960
|
-
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
1961
|
-
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
1962
|
-
cacheKey,
|
|
1963
|
-
staleIfErrorSecs: this.opts.staleIfError
|
|
1964
|
-
});
|
|
1965
|
-
} else {
|
|
1966
|
-
this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
|
|
1967
|
-
}
|
|
1968
|
-
} finally {
|
|
1969
|
-
this.revalidating.delete(cacheKey);
|
|
1970
|
-
}
|
|
1971
|
-
}
|
|
1972
|
-
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1973
|
-
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1974
|
-
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1975
|
-
const span = this._startSpan("tricache.set");
|
|
1976
|
-
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1977
|
-
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1978
|
-
const p = priority ?? inferPriority(cacheKey);
|
|
1979
|
-
const k = this.nk(cacheKey);
|
|
1980
|
-
this.counters.sets++;
|
|
1981
|
-
this.l1.set(k, data, ttlMs, p);
|
|
1982
|
-
if (opts?.tags?.length) {
|
|
1983
|
-
for (const tag of opts.tags) {
|
|
1984
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1985
|
-
let members = this.tagIndex.get(tagKey);
|
|
1986
|
-
if (!members) {
|
|
1987
|
-
members = /* @__PURE__ */ new Set();
|
|
1988
|
-
this.tagIndex.set(tagKey, members);
|
|
1989
|
-
}
|
|
1990
|
-
members.add(k);
|
|
1991
|
-
}
|
|
1992
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1993
|
-
try {
|
|
1994
|
-
const client = await this.getRedis();
|
|
1995
|
-
const pl = client.pipeline();
|
|
1996
|
-
for (const tag of opts.tags) {
|
|
1997
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
1998
|
-
pl.sadd(tagKey, k);
|
|
1999
|
-
pl.expire(tagKey, ttlSeconds + 3600);
|
|
2000
|
-
}
|
|
2001
|
-
await pl.exec();
|
|
2002
|
-
this.cb.onSuccess();
|
|
2003
|
-
} catch {
|
|
2004
|
-
this.cb.onFailure();
|
|
2005
|
-
}
|
|
2006
|
-
}
|
|
2007
|
-
}
|
|
2008
|
-
if (opts?.dependsOn?.length) {
|
|
2009
|
-
for (const pattern of opts.dependsOn) {
|
|
2010
|
-
const nsPattern = this.nk(pattern);
|
|
2011
|
-
let deps = this.dependencyIndex.get(nsPattern);
|
|
2012
|
-
if (!deps) {
|
|
2013
|
-
deps = /* @__PURE__ */ new Set();
|
|
2014
|
-
this.dependencyIndex.set(nsPattern, deps);
|
|
2015
|
-
}
|
|
2016
|
-
deps.add(k);
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
2019
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2020
|
-
try {
|
|
2021
|
-
const client = await this.getRedis();
|
|
2022
|
-
const s = JSON.stringify(data);
|
|
2023
|
-
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
2024
|
-
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
2025
|
-
this.cb.onSuccess();
|
|
2026
|
-
} catch (err) {
|
|
2027
|
-
this.cb.onFailure();
|
|
2028
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
2029
|
-
}
|
|
2030
|
-
}
|
|
2031
|
-
void this.publishInvalidation("del", k);
|
|
2032
|
-
span.end();
|
|
2033
|
-
}
|
|
2034
|
-
/**
|
|
2035
|
-
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
2036
|
-
*
|
|
2037
|
-
* @example
|
|
2038
|
-
* await cache.delete('user:abc:profile'); // exact key
|
|
2039
|
-
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
2040
|
-
*/
|
|
2041
|
-
async delete(cacheKey) {
|
|
2042
|
-
const span = this._startSpan("tricache.delete");
|
|
2043
|
-
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
2044
|
-
const isPattern = cacheKey.includes("*");
|
|
2045
|
-
const k = this.nk(cacheKey);
|
|
2046
|
-
this.counters.deletes++;
|
|
2047
|
-
if (isPattern) {
|
|
2048
|
-
this.l1.deletePattern(k);
|
|
2049
|
-
} else {
|
|
2050
|
-
this.l1.delete(k);
|
|
2051
|
-
this.disk.delete(k);
|
|
2052
|
-
this._cascadeDependencies(k);
|
|
2053
|
-
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
2054
|
-
}
|
|
2055
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2056
|
-
try {
|
|
2057
|
-
const client = await this.getRedis();
|
|
2058
|
-
if (isPattern) {
|
|
2059
|
-
const stream = client.scanStream({ match: k, count: 100 });
|
|
2060
|
-
const keys = [];
|
|
2061
|
-
await new Promise((resolve, reject) => {
|
|
2062
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2063
|
-
stream.on("end", resolve);
|
|
2064
|
-
stream.on("error", reject);
|
|
2065
|
-
});
|
|
2066
|
-
if (keys.length > 0) await client.del(...keys);
|
|
2067
|
-
} else {
|
|
2068
|
-
await client.del(k);
|
|
2069
|
-
}
|
|
2070
|
-
this.cb.onSuccess();
|
|
2071
|
-
} catch (err) {
|
|
2072
|
-
this.cb.onFailure();
|
|
2073
|
-
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
2077
|
-
span.end();
|
|
2078
|
-
}
|
|
2079
|
-
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
2080
|
-
/**
|
|
2081
|
-
* Atomically increment a counter in Redis. Returns the new value.
|
|
2082
|
-
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
2083
|
-
*/
|
|
2084
|
-
async increment(cacheKey, ttlSeconds) {
|
|
2085
|
-
const k = this.nk(cacheKey);
|
|
2086
|
-
if (this._redisDisabled) {
|
|
2087
|
-
const now = Date.now();
|
|
2088
|
-
const ttlMs = (ttlSeconds ?? 60) * 1e3;
|
|
2089
|
-
const entry = this._l1Counters.get(k);
|
|
2090
|
-
if (entry && entry.expiresAt > now) {
|
|
2091
|
-
entry.value++;
|
|
2092
|
-
return entry.value;
|
|
2093
|
-
}
|
|
2094
|
-
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
2095
|
-
return 1;
|
|
2096
|
-
}
|
|
2097
|
-
try {
|
|
2098
|
-
const client = await this.getRedis();
|
|
2099
|
-
const count = await client.incr(k);
|
|
2100
|
-
if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
|
|
2101
|
-
return count;
|
|
2102
|
-
} catch (err) {
|
|
2103
|
-
this.logger.error("increment: Redis error", { cacheKey }, err);
|
|
2104
|
-
return 0;
|
|
2105
|
-
}
|
|
2106
|
-
}
|
|
2107
|
-
// ── Clear / Rebalance / TTL ────────────────────────────────────────────────
|
|
2108
|
-
/**
|
|
2109
|
-
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
2110
|
-
*
|
|
2111
|
-
* @example
|
|
2112
|
-
* await cache.clear(); // flush everything
|
|
2113
|
-
* await cache.clear('user:abc'); // flush all keys for one user
|
|
2114
|
-
*/
|
|
2115
|
-
async clear(prefix) {
|
|
2116
|
-
this.counters.deletes++;
|
|
2117
|
-
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
2118
|
-
if (k) {
|
|
2119
|
-
this.l1.deletePattern(k);
|
|
2120
|
-
} else {
|
|
2121
|
-
this.l1.clear();
|
|
2122
|
-
this.disk.clear();
|
|
2123
|
-
this._l1Counters.clear();
|
|
2124
|
-
this.tagIndex.clear();
|
|
2125
|
-
}
|
|
2126
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2127
|
-
try {
|
|
2128
|
-
const client = await this.getRedis();
|
|
2129
|
-
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
2130
|
-
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2131
|
-
const keys = [];
|
|
2132
|
-
await new Promise((resolve, reject) => {
|
|
2133
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2134
|
-
stream.on("end", resolve);
|
|
2135
|
-
stream.on("error", reject);
|
|
2136
|
-
});
|
|
2137
|
-
if (keys.length > 0) await client.del(...keys);
|
|
2138
|
-
} catch (err) {
|
|
2139
|
-
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
2140
|
-
}
|
|
2141
|
-
}
|
|
2142
|
-
void this.publishInvalidation(
|
|
2143
|
-
"del-glob",
|
|
2144
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
2145
|
-
);
|
|
2146
|
-
}
|
|
2147
|
-
/**
|
|
2148
|
-
* Evict L1 entries that violate the current category or global capacity limits.
|
|
2149
|
-
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
2150
|
-
* Returns the number of entries evicted.
|
|
2151
|
-
*/
|
|
2152
|
-
rebalance() {
|
|
2153
|
-
return this.l1.rebalance();
|
|
2154
|
-
}
|
|
2155
|
-
/**
|
|
2156
|
-
* Return the remaining TTL in seconds for a key currently in L1.
|
|
2157
|
-
* Returns null if the key is absent from L1 or has already expired.
|
|
2158
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
2159
|
-
*/
|
|
2160
|
-
ttl(cacheKey) {
|
|
2161
|
-
return this.l1.ttl(this.nk(cacheKey));
|
|
2162
|
-
}
|
|
2163
|
-
/**
|
|
2164
|
-
* Return true if the key exists in L1 and has not expired.
|
|
2165
|
-
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
2166
|
-
*/
|
|
2167
|
-
has(cacheKey) {
|
|
2168
|
-
return this.l1.has(this.nk(cacheKey));
|
|
2169
|
-
}
|
|
2170
|
-
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
2171
|
-
/**
|
|
2172
|
-
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
2173
|
-
*
|
|
2174
|
-
* @example
|
|
2175
|
-
* for (const key of cache.keys()) console.log(key);
|
|
2176
|
-
*/
|
|
2177
|
-
*keys() {
|
|
2178
|
-
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2179
|
-
for (const key of this.l1.liveKeys()) {
|
|
2180
|
-
yield prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
/**
|
|
2184
|
-
* Lazily yield every non-expired L1 value.
|
|
2185
|
-
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
2186
|
-
*
|
|
2187
|
-
* @example
|
|
2188
|
-
* for (const val of cache.values<User>()) console.log(val.id);
|
|
2189
|
-
*/
|
|
2190
|
-
*values() {
|
|
2191
|
-
yield* this.l1.liveValues();
|
|
2192
|
-
}
|
|
2193
|
-
/**
|
|
2194
|
-
* Lazily yield every non-expired L1 [key, value] pair.
|
|
2195
|
-
* Keys are stripped of their namespace prefix.
|
|
2196
|
-
*
|
|
2197
|
-
* @example
|
|
2198
|
-
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
2199
|
-
*/
|
|
2200
|
-
*entries() {
|
|
2201
|
-
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2202
|
-
for (const [key, entry] of this.l1.liveEntries()) {
|
|
2203
|
-
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2204
|
-
yield [k, entry.value !== void 0 ? entry.value : entry.data];
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
/**
|
|
2208
|
-
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
2209
|
-
* Returns `false` if the key is absent or already expired.
|
|
2210
|
-
*
|
|
2211
|
-
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
2212
|
-
*/
|
|
2213
|
-
async touch(cacheKey, newTtlSeconds) {
|
|
2214
|
-
const k = this.nk(cacheKey);
|
|
2215
|
-
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
2216
|
-
if (hit && !this._redisDisabled) {
|
|
2217
|
-
try {
|
|
2218
|
-
const client = await this.getRedis();
|
|
2219
|
-
void client.expire(k, newTtlSeconds);
|
|
2220
|
-
} catch {
|
|
2221
|
-
}
|
|
2222
|
-
}
|
|
2223
|
-
return hit;
|
|
2224
|
-
}
|
|
2225
|
-
/**
|
|
2226
|
-
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
2227
|
-
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
2228
|
-
*
|
|
2229
|
-
* @example
|
|
2230
|
-
* const fresh = cache.getIfFresh('user:123');
|
|
2231
|
-
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
2232
|
-
*/
|
|
2233
|
-
getIfFresh(cacheKey) {
|
|
2234
|
-
const k = this.nk(cacheKey);
|
|
2235
|
-
const entry = this.l1.getEntry(k);
|
|
2236
|
-
if (!entry) return null;
|
|
2237
|
-
const now = Date.now();
|
|
2238
|
-
if (entry.expiresAt <= now) return null;
|
|
2239
|
-
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
2240
|
-
return entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
2241
|
-
}
|
|
2242
|
-
/**
|
|
2243
|
-
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
2244
|
-
* Preserves input ordering. Uses inflight coalescing per key.
|
|
2245
|
-
*
|
|
2246
|
-
* @param keys - Array of cache keys.
|
|
2247
|
-
* @param fetchFn - Called with only the keys that missed L1.
|
|
2248
|
-
* @param ttl - TTL in seconds for newly fetched values.
|
|
2249
|
-
*/
|
|
2250
|
-
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
2251
|
-
const result = new Array(keys.length);
|
|
2252
|
-
const missIndexes = [];
|
|
2253
|
-
const missKeys = [];
|
|
2254
|
-
for (let i = 0; i < keys.length; i++) {
|
|
2255
|
-
const entry = this.l1.getEntry(this.nk(keys[i]));
|
|
2256
|
-
if (entry && entry.expiresAt > Date.now()) {
|
|
2257
|
-
result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
2258
|
-
this.counters.l1Hits++;
|
|
2259
|
-
} else {
|
|
2260
|
-
missIndexes.push(i);
|
|
2261
|
-
missKeys.push(keys[i]);
|
|
2262
|
-
}
|
|
2263
|
-
}
|
|
2264
|
-
if (missKeys.length > 0) {
|
|
2265
|
-
const fetched = await fetchFn(missKeys);
|
|
2266
|
-
for (let j = 0; j < missKeys.length; j++) {
|
|
2267
|
-
const v = fetched[missKeys[j]];
|
|
2268
|
-
result[missIndexes[j]] = v;
|
|
2269
|
-
if (v !== void 0) {
|
|
2270
|
-
await this.set(missKeys[j], v, ttl, priority);
|
|
2271
|
-
}
|
|
2272
|
-
}
|
|
2273
|
-
}
|
|
2274
|
-
return result;
|
|
2275
|
-
}
|
|
2276
|
-
/**
|
|
2277
|
-
* Batch write — set multiple entries in a single call.
|
|
2278
|
-
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
2279
|
-
*
|
|
2280
|
-
* @example
|
|
2281
|
-
* await cache.mset({
|
|
2282
|
-
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
2283
|
-
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
2284
|
-
* });
|
|
2285
|
-
*/
|
|
2286
|
-
async mset(entries) {
|
|
2287
|
-
const keys = Object.keys(entries);
|
|
2288
|
-
await Promise.all(keys.map((key) => {
|
|
2289
|
-
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
2290
|
-
const hasOpts = tags?.length || dependsOn?.length;
|
|
2291
|
-
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
2292
|
-
}));
|
|
2293
|
-
}
|
|
2294
|
-
/**
|
|
2295
|
-
* Batch delete — delete multiple exact keys in a single call.
|
|
2296
|
-
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
2297
|
-
*
|
|
2298
|
-
* @example
|
|
2299
|
-
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
2300
|
-
*/
|
|
2301
|
-
async mdel(keys) {
|
|
2302
|
-
await Promise.all(keys.map((k) => this.delete(k)));
|
|
2303
|
-
}
|
|
2304
|
-
/**
|
|
2305
|
-
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
2306
|
-
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
2307
|
-
* the local snapshot is unavailable or too stale.
|
|
2308
|
-
*
|
|
2309
|
-
* Returns the number of keys loaded into L1.
|
|
2310
|
-
*
|
|
2311
|
-
* @example
|
|
2312
|
-
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
2313
|
-
* const loaded = await cache.warmFromL2('org:*');
|
|
2314
|
-
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
2315
|
-
*/
|
|
2316
|
-
async warmFromL2(pattern) {
|
|
2317
|
-
if (this._redisDisabled) return 0;
|
|
2318
|
-
try {
|
|
2319
|
-
const client = await this.getRedis();
|
|
2320
|
-
const nsPattern = this.nk(pattern);
|
|
2321
|
-
const matchedKeys = [];
|
|
2322
|
-
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
2323
|
-
await new Promise((resolve, reject) => {
|
|
2324
|
-
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
2325
|
-
stream.on("end", resolve);
|
|
2326
|
-
stream.on("error", reject);
|
|
2327
|
-
});
|
|
2328
|
-
if (matchedKeys.length === 0) {
|
|
2329
|
-
this.cb.onSuccess();
|
|
2330
|
-
return 0;
|
|
2331
|
-
}
|
|
2332
|
-
const pl = client.pipeline();
|
|
2333
|
-
for (const k of matchedKeys) pl.get(k);
|
|
2334
|
-
const results = await pl.exec();
|
|
2335
|
-
this.cb.onSuccess();
|
|
2336
|
-
let loaded = 0;
|
|
2337
|
-
const now = Date.now();
|
|
2338
|
-
for (let i = 0; i < matchedKeys.length; i++) {
|
|
2339
|
-
const [err, raw] = results[i];
|
|
2340
|
-
if (err || raw == null) continue;
|
|
2341
|
-
try {
|
|
2342
|
-
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2343
|
-
const parsed = JSON.parse(decrypted);
|
|
2344
|
-
const remainingMs = 10 * 60 * 1e3;
|
|
2345
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
2346
|
-
loaded++;
|
|
2347
|
-
} catch {
|
|
2348
|
-
}
|
|
2349
|
-
}
|
|
2350
|
-
void now;
|
|
2351
|
-
this.logger.info("warmFromL2 complete", {
|
|
2352
|
-
pattern,
|
|
2353
|
-
matched: matchedKeys.length,
|
|
2354
|
-
loaded
|
|
2355
|
-
});
|
|
2356
|
-
return loaded;
|
|
2357
|
-
} catch (err) {
|
|
2358
|
-
this.cb.onFailure();
|
|
2359
|
-
this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
|
|
2360
|
-
return 0;
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
/**
|
|
2364
|
-
* Invalidate all keys associated with a tag.
|
|
2365
|
-
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
2366
|
-
*
|
|
2367
|
-
* @example
|
|
2368
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
2369
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
2370
|
-
*/
|
|
2371
|
-
async invalidateTag(tag) {
|
|
2372
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
2373
|
-
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
2374
|
-
for (const k of members) {
|
|
2375
|
-
this.l1.delete(k);
|
|
2376
|
-
this.disk.delete(k);
|
|
2377
|
-
}
|
|
2378
|
-
this.tagIndex.delete(tagKey);
|
|
2379
|
-
if (!this._redisDisabled) {
|
|
2380
|
-
try {
|
|
2381
|
-
const client = await this.getRedis();
|
|
2382
|
-
const redisMembers = await client.smembers(tagKey);
|
|
2383
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
2384
|
-
if (toDelete.length > 0) {
|
|
2385
|
-
await client.del(...toDelete, tagKey);
|
|
2386
|
-
} else {
|
|
2387
|
-
await client.del(tagKey);
|
|
2388
|
-
}
|
|
2389
|
-
} catch (err) {
|
|
2390
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
2391
|
-
}
|
|
2392
|
-
}
|
|
2393
|
-
}
|
|
2394
|
-
/**
|
|
2395
|
-
* Measure L1 / disk / Redis latency.
|
|
2396
|
-
* Useful for health checks and dashboards.
|
|
2397
|
-
*
|
|
2398
|
-
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
2399
|
-
* `l2` is `null` when Redis is disabled.
|
|
2400
|
-
*/
|
|
2401
|
-
async ping() {
|
|
2402
|
-
const t0 = Date.now();
|
|
2403
|
-
this.l1.has("__ping__");
|
|
2404
|
-
const l1 = Date.now() - t0;
|
|
2405
|
-
const t1 = Date.now();
|
|
2406
|
-
void this.disk.stats;
|
|
2407
|
-
const disk = Date.now() - t1;
|
|
2408
|
-
let l2 = null;
|
|
2409
|
-
if (!this._redisDisabled) {
|
|
2410
|
-
try {
|
|
2411
|
-
const client = await this.getRedis();
|
|
2412
|
-
const t2 = Date.now();
|
|
2413
|
-
await client.ping();
|
|
2414
|
-
l2 = Date.now() - t2;
|
|
2415
|
-
} catch {
|
|
2416
|
-
l2 = null;
|
|
2417
|
-
}
|
|
2418
|
-
}
|
|
2419
|
-
return { l1, disk, l2 };
|
|
2420
|
-
}
|
|
2421
|
-
/**
|
|
2422
|
-
* Export all live L1 entries to Redis via a single pipeline.
|
|
2423
|
-
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
2424
|
-
* Returns the number of keys written.
|
|
2425
|
-
*/
|
|
2426
|
-
async drainToL2() {
|
|
2427
|
-
if (this._redisDisabled) return 0;
|
|
2428
|
-
try {
|
|
2429
|
-
const client = await this.getRedis();
|
|
2430
|
-
const entries = this.l1.exportEntries([]);
|
|
2431
|
-
const now = Date.now();
|
|
2432
|
-
if (entries.length === 0) return 0;
|
|
2433
|
-
const pl = client.pipeline();
|
|
2434
|
-
for (const { key, entry } of entries) {
|
|
2435
|
-
const remainingMs = entry.expiresAt - now;
|
|
2436
|
-
if (remainingMs <= 0) continue;
|
|
2437
|
-
const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
|
|
2438
|
-
const s = JSON.stringify(entry.value);
|
|
2439
|
-
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
2440
|
-
pl.setex(key, ttlSecs, stored);
|
|
2441
|
-
}
|
|
2442
|
-
await pl.exec();
|
|
2443
|
-
return entries.length;
|
|
2444
|
-
} catch (err) {
|
|
2445
|
-
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
2446
|
-
return 0;
|
|
2447
|
-
}
|
|
2448
|
-
}
|
|
2449
|
-
// ── Stats ─────────────────────────────────────────────────────────────
|
|
2450
|
-
stats() {
|
|
2451
|
-
return {
|
|
2452
|
-
l1: this.l1.getStats(),
|
|
2453
|
-
disk: this.disk.stats
|
|
2454
|
-
};
|
|
2455
|
-
}
|
|
2456
|
-
// ── Conditional write ─────────────────────────────────────────────────
|
|
2457
|
-
/**
|
|
2458
|
-
* Write `value` only if the key is not already cached.
|
|
2459
|
-
* Returns `true` if the write happened, `false` if the key already existed.
|
|
2460
|
-
*
|
|
2461
|
-
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
2462
|
-
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
2463
|
-
* multiple instances. L1 is populated on success.
|
|
2464
|
-
*
|
|
2465
|
-
* @example
|
|
2466
|
-
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
2467
|
-
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
2468
|
-
*/
|
|
2469
|
-
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
2470
|
-
const k = this.nk(cacheKey);
|
|
2471
|
-
if (this.l1.has(k)) return false;
|
|
2472
|
-
if (!this._redisDisabled) {
|
|
2473
|
-
try {
|
|
2474
|
-
const client = await this.getRedis();
|
|
2475
|
-
const serialized = JSON.stringify(value);
|
|
2476
|
-
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
2477
|
-
const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
|
|
2478
|
-
this.cb.onSuccess();
|
|
2479
|
-
if (result === null) return false;
|
|
2480
|
-
} catch (err) {
|
|
2481
|
-
this.cb.onFailure();
|
|
2482
|
-
this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
|
|
2483
|
-
if (this.l1.has(k)) return false;
|
|
2484
|
-
}
|
|
2485
|
-
}
|
|
2486
|
-
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
2487
|
-
const p = priority ?? inferPriority(cacheKey);
|
|
2488
|
-
this.l1.set(k, value, ttlMs, p);
|
|
2489
|
-
this.counters.sets++;
|
|
2490
|
-
return true;
|
|
2491
|
-
}
|
|
2492
|
-
// ── Hot key introspection ─────────────────────────────────────────────
|
|
2493
|
-
/**
|
|
2494
|
-
* Return the top-N live L1 keys by historical access frequency.
|
|
2495
|
-
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
2496
|
-
* whose historical frequency exceeds their current in-memory hit count.
|
|
2497
|
-
*
|
|
2498
|
-
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
2499
|
-
* collection overhead.
|
|
2500
|
-
*
|
|
2501
|
-
* @param n - Maximum number of keys to return. Default: 10.
|
|
2502
|
-
*
|
|
2503
|
-
* @example
|
|
2504
|
-
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
2505
|
-
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
2506
|
-
*/
|
|
2507
|
-
hotKeys(n = 10) {
|
|
2508
|
-
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2509
|
-
return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
|
|
2510
|
-
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
2511
|
-
hits,
|
|
2512
|
-
sizeBytes
|
|
2513
|
-
}));
|
|
2514
|
-
}
|
|
2515
|
-
// ── Dependency cascade helpers ────────────────────────────────────────
|
|
2516
|
-
/**
|
|
2517
|
-
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
2518
|
-
* pattern that may contain `*` wildcards).
|
|
2519
|
-
*/
|
|
2520
|
-
_matchesGlob(key, pattern) {
|
|
2521
|
-
if (!pattern.includes("*")) return key === pattern;
|
|
2522
|
-
const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
|
|
2523
|
-
return re.test(key);
|
|
2524
|
-
}
|
|
2525
|
-
/**
|
|
2526
|
-
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
2527
|
-
* that was registered via `dependsOn` and whose source pattern matches.
|
|
2528
|
-
*/
|
|
2529
|
-
_cascadeDependencies(deletedKey) {
|
|
2530
|
-
for (const [pattern, dependents] of this.dependencyIndex) {
|
|
2531
|
-
if (!this._matchesGlob(deletedKey, pattern)) continue;
|
|
2532
|
-
for (const dep of dependents) {
|
|
2533
|
-
if (dep === deletedKey) continue;
|
|
2534
|
-
this.l1.delete(dep);
|
|
2535
|
-
this.disk.delete(dep);
|
|
2536
|
-
void this.publishInvalidation("del", dep);
|
|
2537
|
-
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
2538
|
-
trigger: deletedKey.slice(0, 60),
|
|
2539
|
-
dependent: dep.slice(0, 60)
|
|
2540
|
-
});
|
|
2541
|
-
}
|
|
2542
|
-
}
|
|
2543
|
-
}
|
|
2544
|
-
// ── Observability ──────────────────────────────────────────────────────────────────
|
|
2545
|
-
/** Return a full metrics snapshot. */
|
|
2546
|
-
metrics() {
|
|
2547
|
-
const c = this.counters;
|
|
2548
|
-
const l1s = this.l1.getStats();
|
|
2549
|
-
const div = (n, d) => d > 0 ? n / d : 0;
|
|
2550
|
-
return {
|
|
2551
|
-
namespace: this.opts.namespace,
|
|
2552
|
-
uptimeMs: Date.now() - c.startedAt,
|
|
2553
|
-
gets: {
|
|
2554
|
-
total: c.gets,
|
|
2555
|
-
l1Hits: c.l1Hits,
|
|
2556
|
-
l1HitRate: div(c.l1Hits, c.gets),
|
|
2557
|
-
diskHits: c.diskHits,
|
|
2558
|
-
diskHitRate: div(c.diskHits, c.gets),
|
|
2559
|
-
l2Hits: c.l2Hits,
|
|
2560
|
-
l2HitRate: div(c.l2Hits, c.gets),
|
|
2561
|
-
fetches: c.fetches,
|
|
2562
|
-
fetchRate: div(c.fetches, c.gets),
|
|
2563
|
-
stampedePrevented: c.stampedes
|
|
2564
|
-
},
|
|
2565
|
-
sets: { total: c.sets },
|
|
2566
|
-
deletes: { total: c.deletes },
|
|
2567
|
-
revalidations: { total: c.swrRevalidations },
|
|
2568
|
-
bloom: {
|
|
2569
|
-
checksTotal: l1s.bloom.checks,
|
|
2570
|
-
falsePositives: l1s.bloom.falsePositives,
|
|
2571
|
-
falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks)
|
|
2572
|
-
},
|
|
2573
|
-
compression: {
|
|
2574
|
-
entriesCompressed: l1s.compression.compressed,
|
|
2575
|
-
entriesUncompressed: l1s.compression.uncompressed,
|
|
2576
|
-
bytesSaved: l1s.compression.bytesSaved
|
|
2577
|
-
},
|
|
2578
|
-
backplane: {
|
|
2579
|
-
enabled: this.opts.invalidationBackplane && !this._redisDisabled,
|
|
2580
|
-
sent: c.invSent,
|
|
2581
|
-
received: c.invReceived,
|
|
2582
|
-
skipped: c.invSkipped
|
|
2583
|
-
},
|
|
2584
|
-
l2CircuitBreaker: {
|
|
2585
|
-
state: this.cb.currentState
|
|
2586
|
-
},
|
|
2587
|
-
oom: {
|
|
2588
|
-
enabled: this.opts.oomProtection,
|
|
2589
|
-
evictions: c.oomEvictions,
|
|
2590
|
-
lastTriggeredAt: c.oomLastAt
|
|
2591
|
-
},
|
|
2592
|
-
l1: {
|
|
2593
|
-
entries: l1s.entries,
|
|
2594
|
-
sizeBytes: this.l1.memoryUsage,
|
|
2595
|
-
maxBytes: this.opts.l1MaxBytes
|
|
2596
|
-
},
|
|
2597
|
-
disk: this.disk.stats
|
|
2598
|
-
};
|
|
2599
|
-
}
|
|
2600
|
-
/**
|
|
2601
|
-
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
2602
|
-
* Paste the result into your `/metrics` endpoint.
|
|
2603
|
-
*
|
|
2604
|
-
* @param m - Snapshot returned by `cache.metrics()`
|
|
2605
|
-
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
2606
|
-
*/
|
|
2607
|
-
static toPrometheusText(m, prefix = "tricache", instanceName) {
|
|
2608
|
-
const parts = [];
|
|
2609
|
-
if (m.namespace) parts.push(`namespace="${m.namespace}"`);
|
|
2610
|
-
if (instanceName) parts.push(`instance="${instanceName}"`);
|
|
2611
|
-
const lbl = parts.length ? `{${parts.join(",")}}` : "";
|
|
2612
|
-
const lines = [];
|
|
2613
|
-
const counter = (name, val, help) => {
|
|
2614
|
-
lines.push(`# HELP ${prefix}_${name}_total ${help}`);
|
|
2615
|
-
lines.push(`# TYPE ${prefix}_${name}_total counter`);
|
|
2616
|
-
lines.push(`${prefix}_${name}_total${lbl} ${val}`);
|
|
2617
|
-
};
|
|
2618
|
-
const gauge = (name, val, help) => {
|
|
2619
|
-
lines.push(`# HELP ${prefix}_${name} ${help}`);
|
|
2620
|
-
lines.push(`# TYPE ${prefix}_${name} gauge`);
|
|
2621
|
-
lines.push(`${prefix}_${name}${lbl} ${val}`);
|
|
2622
|
-
};
|
|
2623
|
-
counter("gets", m.gets.total, "Total get() calls");
|
|
2624
|
-
counter("l1_hits", m.gets.l1Hits, "L1 RAM cache hits");
|
|
2625
|
-
counter("disk_hits", m.gets.diskHits, "L1.5 disk tier hits");
|
|
2626
|
-
counter("l2_hits", m.gets.l2Hits, "L2 Redis hits");
|
|
2627
|
-
counter("fetches", m.gets.fetches, "fetchFn calls (cache misses)");
|
|
2628
|
-
counter("stampedes_prevented", m.gets.stampedePrevented, "Coalesced duplicate inflight requests");
|
|
2629
|
-
counter("sets", m.sets.total, "Total set() calls");
|
|
2630
|
-
counter("deletes", m.deletes.total, "Total delete() calls");
|
|
2631
|
-
counter("swr_revalidations", m.revalidations.total, "Stale-While-Revalidate background refreshes");
|
|
2632
|
-
gauge("l1_hit_rate", m.gets.l1HitRate, "Fraction of gets served from L1 RAM (0-1)");
|
|
2633
|
-
gauge("disk_hit_rate", m.gets.diskHitRate, "Fraction of gets served from disk (0-1)");
|
|
2634
|
-
gauge("l2_hit_rate", m.gets.l2HitRate, "Fraction of gets served from Redis (0-1)");
|
|
2635
|
-
gauge("fetch_rate", m.gets.fetchRate, "Fraction of gets calling fetchFn (0-1)");
|
|
2636
|
-
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
2637
|
-
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
2638
|
-
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
2639
|
-
gauge(
|
|
2640
|
-
"bloom_false_positive_rate",
|
|
2641
|
-
m.bloom.falsePositiveRate,
|
|
2642
|
-
"Bloom filter false-positive rate; increase capacity if > 0.01"
|
|
2643
|
-
);
|
|
2644
|
-
gauge(
|
|
2645
|
-
"compression_bytes_saved",
|
|
2646
|
-
m.compression.bytesSaved,
|
|
2647
|
-
"Approximate bytes saved by msgpackr compression"
|
|
2648
|
-
);
|
|
2649
|
-
if (m.backplane.enabled) {
|
|
2650
|
-
counter("backplane_sent", m.backplane.sent, "Invalidation messages sent via Pub/Sub");
|
|
2651
|
-
counter("backplane_received", m.backplane.received, "Invalidation messages received from peers");
|
|
2652
|
-
}
|
|
2653
|
-
if (m.oom.enabled) {
|
|
2654
|
-
counter(
|
|
2655
|
-
"oom_evictions",
|
|
2656
|
-
m.oom.evictions,
|
|
2657
|
-
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
2658
|
-
);
|
|
2659
|
-
}
|
|
2660
|
-
return lines.join("\n");
|
|
2661
|
-
}
|
|
2662
|
-
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
2663
|
-
/** Close Redis connections and stop all background timers. */
|
|
2664
|
-
async destroy() {
|
|
2665
|
-
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
2666
|
-
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
2667
|
-
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
2668
|
-
if (this._shutdownHandler) {
|
|
2669
|
-
process.off("SIGTERM", this._shutdownHandler);
|
|
2670
|
-
process.off("SIGINT", this._shutdownHandler);
|
|
2671
|
-
this._shutdownHandler = null;
|
|
2672
|
-
}
|
|
2673
|
-
if (this.subClient) {
|
|
2674
|
-
try {
|
|
2675
|
-
await this.subClient.quit();
|
|
2676
|
-
} catch {
|
|
2677
|
-
}
|
|
2678
|
-
this.subClient = null;
|
|
2679
|
-
}
|
|
2680
|
-
if (this.redis) {
|
|
2681
|
-
try {
|
|
2682
|
-
await this.redis.disconnect();
|
|
2683
|
-
} catch {
|
|
2684
|
-
}
|
|
2685
|
-
this.redis = null;
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
};
|
|
2689
|
-
export {
|
|
2690
|
-
CacheEncryption,
|
|
2691
|
-
CachePriority,
|
|
2692
|
-
CacheService,
|
|
2693
|
-
DiskTier,
|
|
2694
|
-
SmartMemoryCache,
|
|
2695
|
-
WasmBloomFilter,
|
|
2696
|
-
consoleLogger
|
|
2697
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* tricache — three-tier cache for Node.js
|
|
3
|
+
*
|
|
4
|
+
* L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
|
|
5
|
+
*
|
|
6
|
+
* Quick start:
|
|
7
|
+
* import { CacheService, CachePriority } from 'tricache';
|
|
8
|
+
*
|
|
9
|
+
* const cache = CacheService.create({ redisHost: 'localhost' });
|
|
10
|
+
*
|
|
11
|
+
* const user = await cache.get(
|
|
12
|
+
* `user:${userId}`,
|
|
13
|
+
* () => db.users.findById(userId),
|
|
14
|
+
* 300, // 5-minute TTL
|
|
15
|
+
* );
|
|
16
|
+
*
|
|
17
|
+
* await cache.delete(`user:${userId}`);
|
|
18
|
+
*/
|
|
19
|
+
export { CacheService } from './cache-service';
|
|
20
|
+
export { CacheEncryption } from './encryption';
|
|
21
|
+
export { SmartMemoryCache } from './smart-memory-cache';
|
|
22
|
+
export { DiskTier } from './disk-tier';
|
|
23
|
+
export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
24
|
+
export { CachePriority, consoleLogger, } from './types';
|
|
25
|
+
//# sourceMappingURL=index.js.map
|