tricache 0.5.0 → 0.6.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 +32 -0
- package/dist/cache-service.d.ts +54 -1
- package/dist/cache-service.d.ts.map +1 -1
- package/dist/cache-service.js +353 -59
- package/dist/cache-service.js.map +1 -1
- package/dist/disk-tier.d.ts +74 -7
- package/dist/disk-tier.d.ts.map +1 -1
- package/dist/disk-tier.js +512 -28
- package/dist/disk-tier.js.map +1 -1
- package/dist/encryption.d.ts +2 -0
- package/dist/encryption.d.ts.map +1 -1
- package/dist/encryption.js +55 -33
- package/dist/encryption.js.map +1 -1
- package/dist/index.cjs +952 -155
- package/dist/index.d.cts +269 -8
- package/dist/smart-memory-cache.d.ts +30 -0
- package/dist/smart-memory-cache.d.ts.map +1 -1
- package/dist/smart-memory-cache.js +216 -36
- package/dist/smart-memory-cache.js.map +1 -1
- package/dist/types.d.ts +109 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -1
- package/dist/wasm/bloom-filter-wasm.js +5 -21
- package/dist/wasm/bloom-filter-wasm.js.map +1 -1
- package/package.json +11 -10
- package/src/cache-service.ts +394 -57
- package/src/disk-tier.ts +481 -27
- package/src/encryption.ts +61 -34
- package/src/smart-memory-cache.ts +213 -41
- package/src/types.ts +117 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
package/src/encryption.ts
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* TRIC1XOR | key⊕data[N] ← XOR
|
|
34
34
|
*/
|
|
35
35
|
|
|
36
|
-
import { createCipheriv, createDecipheriv, randomFillSync } from 'crypto';
|
|
36
|
+
import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync, type KeyObject } from 'crypto';
|
|
37
37
|
import type { ILogger } from './types';
|
|
38
38
|
|
|
39
39
|
// ── Public type ───────────────────────────────────────────────────────────────
|
|
@@ -71,9 +71,11 @@ const PREFIX_CTR = 'ctr:v1:'; // AES-128-CTR (no auth tag)
|
|
|
71
71
|
const IV_POOL_COUNT = 64;
|
|
72
72
|
|
|
73
73
|
export class CacheEncryption {
|
|
74
|
-
private _key:
|
|
74
|
+
private _key: Buffer | null = null; // raw bytes — used only for XOR
|
|
75
|
+
private _keyObj: KeyObject | null = null; // parsed KeyObject — used for all AES modes
|
|
75
76
|
private readonly _mode: EncryptionMode;
|
|
76
|
-
private _prevKey:
|
|
77
|
+
private _prevKey: Buffer | null = null;
|
|
78
|
+
private _prevKeyObj: KeyObject | null = null;
|
|
77
79
|
private _prevMode: EncryptionMode = 'aes-256-gcm';
|
|
78
80
|
|
|
79
81
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
@@ -179,6 +181,19 @@ export class CacheEncryption {
|
|
|
179
181
|
throw new Error('XOR key must be at least 1 byte');
|
|
180
182
|
}
|
|
181
183
|
this._key = buf;
|
|
184
|
+
if (mode !== 'xor') {
|
|
185
|
+
this._keyObj = createSecretKey(buf);
|
|
186
|
+
// Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
|
|
187
|
+
// because OpenSSL initialises internal state on demand. Paying that cost now
|
|
188
|
+
// (at construction) guarantees every production encrypt/decrypt call is fast.
|
|
189
|
+
const _wc = createCipheriv(
|
|
190
|
+
mode,
|
|
191
|
+
this._keyObj,
|
|
192
|
+
Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
|
|
193
|
+
);
|
|
194
|
+
_wc.update(Buffer.alloc(0));
|
|
195
|
+
_wc.final();
|
|
196
|
+
}
|
|
182
197
|
if (mode === 'xor') {
|
|
183
198
|
logger.warn(
|
|
184
199
|
'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
|
|
@@ -194,6 +209,16 @@ export class CacheEncryption {
|
|
|
194
209
|
try {
|
|
195
210
|
this._prevMode = previousMode ?? mode;
|
|
196
211
|
this._prevKey = Buffer.from(previousKeyBase64, 'base64');
|
|
212
|
+
if (this._prevMode !== 'xor') {
|
|
213
|
+
this._prevKeyObj = createSecretKey(this._prevKey);
|
|
214
|
+
const _wc = createCipheriv(
|
|
215
|
+
this._prevMode,
|
|
216
|
+
this._prevKeyObj,
|
|
217
|
+
Buffer.alloc(this._prevMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
|
|
218
|
+
);
|
|
219
|
+
_wc.update(Buffer.alloc(0));
|
|
220
|
+
_wc.final();
|
|
221
|
+
}
|
|
197
222
|
logger.debug('Previous encryption key loaded for key rotation fallback');
|
|
198
223
|
} catch (err) {
|
|
199
224
|
logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
|
|
@@ -219,18 +244,19 @@ export class CacheEncryption {
|
|
|
219
244
|
}
|
|
220
245
|
if (this._mode === 'aes-128-ctr') {
|
|
221
246
|
const iv = this._nextCtrIV();
|
|
222
|
-
const c = createCipheriv('aes-128-ctr', this.
|
|
223
|
-
const enc = c.update(plaintext, 'utf8');
|
|
224
|
-
c.final();
|
|
225
|
-
const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length);
|
|
247
|
+
const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
|
|
248
|
+
const enc = c.update(plaintext, 'utf8');
|
|
249
|
+
const fin = c.final(); // CTR: almost always empty — captured defensively
|
|
250
|
+
const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
|
|
226
251
|
iv.copy(out, 0);
|
|
227
252
|
enc.copy(out, CTR_IV_BYTES);
|
|
253
|
+
if (fin.length > 0) fin.copy(out, CTR_IV_BYTES + enc.length);
|
|
228
254
|
return PREFIX_CTR + out.toString('base64');
|
|
229
255
|
}
|
|
230
256
|
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
231
257
|
const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
|
|
232
258
|
const iv = this._nextIV();
|
|
233
|
-
const c = createCipheriv(algo, this.
|
|
259
|
+
const c = createCipheriv(algo, this._keyObj!, iv);
|
|
234
260
|
const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
|
|
235
261
|
c.final(); // finalise — makes auth tag available
|
|
236
262
|
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
@@ -247,18 +273,18 @@ export class CacheEncryption {
|
|
|
247
273
|
*/
|
|
248
274
|
decrypt(value: string): string {
|
|
249
275
|
try {
|
|
250
|
-
return this._decryptWithKey(value, this._key, this._mode);
|
|
276
|
+
return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
|
|
251
277
|
} catch (primaryErr) {
|
|
252
278
|
if (this._prevKey) {
|
|
253
279
|
try {
|
|
254
|
-
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
280
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
|
|
255
281
|
} catch { /* ignore — fall through to re-throw primary */ }
|
|
256
282
|
}
|
|
257
283
|
throw primaryErr;
|
|
258
284
|
}
|
|
259
285
|
}
|
|
260
286
|
|
|
261
|
-
private _decryptWithKey(value: string, key: Buffer | null, mode: EncryptionMode): string {
|
|
287
|
+
private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null, mode: EncryptionMode): string {
|
|
262
288
|
if (value.startsWith(PREFIX_XOR)) {
|
|
263
289
|
if (!key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
264
290
|
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
@@ -271,31 +297,31 @@ export class CacheEncryption {
|
|
|
271
297
|
return out.toString('utf8');
|
|
272
298
|
}
|
|
273
299
|
if (value.startsWith(PREFIX_CTR)) {
|
|
274
|
-
if (!
|
|
300
|
+
if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
|
|
275
301
|
const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
|
|
276
302
|
const iv = combined.subarray(0, CTR_IV_BYTES);
|
|
277
303
|
const ct = combined.subarray(CTR_IV_BYTES);
|
|
278
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
279
|
-
const plain = d.update(ct);
|
|
280
|
-
d.final();
|
|
281
|
-
return plain.toString('utf8');
|
|
304
|
+
const d = createDecipheriv('aes-128-ctr', keyObj, iv);
|
|
305
|
+
const plain = d.update(ct);
|
|
306
|
+
const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
|
|
307
|
+
return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
|
|
282
308
|
}
|
|
283
309
|
const is256 = value.startsWith(PREFIX_256);
|
|
284
310
|
const is128 = value.startsWith(PREFIX_128);
|
|
285
311
|
if (!is256 && !is128) return value;
|
|
286
|
-
if (!
|
|
312
|
+
if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
|
|
287
313
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
288
314
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
289
315
|
const combined = Buffer.from(value.slice(prefix.length), 'base64');
|
|
290
316
|
const iv = combined.subarray(0, IV_BYTES);
|
|
291
317
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
292
318
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
293
|
-
const d = createDecipheriv(algo,
|
|
319
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
294
320
|
d.setAuthTag(tag);
|
|
295
321
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
296
322
|
d.final(); // verifies auth tag — throws on tamper
|
|
297
323
|
return plain.toString('utf8');
|
|
298
|
-
void mode; // mode
|
|
324
|
+
void mode; void key; // mode and raw key used implicitly (mode via prefix; key via keyObj for AES, directly for XOR)
|
|
299
325
|
}
|
|
300
326
|
|
|
301
327
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
@@ -313,20 +339,21 @@ export class CacheEncryption {
|
|
|
313
339
|
}
|
|
314
340
|
if (this._mode === 'aes-128-ctr') {
|
|
315
341
|
const iv = this._nextCtrIV();
|
|
316
|
-
const c = createCipheriv('aes-128-ctr', this.
|
|
317
|
-
const enc = c.update(data);
|
|
318
|
-
c.final();
|
|
342
|
+
const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
|
|
343
|
+
const enc = c.update(data);
|
|
344
|
+
const fin = c.final(); // CTR: almost always empty — captured defensively
|
|
319
345
|
// Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
|
|
320
|
-
const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length);
|
|
346
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length + fin.length);
|
|
321
347
|
MAGIC_CTR.copy(out, 0);
|
|
322
348
|
iv.copy(out, MAGIC_LEN);
|
|
323
349
|
enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
|
|
350
|
+
if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
|
|
324
351
|
return out;
|
|
325
352
|
}
|
|
326
353
|
const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
|
|
327
354
|
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
328
355
|
const iv = this._nextIV();
|
|
329
|
-
const c = createCipheriv(algo, this.
|
|
356
|
+
const c = createCipheriv(algo, this._keyObj!, iv);
|
|
330
357
|
const enc = c.update(data); // GCM: final() emits no bytes
|
|
331
358
|
c.final(); // finalise — makes auth tag available
|
|
332
359
|
// Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
|
|
@@ -345,18 +372,18 @@ export class CacheEncryption {
|
|
|
345
372
|
*/
|
|
346
373
|
decryptBuffer(data: Buffer): Buffer {
|
|
347
374
|
try {
|
|
348
|
-
return this._decryptBufferWithKey(data, this._key);
|
|
375
|
+
return this._decryptBufferWithKey(data, this._key, this._keyObj);
|
|
349
376
|
} catch (primaryErr) {
|
|
350
377
|
if (this._prevKey) {
|
|
351
378
|
try {
|
|
352
|
-
return this._decryptBufferWithKey(data, this._prevKey);
|
|
379
|
+
return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
|
|
353
380
|
} catch { /* ignore — re-throw primary */ }
|
|
354
381
|
}
|
|
355
382
|
throw primaryErr;
|
|
356
383
|
}
|
|
357
384
|
}
|
|
358
385
|
|
|
359
|
-
private _decryptBufferWithKey(data: Buffer, key: Buffer | null): Buffer {
|
|
386
|
+
private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
|
|
360
387
|
if (data.length < MAGIC_LEN) return data;
|
|
361
388
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
362
389
|
|
|
@@ -371,23 +398,23 @@ export class CacheEncryption {
|
|
|
371
398
|
}
|
|
372
399
|
|
|
373
400
|
if (magic.equals(MAGIC_CTR)) {
|
|
374
|
-
if (!
|
|
401
|
+
if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
375
402
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
376
403
|
const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
377
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
378
|
-
const plain = d.update(ct);
|
|
379
|
-
d.final();
|
|
380
|
-
return plain;
|
|
404
|
+
const d = createDecipheriv('aes-128-ctr', keyObj, iv);
|
|
405
|
+
const plain = d.update(ct);
|
|
406
|
+
const fin = d.final(); // CTR: almost always empty — captured defensively
|
|
407
|
+
return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
|
|
381
408
|
}
|
|
382
409
|
const is256 = magic.equals(MAGIC_256);
|
|
383
410
|
const is128 = magic.equals(MAGIC_128);
|
|
384
411
|
if (!is256 && !is128) return data;
|
|
385
|
-
if (!
|
|
412
|
+
if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
386
413
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
387
414
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
388
415
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
389
416
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
390
|
-
const d = createDecipheriv(algo,
|
|
417
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
391
418
|
d.setAuthTag(tag);
|
|
392
419
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
393
420
|
d.final(); // verifies auth tag — throws on tamper
|
|
@@ -17,13 +17,17 @@ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger,
|
|
|
17
17
|
|
|
18
18
|
// Reusable return object for get() — eliminates one heap allocation per hot read.
|
|
19
19
|
// Safe because JS is single-threaded: callers consume all fields before the next get().
|
|
20
|
-
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined };
|
|
20
|
+
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0 };
|
|
21
21
|
import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
/** Fraction of candidates evicted in one pass when a limit is exceeded */
|
|
26
26
|
const EVICTION_BATCH_PERCENT = 0.2;
|
|
27
|
+
/** Reservoir sample window for smartEvict() — Redis-style. */
|
|
28
|
+
const EVICTION_SAMPLE = 16;
|
|
29
|
+
/** Number of lowest-scored candidates evicted per smartEvict() call. */
|
|
30
|
+
const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
|
|
27
31
|
|
|
28
32
|
// ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
|
|
29
33
|
|
|
@@ -93,15 +97,35 @@ class JsBloomFilter {
|
|
|
93
97
|
|
|
94
98
|
type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
|
|
95
99
|
|
|
96
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Return a bloom filter sized for `maxEntries` at a ~1 % false-positive target.
|
|
102
|
+
*
|
|
103
|
+
* The WASM filter is hardcoded at 100 K bits (k = 7), which holds ≈ 10 400 entries
|
|
104
|
+
* at 1 % FP. For larger caches the filter saturates quickly, producing high FP rates
|
|
105
|
+
* that force wasted Map.get() calls on every definite miss. When `maxEntries` exceeds
|
|
106
|
+
* the WASM filter's rated capacity, we instantiate a JS filter sized via the optimal
|
|
107
|
+
* formula: m = ⌈–n · ln p / (ln 2)²⌉ with k = round(ln 2 · m / n) clamped to [4, 10].
|
|
108
|
+
*/
|
|
109
|
+
function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
|
|
110
|
+
// Compute optimal bit-count for p = 1 % and the requested entry ceiling.
|
|
111
|
+
const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
|
|
112
|
+
const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
|
|
113
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
|
|
114
|
+
|
|
97
115
|
try {
|
|
98
116
|
const wasm = new WasmBloomFilter();
|
|
99
|
-
|
|
100
|
-
|
|
117
|
+
if (wasm.maxCapacity >= maxEntries) {
|
|
118
|
+
logger.debug('SmartMemoryCache: WASM BloomFilter active');
|
|
119
|
+
return wasm;
|
|
120
|
+
}
|
|
121
|
+
// WASM filter is undersized for this cache — fall through to right-sized JS filter.
|
|
122
|
+
logger.debug('SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter', {
|
|
123
|
+
wasmCapacity: wasm.maxCapacity, maxEntries, optimalBits,
|
|
124
|
+
});
|
|
101
125
|
} catch (err) {
|
|
102
126
|
logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
|
|
103
|
-
return new JsBloomFilter();
|
|
104
127
|
}
|
|
128
|
+
return new JsBloomFilter(optimalBits, optimalK);
|
|
105
129
|
}
|
|
106
130
|
|
|
107
131
|
// ─── Count-Min Sketch ─────────────────────────────────────────────────────────
|
|
@@ -179,15 +203,57 @@ class CountMinSketch {
|
|
|
179
203
|
}
|
|
180
204
|
}
|
|
181
205
|
|
|
206
|
+
// ─── Glob matcher ───────────────────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Pure-string glob matcher — replaces RegExp on the deletePattern hot path.
|
|
210
|
+
* Supports only '*' wildcards (any sequence, including empty).
|
|
211
|
+
* No NFA/DFA state machine, no backtracking.
|
|
212
|
+
*
|
|
213
|
+
* Two-layer design to avoid per-key allocation in the inner loop:
|
|
214
|
+
* globMatch() — public entry point; splits the pattern once.
|
|
215
|
+
* globMatchParts() — hot inner loop; receives the pre-split segments.
|
|
216
|
+
*
|
|
217
|
+
* Algorithm:
|
|
218
|
+
* 1. First segment anchors the prefix (startsWith, O(|first|)).
|
|
219
|
+
* 2. Last segment anchors the suffix (endsWith, O(|last|)).
|
|
220
|
+
* 3. Middle segments are located left-to-right with indexOf (O(N) total, no re-scan).
|
|
221
|
+
*/
|
|
222
|
+
function globMatchParts(parts: string[], first: string, last: string, key: string): boolean {
|
|
223
|
+
if (first.length > 0 && !key.startsWith(first)) return false;
|
|
224
|
+
if (last.length > 0 && !key.endsWith(last)) return false;
|
|
225
|
+
if (first.length + last.length > key.length) return false; // anchors overlap
|
|
226
|
+
|
|
227
|
+
// Walk any middle segments left-to-right — indexOf never backtracks.
|
|
228
|
+
let pos = first.length;
|
|
229
|
+
const end = key.length - last.length;
|
|
230
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
231
|
+
const seg = parts[i];
|
|
232
|
+
if (seg.length === 0) continue; // consecutive '*' — skip
|
|
233
|
+
const idx = key.indexOf(seg, pos);
|
|
234
|
+
if (idx === -1 || idx + seg.length > end) return false;
|
|
235
|
+
pos = idx + seg.length;
|
|
236
|
+
}
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function globMatch(pattern: string, key: string): boolean {
|
|
241
|
+
const parts = pattern.split('*');
|
|
242
|
+
if (parts.length === 1) return pattern === key; // no wildcard — exact match
|
|
243
|
+
return globMatchParts(parts, parts[0], parts[parts.length - 1], key);
|
|
244
|
+
}
|
|
245
|
+
|
|
182
246
|
// ─── SmartMemoryCache ─────────────────────────────────────────────────────────
|
|
183
247
|
|
|
184
248
|
export interface SmartMemoryCacheOptions {
|
|
185
|
-
maxBytes:
|
|
186
|
-
maxEntries:
|
|
187
|
-
categories:
|
|
188
|
-
diskSpill?:
|
|
189
|
-
onEviction?:
|
|
190
|
-
logger:
|
|
249
|
+
maxBytes: number;
|
|
250
|
+
maxEntries: number;
|
|
251
|
+
categories: Record<string, CategoryLimit>;
|
|
252
|
+
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
253
|
+
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
254
|
+
logger: ILogger;
|
|
255
|
+
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
256
|
+
evictionWatermark?: number;
|
|
191
257
|
}
|
|
192
258
|
|
|
193
259
|
export class SmartMemoryCache {
|
|
@@ -211,9 +277,21 @@ export class SmartMemoryCache {
|
|
|
211
277
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
212
278
|
private _bloomDirtyCount = 0;
|
|
213
279
|
|
|
280
|
+
/**
|
|
281
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
282
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
283
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
284
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
285
|
+
* any other code can observe the pool state.
|
|
286
|
+
*/
|
|
287
|
+
private readonly _evictPool: Array<{ key: string; score: number }> =
|
|
288
|
+
Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
|
|
289
|
+
private readonly _evictGPool: Array<{ key: string; score: number }> =
|
|
290
|
+
Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
|
|
291
|
+
|
|
214
292
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
|
|
215
293
|
this.opts = opts;
|
|
216
|
-
this.bloom = createBloomFilter(opts.logger);
|
|
294
|
+
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
217
295
|
this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
|
|
218
296
|
|
|
219
297
|
if (existing) {
|
|
@@ -274,7 +352,22 @@ export class SmartMemoryCache {
|
|
|
274
352
|
const catSz = this.categorySize.get(category) ?? 0;
|
|
275
353
|
const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
276
354
|
const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
277
|
-
if (!catOvf && !glbOvf)
|
|
355
|
+
if (!catOvf && !glbOvf) {
|
|
356
|
+
// Proactive watermark: when either the global entry count OR total byte
|
|
357
|
+
// usage crosses 90 % of its configured ceiling while there is still
|
|
358
|
+
// headroom, run one eviction pass now — during the cheap headroom path —
|
|
359
|
+
// so the hard cliffs at 100 % are rarely reached and writes at full
|
|
360
|
+
// capacity become uncommon. Both dimensions are guarded so that
|
|
361
|
+
// large-payload workloads (where maxBytes is the binding constraint)
|
|
362
|
+
// benefit equally alongside entry-count-bound workloads.
|
|
363
|
+
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
364
|
+
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
365
|
+
const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
|
|
366
|
+
if (entryWatermark || byteWatermark) {
|
|
367
|
+
this.smartEvict(category, false);
|
|
368
|
+
}
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
278
371
|
this.smartEvict(category, catOvf);
|
|
279
372
|
}
|
|
280
373
|
|
|
@@ -305,9 +398,15 @@ export class SmartMemoryCache {
|
|
|
305
398
|
// Two independent triggers — whichever fires first:
|
|
306
399
|
// 1. Phantom count (insertions of dead keys since last rebuild)
|
|
307
400
|
// 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
|
|
308
|
-
//
|
|
309
|
-
//
|
|
310
|
-
|
|
401
|
+
//
|
|
402
|
+
// Dirty-count cap: bloom.maxCapacity grows proportionally with filter size, but
|
|
403
|
+
// we want rebuild frequency to stay proportional to cache ENTRY count, not bit
|
|
404
|
+
// count. Without the cap a JS filter sized for 50 K entries allows ~12 500 ghost
|
|
405
|
+
// entries before a rebuild — 5× longer than the old WASM filter, which let phantom
|
|
406
|
+
// bits accumulate and raised the measured FP rate. The cap restores the original
|
|
407
|
+
// rebuild cadence: rebuild after ~5 % of maxEntries are deleted, with a 256 floor.
|
|
408
|
+
const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
|
|
409
|
+
if (this._bloomDirtyCount > dirtyThreshold ||
|
|
311
410
|
this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
|
|
312
411
|
this.bloom.rebuild(this.cache.keys());
|
|
313
412
|
this._bloomDirtyCount = 0;
|
|
@@ -316,16 +415,15 @@ export class SmartMemoryCache {
|
|
|
316
415
|
|
|
317
416
|
private smartEvict(targetCat: string, catOvf: boolean): void {
|
|
318
417
|
const now = Date.now();
|
|
319
|
-
const
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
const pool: Array<{ key: string; score: number }> = [];
|
|
418
|
+
const pool = this._evictPool;
|
|
419
|
+
const gPool = this._evictGPool;
|
|
420
|
+
let poolLen = 0;
|
|
323
421
|
|
|
324
422
|
if (catOvf) {
|
|
325
423
|
// Phase 1 — O(catSize) category-local reservoir sample.
|
|
326
424
|
// Uses the categoryKeys index to iterate only the overflowing category's keys,
|
|
327
425
|
// avoiding an O(N) scan of the entire cache. Guarantees at least
|
|
328
|
-
// min(catSize,
|
|
426
|
+
// min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
|
|
329
427
|
// the priority score ordering is always deterministic in practice.
|
|
330
428
|
const catKeySet = this.categoryKeys.get(targetCat);
|
|
331
429
|
if (catKeySet) {
|
|
@@ -335,44 +433,59 @@ export class SmartMemoryCache {
|
|
|
335
433
|
if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
|
|
336
434
|
catSeen++;
|
|
337
435
|
const s = this.score(entry, 100, now, key);
|
|
338
|
-
if (
|
|
339
|
-
pool.
|
|
436
|
+
if (poolLen < EVICT_COUNT) {
|
|
437
|
+
pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
|
|
340
438
|
} else {
|
|
341
439
|
const j = Math.floor(Math.random() * catSeen);
|
|
342
|
-
if (j <
|
|
440
|
+
if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
|
|
343
441
|
}
|
|
344
442
|
}
|
|
345
443
|
}
|
|
346
444
|
}
|
|
347
445
|
|
|
348
|
-
// Phase 2 — global reservoir sample fills remaining
|
|
349
|
-
// Skipped entirely when Phase 1 already collected a full
|
|
350
|
-
// (the common catOvf case — overflowing categories always have ≥
|
|
446
|
+
// Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
|
|
447
|
+
// Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
|
|
448
|
+
// (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
|
|
351
449
|
// Also the sole phase when !catOvf (global over-capacity, no preferred category).
|
|
352
|
-
if (
|
|
353
|
-
const remaining =
|
|
450
|
+
if (poolLen < EVICT_COUNT) {
|
|
451
|
+
const remaining = EVICTION_SAMPLE - poolLen;
|
|
354
452
|
let globalSeen = 0;
|
|
355
|
-
|
|
453
|
+
let gLen = 0;
|
|
356
454
|
for (const [key, entry] of this.cache) {
|
|
357
455
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
358
456
|
if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
|
|
359
457
|
globalSeen++;
|
|
360
458
|
const s = this.score(entry, 0, now, key);
|
|
361
|
-
if (
|
|
362
|
-
|
|
459
|
+
if (gLen < remaining) {
|
|
460
|
+
gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
|
|
363
461
|
} else {
|
|
364
462
|
const j = Math.floor(Math.random() * globalSeen);
|
|
365
|
-
if (j < remaining)
|
|
463
|
+
if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
|
|
366
464
|
}
|
|
367
465
|
}
|
|
368
|
-
|
|
466
|
+
// Manual merge — no spread, no new array
|
|
467
|
+
for (let i = 0; i < gLen; i++) {
|
|
468
|
+
pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
|
|
469
|
+
}
|
|
369
470
|
}
|
|
370
471
|
|
|
371
|
-
if (
|
|
472
|
+
if (poolLen === 0) return;
|
|
372
473
|
|
|
373
|
-
//
|
|
374
|
-
|
|
375
|
-
|
|
474
|
+
// Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
|
|
475
|
+
// Faster than Array.sort() at this scale: no comparator closure call overhead,
|
|
476
|
+
// no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
|
|
477
|
+
for (let i = 1; i < poolLen; i++) {
|
|
478
|
+
const sk = pool[i].key, ss = pool[i].score;
|
|
479
|
+
let j = i - 1;
|
|
480
|
+
while (j >= 0 && pool[j].score > ss) {
|
|
481
|
+
pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
|
|
482
|
+
}
|
|
483
|
+
pool[j + 1].key = sk; pool[j + 1].score = ss;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const toEvict = Math.min(EVICT_COUNT, poolLen);
|
|
487
|
+
for (let i = 0; i < toEvict; i++) {
|
|
488
|
+
const key = pool[i].key;
|
|
376
489
|
const entry = this.cache.get(key);
|
|
377
490
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
|
|
378
491
|
this._delete(key, 'capacity');
|
|
@@ -400,6 +513,7 @@ export class SmartMemoryCache {
|
|
|
400
513
|
_hit.expiresAt = entry.expiresAt;
|
|
401
514
|
_hit.ttlMs = entry.ttlMs;
|
|
402
515
|
_hit.delta = entry.delta;
|
|
516
|
+
_hit.fetchedAt = now;
|
|
403
517
|
return _hit;
|
|
404
518
|
}
|
|
405
519
|
|
|
@@ -438,7 +552,9 @@ export class SmartMemoryCache {
|
|
|
438
552
|
|
|
439
553
|
const now = Date.now();
|
|
440
554
|
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
441
|
-
|
|
555
|
+
// Only add new keys to the bloom — overwrites already have their bits set.
|
|
556
|
+
// Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
|
|
557
|
+
if (!existingEntry) this.bloom.add(key);
|
|
442
558
|
this.maybeRebuildBloom();
|
|
443
559
|
this.totalSize += size;
|
|
444
560
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
@@ -456,9 +572,40 @@ export class SmartMemoryCache {
|
|
|
456
572
|
|
|
457
573
|
private keysMatchingPattern(pattern: string): string[] {
|
|
458
574
|
if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
|
|
459
|
-
|
|
575
|
+
|
|
576
|
+
// Fast path: trailing-only wildcard whose prefix exactly matches a configured
|
|
577
|
+
// category (e.g. deletePattern('user:*') when 'user:' is a category).
|
|
578
|
+
// categoryKeys already indexes all live keys per category prefix in O(1),
|
|
579
|
+
// so we skip the O(N) Map scan and regex evaluation entirely.
|
|
580
|
+
// We snapshot via Array.from() before returning so _delete() mutations to
|
|
581
|
+
// the Set during the subsequent iteration are safe.
|
|
582
|
+
if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
|
|
583
|
+
const prefix = pattern.slice(0, -1);
|
|
584
|
+
const catKeys = this.categoryKeys.get(prefix);
|
|
585
|
+
if (catKeys !== undefined) return Array.from(catKeys);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// Fast path: exactly one '*' that is NOT at the end (e.g. "user:*:profile").
|
|
589
|
+
// AOT detection lets us avoid globMatchParts dispatch and its empty middle-
|
|
590
|
+
// segment loop — keys only need startsWith + endsWith + length checks inline.
|
|
591
|
+
const firstStar = pattern.indexOf('*');
|
|
592
|
+
if (firstStar === pattern.lastIndexOf('*')) {
|
|
593
|
+
const prefix = pattern.slice(0, firstStar);
|
|
594
|
+
const suffix = pattern.slice(firstStar + 1); // empty when star is last char
|
|
595
|
+
const minLen = prefix.length + suffix.length;
|
|
596
|
+
const out: string[] = [];
|
|
597
|
+
for (const k of this.cache.keys()) {
|
|
598
|
+
if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out.push(k);
|
|
599
|
+
}
|
|
600
|
+
return out;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// General case: multiple '*' wildcards — split once, then scan.
|
|
604
|
+
const parts = pattern.split('*');
|
|
605
|
+
const first = parts[0];
|
|
606
|
+
const last = parts[parts.length - 1];
|
|
460
607
|
const out: string[] = [];
|
|
461
|
-
for (const k of this.cache.keys()) if (
|
|
608
|
+
for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
|
|
462
609
|
return out;
|
|
463
610
|
}
|
|
464
611
|
|
|
@@ -634,6 +781,31 @@ export class SmartMemoryCache {
|
|
|
634
781
|
}
|
|
635
782
|
}
|
|
636
783
|
|
|
784
|
+
/**
|
|
785
|
+
* Non-generator bulk scan over all live entries.
|
|
786
|
+
*
|
|
787
|
+
* Faster than the generator-based iterators for bulk operations because:
|
|
788
|
+
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
789
|
+
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
790
|
+
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
791
|
+
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
792
|
+
* monomorphic profile for this path.
|
|
793
|
+
*
|
|
794
|
+
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
795
|
+
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
796
|
+
* key, avoiding the allocation entirely for callers that don't.
|
|
797
|
+
*
|
|
798
|
+
* @param fn Called once per live entry.
|
|
799
|
+
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
800
|
+
* Pass 0 when no namespace is configured.
|
|
801
|
+
*/
|
|
802
|
+
scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void {
|
|
803
|
+
const now = Date.now();
|
|
804
|
+
for (const [key, entry] of this.cache) {
|
|
805
|
+
if (entry.expiresAt > now) fn(key, entry, prefixLen);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
637
809
|
/**
|
|
638
810
|
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
639
811
|
* Use this instead of liveEntries() when you only need keys.
|