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.
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
3
+ *
4
+ * Four modes are supported via the `encryptionMode` CacheOption:
5
+ *
6
+ * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
7
+ * │ Mode │ Key bytes │ Notes │
8
+ * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
9
+ * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
10
+ * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
11
+ * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
12
+ * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
13
+ * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
14
+ * │ │ │ Use only for dev or non-sensitive data. │
15
+ * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
16
+ *
17
+ * Key generation:
18
+ * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
19
+ * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
20
+ * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
21
+ * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
22
+ *
23
+ * Redis envelope formats:
24
+ * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
25
+ * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
26
+ * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
27
+ * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
28
+ *
29
+ * Disk envelope formats:
30
+ * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
31
+ * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
32
+ * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
33
+ * TRIC1XOR | key⊕data[N] ← XOR
34
+ */
35
+ import { createCipheriv, createDecipheriv, randomFillSync } from 'crypto';
36
+ // ── GCM constants ─────────────────────────────────────────────────────────────
37
+ const IV_BYTES = 12; // 96-bit IV (NIST recommended for GCM)
38
+ const TAG_BYTES = 16; // 128-bit auth tag
39
+ // ── Redis prefixes ────────────────────────────────────────────────────────────
40
+ const PREFIX_256 = 'enc:v1:'; // AES-256-GCM (legacy-compatible)
41
+ const PREFIX_128 = 'a128:v1:'; // AES-128-GCM
42
+ const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
43
+ // ── Binary magic headers (8 bytes each) ──────────────────────────────────────
44
+ /** "TRIC1ENC" — AES-256-GCM disk blob */
45
+ const MAGIC_256 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x45, 0x4e, 0x43]);
46
+ /** "TRIC1128" — AES-128-GCM disk blob */
47
+ const MAGIC_128 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x31, 0x32, 0x38]);
48
+ /** "TRIC1XOR" — XOR-obfuscated disk blob */
49
+ const MAGIC_XOR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x58, 0x4f, 0x52]);
50
+ /** "TRIC1CTR" — AES-128-CTR disk blob */
51
+ const MAGIC_CTR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x43, 0x54, 0x52]);
52
+ const MAGIC_LEN = 8;
53
+ // ── CTR constants ─────────────────────────────────────────────────────────────
54
+ /** AES-128-CTR IV is the full 128-bit AES block used as the initial counter block. */
55
+ const CTR_IV_BYTES = 16;
56
+ const PREFIX_CTR = 'ctr:v1:'; // AES-128-CTR (no auth tag)
57
+ // ── IV pool ───────────────────────────────────────────────────────────────────
58
+ // randomFillSync() fills the existing Buffer in-place — no allocation on refill.
59
+ const IV_POOL_COUNT = 64;
60
+ export class CacheEncryption {
61
+ _key = null;
62
+ _mode;
63
+ _prevKey = null;
64
+ _prevMode = 'aes-256-gcm';
65
+ // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
66
+ _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
67
+ _ivOffset = IV_BYTES * IV_POOL_COUNT; // start exhausted → fill on first use
68
+ /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
69
+ _nextIV() {
70
+ if (this._ivOffset >= this._ivPool.length) {
71
+ randomFillSync(this._ivPool); // fills existing Buffer in-place — zero allocation
72
+ this._ivOffset = 0;
73
+ }
74
+ const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES); // Buffer (not Uint8Array)
75
+ this._ivOffset += IV_BYTES;
76
+ return iv;
77
+ }
78
+ // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
79
+ _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
80
+ _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
81
+ /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
82
+ _nextCtrIV() {
83
+ if (this._ctrIvOffset >= this._ctrIvPool.length) {
84
+ randomFillSync(this._ctrIvPool);
85
+ this._ctrIvOffset = 0;
86
+ }
87
+ const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
88
+ this._ctrIvOffset += CTR_IV_BYTES;
89
+ return iv;
90
+ }
91
+ /**
92
+ * XOR `data` with the key, cycling through key bytes.
93
+ * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
94
+ *
95
+ * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
96
+ * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
97
+ * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
98
+ * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
99
+ *
100
+ * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
101
+ */
102
+ _xorBuffer(data) {
103
+ const key = this._key;
104
+ const klen = key.length;
105
+ const len = data.length;
106
+ const out = Buffer.allocUnsafe(len);
107
+ if (klen % 4 === 0 &&
108
+ len >= 4 &&
109
+ data.byteOffset % 4 === 0 &&
110
+ out.byteOffset % 4 === 0 &&
111
+ key.byteOffset % 4 === 0) {
112
+ const wordCount = len >>> 2;
113
+ const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
114
+ const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
115
+ const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
116
+ const kLen32 = key32.length;
117
+ for (let i = 0; i < wordCount; i++) {
118
+ out32[i] = data32[i] ^ key32[i % kLen32];
119
+ }
120
+ // 0–3 trailing bytes
121
+ for (let i = wordCount << 2; i < len; i++) {
122
+ out[i] = data[i] ^ key[i % klen];
123
+ }
124
+ return out;
125
+ }
126
+ // Fallback: buffer not 4-byte-aligned or key length not a multiple of 4
127
+ for (let i = 0; i < len; i++) {
128
+ out[i] = data[i] ^ key[i % klen];
129
+ }
130
+ return out;
131
+ }
132
+ constructor(keyBase64, logger, mode = 'aes-256-gcm', previousKeyBase64, previousMode) {
133
+ this._mode = mode;
134
+ if (!keyBase64) {
135
+ if (process.env.NODE_ENV === 'production') {
136
+ logger.warn('SECURITY: encryption key not set — cache data stored unencrypted at rest', { hint: 'Set encryptionKey option or CACHE_ENCRYPTION_KEY env var' });
137
+ }
138
+ return;
139
+ }
140
+ try {
141
+ const buf = Buffer.from(keyBase64, 'base64');
142
+ const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
143
+ if (requiredLen > 0 && buf.length !== requiredLen) {
144
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
145
+ }
146
+ if (buf.length < 1) {
147
+ throw new Error('XOR key must be at least 1 byte');
148
+ }
149
+ this._key = buf;
150
+ if (mode === 'xor') {
151
+ logger.warn('Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.');
152
+ }
153
+ else {
154
+ logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
155
+ }
156
+ }
157
+ catch (err) {
158
+ logger.error('Invalid encryption key — falling back to plaintext', {}, err);
159
+ }
160
+ if (previousKeyBase64) {
161
+ try {
162
+ this._prevMode = previousMode ?? mode;
163
+ this._prevKey = Buffer.from(previousKeyBase64, 'base64');
164
+ logger.debug('Previous encryption key loaded for key rotation fallback');
165
+ }
166
+ catch (err) {
167
+ logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: err.message });
168
+ }
169
+ }
170
+ }
171
+ get isEnabled() { return this._key !== null; }
172
+ // ── String (Redis) ────────────────────────────────────────────────────────
173
+ /**
174
+ * Encrypt a string for Redis storage.
175
+ * Returns a mode-prefixed base64 string when a key is configured;
176
+ * otherwise returns the original string unchanged (backward-compatible).
177
+ */
178
+ encrypt(plaintext) {
179
+ if (!this._key)
180
+ return plaintext;
181
+ if (this._mode === 'xor') {
182
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
183
+ const masked = this._xorBuffer(Buffer.from(plaintext, 'utf8'));
184
+ return PREFIX_XOR + masked.toString('base64');
185
+ }
186
+ if (this._mode === 'aes-128-ctr') {
187
+ const iv = this._nextCtrIV();
188
+ const c = createCipheriv('aes-128-ctr', this._key, iv);
189
+ const enc = c.update(plaintext, 'utf8'); // CTR: stream cipher — final() emits no bytes
190
+ c.final();
191
+ const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length);
192
+ iv.copy(out, 0);
193
+ enc.copy(out, CTR_IV_BYTES);
194
+ return PREFIX_CTR + out.toString('base64');
195
+ }
196
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
197
+ const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
198
+ const iv = this._nextIV();
199
+ const c = createCipheriv(algo, this._key, iv);
200
+ const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
201
+ c.final(); // finalise — makes auth tag available
202
+ const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
203
+ iv.copy(out, 0);
204
+ c.getAuthTag().copy(out, IV_BYTES);
205
+ enc.copy(out, IV_BYTES + TAG_BYTES);
206
+ return prefix + out.toString('base64');
207
+ }
208
+ /**
209
+ * Decrypt a Redis value.
210
+ * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
211
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
212
+ */
213
+ decrypt(value) {
214
+ try {
215
+ return this._decryptWithKey(value, this._key, this._mode);
216
+ }
217
+ catch (primaryErr) {
218
+ if (this._prevKey) {
219
+ try {
220
+ return this._decryptWithKey(value, this._prevKey, this._prevMode);
221
+ }
222
+ catch { /* ignore — fall through to re-throw primary */ }
223
+ }
224
+ throw primaryErr;
225
+ }
226
+ }
227
+ _decryptWithKey(value, key, mode) {
228
+ if (value.startsWith(PREFIX_XOR)) {
229
+ if (!key)
230
+ throw new Error('Cannot decrypt: encryption key is not set');
231
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
232
+ const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
233
+ // XOR is self-inverse; use the provided key regardless of mode
234
+ const klen = key.length;
235
+ const len = masked.length;
236
+ const out = Buffer.allocUnsafe(len);
237
+ for (let i = 0; i < len; i++)
238
+ out[i] = masked[i] ^ key[i % klen];
239
+ return out.toString('utf8');
240
+ }
241
+ if (value.startsWith(PREFIX_CTR)) {
242
+ if (!key)
243
+ throw new Error('Cannot decrypt: encryption key is not set');
244
+ const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
245
+ const iv = combined.subarray(0, CTR_IV_BYTES);
246
+ const ct = combined.subarray(CTR_IV_BYTES);
247
+ const d = createDecipheriv('aes-128-ctr', key, iv);
248
+ const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
249
+ d.final();
250
+ return plain.toString('utf8');
251
+ }
252
+ const is256 = value.startsWith(PREFIX_256);
253
+ const is128 = value.startsWith(PREFIX_128);
254
+ if (!is256 && !is128)
255
+ return value;
256
+ if (!key)
257
+ throw new Error('Cannot decrypt: encryption key is not set');
258
+ const prefix = is128 ? PREFIX_128 : PREFIX_256;
259
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
260
+ const combined = Buffer.from(value.slice(prefix.length), 'base64');
261
+ const iv = combined.subarray(0, IV_BYTES);
262
+ const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
263
+ const ct = combined.subarray(IV_BYTES + TAG_BYTES);
264
+ const d = createDecipheriv(algo, key, iv);
265
+ d.setAuthTag(tag);
266
+ const plain = d.update(ct); // GCM: final() emits no bytes
267
+ d.final(); // verifies auth tag — throws on tamper
268
+ return plain.toString('utf8');
269
+ void mode; // mode is used implicitly via prefix detection
270
+ }
271
+ // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
272
+ /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
273
+ encryptBuffer(data) {
274
+ if (!this._key)
275
+ return data;
276
+ if (this._mode === 'xor') {
277
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
278
+ const masked = this._xorBuffer(data);
279
+ const out = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
280
+ MAGIC_XOR.copy(out, 0);
281
+ masked.copy(out, MAGIC_LEN);
282
+ return out;
283
+ }
284
+ if (this._mode === 'aes-128-ctr') {
285
+ const iv = this._nextCtrIV();
286
+ const c = createCipheriv('aes-128-ctr', this._key, iv);
287
+ const enc = c.update(data); // CTR: stream cipher — final() emits no bytes
288
+ c.final();
289
+ // Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
290
+ const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length);
291
+ MAGIC_CTR.copy(out, 0);
292
+ iv.copy(out, MAGIC_LEN);
293
+ enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
294
+ return out;
295
+ }
296
+ const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
297
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
298
+ const iv = this._nextIV();
299
+ const c = createCipheriv(algo, this._key, iv);
300
+ const enc = c.update(data); // GCM: final() emits no bytes
301
+ c.final(); // finalise — makes auth tag available
302
+ // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
303
+ const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
304
+ magic.copy(out, 0);
305
+ iv.copy(out, MAGIC_LEN);
306
+ c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
307
+ enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
308
+ return out;
309
+ }
310
+ /**
311
+ * Decrypt a raw Buffer from disk/snapshot.
312
+ * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
313
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
314
+ */
315
+ decryptBuffer(data) {
316
+ try {
317
+ return this._decryptBufferWithKey(data, this._key);
318
+ }
319
+ catch (primaryErr) {
320
+ if (this._prevKey) {
321
+ try {
322
+ return this._decryptBufferWithKey(data, this._prevKey);
323
+ }
324
+ catch { /* ignore — re-throw primary */ }
325
+ }
326
+ throw primaryErr;
327
+ }
328
+ }
329
+ _decryptBufferWithKey(data, key) {
330
+ if (data.length < MAGIC_LEN)
331
+ return data;
332
+ const magic = data.subarray(0, MAGIC_LEN);
333
+ if (magic.equals(MAGIC_XOR)) {
334
+ if (!key)
335
+ throw new Error('Cannot decrypt buffer: encryption key is not set');
336
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
337
+ const raw = data.subarray(MAGIC_LEN);
338
+ const klen = key.length;
339
+ const out = Buffer.allocUnsafe(raw.length);
340
+ for (let i = 0; i < raw.length; i++)
341
+ out[i] = raw[i] ^ key[i % klen];
342
+ return out;
343
+ }
344
+ if (magic.equals(MAGIC_CTR)) {
345
+ if (!key)
346
+ throw new Error('Cannot decrypt buffer: encryption key is not set');
347
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
348
+ const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
349
+ const d = createDecipheriv('aes-128-ctr', key, iv);
350
+ const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
351
+ d.final();
352
+ return plain;
353
+ }
354
+ const is256 = magic.equals(MAGIC_256);
355
+ const is128 = magic.equals(MAGIC_128);
356
+ if (!is256 && !is128)
357
+ return data;
358
+ if (!key)
359
+ throw new Error('Cannot decrypt buffer: encryption key is not set');
360
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
361
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
362
+ const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
363
+ const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
364
+ const d = createDecipheriv(algo, key, iv);
365
+ d.setAuthTag(tag);
366
+ const plain = d.update(ct); // GCM: final() emits no bytes
367
+ d.final(); // verifies auth tag — throws on tamper
368
+ return plain;
369
+ }
370
+ }
371
+ //# sourceMappingURL=encryption.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption.js","sourceRoot":"","sources":["../src/encryption.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAO1E,iFAAiF;AACjF,MAAM,QAAQ,GAAI,EAAE,CAAC,CAAC,uCAAuC;AAC7D,MAAM,SAAS,GAAG,EAAE,CAAC,CAAC,mBAAmB;AAEzC,iFAAiF;AACjF,MAAM,U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C,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAClC,IAAI,CAAC,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;QAC9E,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC;QACnD,MAAM,EAAE,GAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,GAAG,QAAQ,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,GAAG,QAAQ,EAAE,SAAS,GAAG,QAAQ,GAAG,SAAS,CAAC,CAAC;QAClF,MAAM,EAAE,GAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,GAAG,QAAQ,GAAG,SAAS,CAAC,CAAC;QAC5D,MAAM,CAAC,GAAK,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;QAC5C,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QAClB,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAE,8BAA8B;QAC3D,CAAC,CAAC,KAAK,EAAE,CAAC,CAAmB,uCAAuC;QACpE,OAAO,KAAK,CAAC;IACf,CAAC;CACF"}
package/dist/index.cjs CHANGED
@@ -449,6 +449,7 @@ var WasmBloomFilter = class {
449
449
  };
450
450
 
451
451
  // src/smart-memory-cache.ts
452
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0 };
452
453
  var EVICTION_BATCH_PERCENT = 0.2;
453
454
  var JsBloomFilter = class {
454
455
  bits;
@@ -553,32 +554,35 @@ var CountMinSketch = class {
553
554
  }
554
555
  return h;
555
556
  }
556
- /** Four independent bit-mixes from one FNV-1a seed. */
557
- hashes(key) {
557
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
558
+ increment(key) {
558
559
  const h = this.fnv32(key);
559
560
  const h1 = (h ^ h >>> 16) >>> 0;
560
561
  const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
561
562
  const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
562
563
  const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
563
- return [h1, h2, h3, h4];
564
- }
565
- /** Record one access. Decays all counters when the insertion threshold is crossed. */
566
- increment(key) {
567
- const [h1, h2, h3, h4] = this.hashes(key);
568
564
  const t = this.table;
569
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
570
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
571
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
572
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
565
+ const i0 = h1 & SKETCH_MASK;
566
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
567
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
568
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
569
+ if (t[i0] < 65535) t[i0]++;
570
+ if (t[i1] < 65535) t[i1]++;
571
+ if (t[i2] < 65535) t[i2]++;
572
+ if (t[i3] < 65535) t[i3]++;
573
573
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
574
574
  }
575
575
  /** Minimum-across-rows frequency estimate. */
576
576
  estimate(key) {
577
- const [h1, h2, h3, h4] = this.hashes(key);
577
+ const h = this.fnv32(key);
578
+ const h1 = (h ^ h >>> 16) >>> 0;
579
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
580
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
581
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
578
582
  const t = this.table;
579
583
  return Math.min(
580
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
581
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
584
+ t[h1 & SKETCH_MASK],
585
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
582
586
  t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
583
587
  t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
584
588
  );
@@ -764,12 +768,14 @@ var SmartMemoryCache = class {
764
768
  }
765
769
  entry.hits++;
766
770
  entry.lastAccess = now;
767
- this.sketch.increment(key);
768
- const cat = this.getCategory(key);
769
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
771
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
770
772
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
771
- const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
772
- return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
773
+ _hit.value = value;
774
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
775
+ _hit.expiresAt = entry.expiresAt;
776
+ _hit.ttlMs = entry.ttlMs;
777
+ _hit.delta = entry.delta;
778
+ return _hit;
773
779
  }
774
780
  set(key, data, ttlMs, priority = 2, staleAt, delta) {
775
781
  const packed = (0, import_msgpackr.pack)(data);
@@ -1455,6 +1461,7 @@ var CacheService = class _CacheService {
1455
1461
  redisConnecting = null;
1456
1462
  cb;
1457
1463
  snapshotLoaded = false;
1464
+ _readyPromise = Promise.resolve();
1458
1465
  cleanupInterval = null;
1459
1466
  oomInterval = null;
1460
1467
  metricsInterval = null;
@@ -1531,7 +1538,8 @@ var CacheService = class _CacheService {
1531
1538
  instanceName: options.instanceName ?? "",
1532
1539
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1533
1540
  tracer: options.tracer,
1534
- notFoundTtl: options.notFoundTtl ?? 0
1541
+ notFoundTtl: options.notFoundTtl ?? 0,
1542
+ warmKeys: options.warmKeys
1535
1543
  };
1536
1544
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1537
1545
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1603,6 +1611,9 @@ var CacheService = class _CacheService {
1603
1611
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
1604
1612
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
1605
1613
  this.initBackplane();
1614
+ if (this.opts.warmKeys) {
1615
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
1616
+ }
1606
1617
  }
1607
1618
  // ── Singleton factory ─────────────────────────────────────────────────────
1608
1619
  /**
@@ -1710,6 +1721,7 @@ var CacheService = class _CacheService {
1710
1721
  if (msg.op === "del") {
1711
1722
  this.l1.delete(msg.key);
1712
1723
  setImmediate(() => this.disk.delete(msg.key));
1724
+ this._cascadeDependencies(msg.key);
1713
1725
  } else if (msg.op === "del-glob") {
1714
1726
  this.l1.deletePattern(msg.key);
1715
1727
  }
@@ -1880,10 +1892,10 @@ var CacheService = class _CacheService {
1880
1892
  const now = Date.now();
1881
1893
  const remaining = l1Hit.expiresAt - now;
1882
1894
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1883
- const priority2 = opts.priority ?? inferPriority(cacheKey);
1884
1895
  const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1885
1896
  const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1886
1897
  if (shouldRefreshAhead || shouldXFetch) {
1898
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1887
1899
  this.revalidating.add(k);
1888
1900
  void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1889
1901
  this.counters.swrRevalidations++;
@@ -2287,7 +2299,8 @@ var CacheService = class _CacheService {
2287
2299
  *
2288
2300
  * @param keys - Array of cache keys.
2289
2301
  * @param fetchFn - Called with only the keys that missed L1.
2290
- * @param ttl - TTL in seconds for newly fetched values.
2302
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
2303
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
2291
2304
  */
2292
2305
  async mget(keys, fetchFn, ttl = 300, priority) {
2293
2306
  const result = new Array(keys.length);
@@ -2309,12 +2322,27 @@ var CacheService = class _CacheService {
2309
2322
  const v = fetched[missKeys[j]];
2310
2323
  result[missIndexes[j]] = v;
2311
2324
  if (v !== void 0) {
2312
- await this.set(missKeys[j], v, ttl, priority);
2325
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
2326
+ await this.set(missKeys[j], v, resolvedTtl, priority);
2313
2327
  }
2314
2328
  }
2315
2329
  }
2316
2330
  return result;
2317
2331
  }
2332
+ /**
2333
+ * Returns a Promise that resolves once the cache is fully initialised and any
2334
+ * startup warming configured via `warmKeys` has completed.
2335
+ *
2336
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
2337
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
2338
+ *
2339
+ * @example
2340
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
2341
+ * await cache.ready(); // gate traffic until warm
2342
+ */
2343
+ ready() {
2344
+ return this._readyPromise;
2345
+ }
2318
2346
  /**
2319
2347
  * Batch write — set multiple entries in a single call.
2320
2348
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
package/dist/index.d.cts CHANGED
@@ -418,6 +418,12 @@ interface CacheOptions {
418
418
  * Default: `30 000` ms (30 s).
419
419
  */
420
420
  l2CircuitBreakerCooldownMs?: number;
421
+ /**
422
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
423
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
424
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
425
+ */
426
+ warmKeys?: string;
421
427
  }
422
428
 
423
429
  /**
@@ -462,6 +468,7 @@ declare class CacheService {
462
468
  private redisConnecting;
463
469
  private readonly cb;
464
470
  private snapshotLoaded;
471
+ private _readyPromise;
465
472
  private cleanupInterval;
466
473
  private oomInterval;
467
474
  private metricsInterval;
@@ -627,9 +634,22 @@ declare class CacheService {
627
634
  *
628
635
  * @param keys - Array of cache keys.
629
636
  * @param fetchFn - Called with only the keys that missed L1.
630
- * @param ttl - TTL in seconds for newly fetched values.
637
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
638
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
639
+ */
640
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
641
+ /**
642
+ * Returns a Promise that resolves once the cache is fully initialised and any
643
+ * startup warming configured via `warmKeys` has completed.
644
+ *
645
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
646
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
647
+ *
648
+ * @example
649
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
650
+ * await cache.ready(); // gate traffic until warm
631
651
  */
632
- mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
652
+ ready(): Promise<void>;
633
653
  /**
634
654
  * Batch write — set multiple entries in a single call.
635
655
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.