tricache 0.1.0 → 0.2.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 +210 -56
- package/dist/index.cjs +553 -63
- package/dist/index.d.cts +208 -8
- package/dist/index.d.ts +208 -8
- package/dist/index.js +553 -63
- package/package.json +9 -8
- package/src/cache-service.ts +367 -37
- package/src/disk-tier.ts +18 -2
- package/src/encryption.ts +69 -13
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +159 -18
- package/src/types.ts +75 -1
package/src/encryption.ts
CHANGED
|
@@ -73,6 +73,8 @@ const IV_POOL_COUNT = 64;
|
|
|
73
73
|
export class CacheEncryption {
|
|
74
74
|
private _key: Buffer | null = null;
|
|
75
75
|
private readonly _mode: EncryptionMode;
|
|
76
|
+
private _prevKey: Buffer | null = null;
|
|
77
|
+
private _prevMode: EncryptionMode = 'aes-256-gcm';
|
|
76
78
|
|
|
77
79
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
78
80
|
private readonly _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
@@ -150,7 +152,13 @@ export class CacheEncryption {
|
|
|
150
152
|
return out;
|
|
151
153
|
}
|
|
152
154
|
|
|
153
|
-
constructor(
|
|
155
|
+
constructor(
|
|
156
|
+
keyBase64: string | undefined,
|
|
157
|
+
logger: ILogger,
|
|
158
|
+
mode: EncryptionMode = 'aes-256-gcm',
|
|
159
|
+
previousKeyBase64?: string,
|
|
160
|
+
previousMode?: EncryptionMode,
|
|
161
|
+
) {
|
|
154
162
|
this._mode = mode;
|
|
155
163
|
if (!keyBase64) {
|
|
156
164
|
if (process.env.NODE_ENV === 'production') {
|
|
@@ -181,6 +189,16 @@ export class CacheEncryption {
|
|
|
181
189
|
} catch (err) {
|
|
182
190
|
logger.error('Invalid encryption key — falling back to plaintext', {}, err as Error);
|
|
183
191
|
}
|
|
192
|
+
|
|
193
|
+
if (previousKeyBase64) {
|
|
194
|
+
try {
|
|
195
|
+
this._prevMode = previousMode ?? mode;
|
|
196
|
+
this._prevKey = Buffer.from(previousKeyBase64, 'base64');
|
|
197
|
+
logger.debug('Previous encryption key loaded for key rotation fallback');
|
|
198
|
+
} catch (err) {
|
|
199
|
+
logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
184
202
|
}
|
|
185
203
|
|
|
186
204
|
get isEnabled(): boolean { return this._key !== null; }
|
|
@@ -225,20 +243,39 @@ export class CacheEncryption {
|
|
|
225
243
|
/**
|
|
226
244
|
* Decrypt a Redis value.
|
|
227
245
|
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
246
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
228
247
|
*/
|
|
229
248
|
decrypt(value: string): string {
|
|
249
|
+
try {
|
|
250
|
+
return this._decryptWithKey(value, this._key, this._mode);
|
|
251
|
+
} catch (primaryErr) {
|
|
252
|
+
if (this._prevKey) {
|
|
253
|
+
try {
|
|
254
|
+
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
255
|
+
} catch { /* ignore — fall through to re-throw primary */ }
|
|
256
|
+
}
|
|
257
|
+
throw primaryErr;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private _decryptWithKey(value: string, key: Buffer | null, mode: EncryptionMode): string {
|
|
230
262
|
if (value.startsWith(PREFIX_XOR)) {
|
|
231
|
-
if (!
|
|
263
|
+
if (!key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
232
264
|
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
233
265
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
|
|
234
|
-
|
|
266
|
+
// XOR is self-inverse; use the provided key regardless of mode
|
|
267
|
+
const klen = key.length;
|
|
268
|
+
const len = masked.length;
|
|
269
|
+
const out = Buffer.allocUnsafe(len);
|
|
270
|
+
for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
|
|
271
|
+
return out.toString('utf8');
|
|
235
272
|
}
|
|
236
273
|
if (value.startsWith(PREFIX_CTR)) {
|
|
237
|
-
if (!
|
|
274
|
+
if (!key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
238
275
|
const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
|
|
239
276
|
const iv = combined.subarray(0, CTR_IV_BYTES);
|
|
240
277
|
const ct = combined.subarray(CTR_IV_BYTES);
|
|
241
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
278
|
+
const d = createDecipheriv('aes-128-ctr', key, iv);
|
|
242
279
|
const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
|
|
243
280
|
d.final();
|
|
244
281
|
return plain.toString('utf8');
|
|
@@ -246,18 +283,19 @@ export class CacheEncryption {
|
|
|
246
283
|
const is256 = value.startsWith(PREFIX_256);
|
|
247
284
|
const is128 = value.startsWith(PREFIX_128);
|
|
248
285
|
if (!is256 && !is128) return value;
|
|
249
|
-
if (!
|
|
286
|
+
if (!key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
250
287
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
251
288
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
252
289
|
const combined = Buffer.from(value.slice(prefix.length), 'base64');
|
|
253
290
|
const iv = combined.subarray(0, IV_BYTES);
|
|
254
291
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
255
292
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
256
|
-
const d = createDecipheriv(algo,
|
|
293
|
+
const d = createDecipheriv(algo, key, iv);
|
|
257
294
|
d.setAuthTag(tag);
|
|
258
295
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
259
296
|
d.final(); // verifies auth tag — throws on tamper
|
|
260
297
|
return plain.toString('utf8');
|
|
298
|
+
void mode; // mode is used implicitly via prefix detection
|
|
261
299
|
}
|
|
262
300
|
|
|
263
301
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
@@ -303,22 +341,40 @@ export class CacheEncryption {
|
|
|
303
341
|
/**
|
|
304
342
|
* Decrypt a raw Buffer from disk/snapshot.
|
|
305
343
|
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
344
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
306
345
|
*/
|
|
307
346
|
decryptBuffer(data: Buffer): Buffer {
|
|
347
|
+
try {
|
|
348
|
+
return this._decryptBufferWithKey(data, this._key);
|
|
349
|
+
} catch (primaryErr) {
|
|
350
|
+
if (this._prevKey) {
|
|
351
|
+
try {
|
|
352
|
+
return this._decryptBufferWithKey(data, this._prevKey);
|
|
353
|
+
} catch { /* ignore — re-throw primary */ }
|
|
354
|
+
}
|
|
355
|
+
throw primaryErr;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
private _decryptBufferWithKey(data: Buffer, key: Buffer | null): Buffer {
|
|
308
360
|
if (data.length < MAGIC_LEN) return data;
|
|
309
361
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
310
362
|
|
|
311
363
|
if (magic.equals(MAGIC_XOR)) {
|
|
312
|
-
if (!
|
|
364
|
+
if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
313
365
|
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
314
|
-
|
|
366
|
+
const raw = data.subarray(MAGIC_LEN);
|
|
367
|
+
const klen = key.length;
|
|
368
|
+
const out = Buffer.allocUnsafe(raw.length);
|
|
369
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
|
|
370
|
+
return out;
|
|
315
371
|
}
|
|
316
372
|
|
|
317
373
|
if (magic.equals(MAGIC_CTR)) {
|
|
318
|
-
if (!
|
|
374
|
+
if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
319
375
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
320
376
|
const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
321
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
377
|
+
const d = createDecipheriv('aes-128-ctr', key, iv);
|
|
322
378
|
const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
|
|
323
379
|
d.final();
|
|
324
380
|
return plain;
|
|
@@ -326,12 +382,12 @@ export class CacheEncryption {
|
|
|
326
382
|
const is256 = magic.equals(MAGIC_256);
|
|
327
383
|
const is128 = magic.equals(MAGIC_128);
|
|
328
384
|
if (!is256 && !is128) return data;
|
|
329
|
-
if (!
|
|
385
|
+
if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
330
386
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
331
387
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
332
388
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
333
389
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
334
|
-
const d = createDecipheriv(algo,
|
|
390
|
+
const d = createDecipheriv(algo, key, iv);
|
|
335
391
|
d.setAuthTag(tag);
|
|
336
392
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
337
393
|
d.final(); // verifies auth tag — throws on tamper
|
package/src/index.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { pack, unpack } from 'msgpackr';
|
|
16
|
-
import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger } from './types';
|
|
16
|
+
import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
|
|
17
17
|
import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
18
18
|
|
|
19
19
|
|
|
@@ -107,6 +107,7 @@ export interface SmartMemoryCacheOptions {
|
|
|
107
107
|
maxEntries: number;
|
|
108
108
|
categories: Record<string, CategoryLimit>;
|
|
109
109
|
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
110
|
+
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
110
111
|
logger: ILogger;
|
|
111
112
|
}
|
|
112
113
|
|
|
@@ -125,8 +126,7 @@ export class SmartMemoryCache {
|
|
|
125
126
|
// ── Observability counters ──────────────────────────────────────────────────────
|
|
126
127
|
private bloomChecks = 0;
|
|
127
128
|
private bloomFalsePos = 0;
|
|
128
|
-
private compressions = 0;
|
|
129
|
-
|
|
129
|
+
private compressions = 0; private categoryHits = new Map<string, number>();
|
|
130
130
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
131
131
|
private _bloomDirtyCount = 0;
|
|
132
132
|
|
|
@@ -171,7 +171,7 @@ export class SmartMemoryCache {
|
|
|
171
171
|
return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
private _delete(key: string): boolean {
|
|
174
|
+
private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
|
|
175
175
|
const entry = this.cache.get(key);
|
|
176
176
|
if (!entry) return false;
|
|
177
177
|
const cat = this.getCategory(key);
|
|
@@ -180,7 +180,11 @@ export class SmartMemoryCache {
|
|
|
180
180
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
181
181
|
this.categoryKeys.get(cat)?.delete(key);
|
|
182
182
|
this._bloomDirtyCount++;
|
|
183
|
-
|
|
183
|
+
const deleted = this.cache.delete(key);
|
|
184
|
+
if (deleted && this.opts.onEviction) {
|
|
185
|
+
try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
|
|
186
|
+
}
|
|
187
|
+
return deleted;
|
|
184
188
|
}
|
|
185
189
|
|
|
186
190
|
private ensureCapacity(category: string, neededSize: number): void {
|
|
@@ -287,7 +291,7 @@ export class SmartMemoryCache {
|
|
|
287
291
|
for (const { key } of pool.slice(0, EVICT)) {
|
|
288
292
|
const entry = this.cache.get(key);
|
|
289
293
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
|
|
290
|
-
this._delete(key);
|
|
294
|
+
this._delete(key, 'capacity');
|
|
291
295
|
}
|
|
292
296
|
}
|
|
293
297
|
|
|
@@ -299,10 +303,14 @@ export class SmartMemoryCache {
|
|
|
299
303
|
const entry = this.cache.get(key);
|
|
300
304
|
if (!entry) { this.bloomFalsePos++; return null; }
|
|
301
305
|
const now = Date.now();
|
|
302
|
-
if (entry.expiresAt < now) { this._delete(key); return null; }
|
|
306
|
+
if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
|
|
303
307
|
entry.hits++;
|
|
304
308
|
entry.lastAccess = now;
|
|
305
|
-
const
|
|
309
|
+
const cat = this.getCategory(key);
|
|
310
|
+
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
311
|
+
// value is cached at write time — hot reads return the live object directly,
|
|
312
|
+
// skipping unpack. Falls back to decode for entries restored from disk/snapshot.
|
|
313
|
+
const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
|
|
306
314
|
const isStale = entry.staleAt !== undefined && now > entry.staleAt;
|
|
307
315
|
return { value, isStale };
|
|
308
316
|
}
|
|
@@ -339,7 +347,7 @@ export class SmartMemoryCache {
|
|
|
339
347
|
this.ensureCapacity(cat, size);
|
|
340
348
|
|
|
341
349
|
const now = Date.now();
|
|
342
|
-
this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
350
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
343
351
|
this.bloom.add(key);
|
|
344
352
|
this.maybeRebuildBloom();
|
|
345
353
|
this.totalSize += size;
|
|
@@ -351,7 +359,7 @@ export class SmartMemoryCache {
|
|
|
351
359
|
}
|
|
352
360
|
|
|
353
361
|
delete(key: string): boolean {
|
|
354
|
-
const deleted = this._delete(key);
|
|
362
|
+
const deleted = this._delete(key, 'manual');
|
|
355
363
|
if (deleted) this.maybeRebuildBloom();
|
|
356
364
|
return deleted;
|
|
357
365
|
}
|
|
@@ -366,11 +374,88 @@ export class SmartMemoryCache {
|
|
|
366
374
|
|
|
367
375
|
deletePattern(pattern: string): number {
|
|
368
376
|
let n = 0;
|
|
369
|
-
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
|
|
377
|
+
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, 'manual')) n++;
|
|
370
378
|
if (n > 0) this.maybeRebuildBloom();
|
|
371
379
|
return n;
|
|
372
380
|
}
|
|
373
381
|
|
|
382
|
+
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
383
|
+
clear(prefix?: string): number {
|
|
384
|
+
if (prefix) {
|
|
385
|
+
const pattern = prefix.includes('*') ? prefix : `${prefix}*`;
|
|
386
|
+
return this.deletePattern(pattern);
|
|
387
|
+
}
|
|
388
|
+
const count = this.cache.size;
|
|
389
|
+
this.cache.clear();
|
|
390
|
+
this.totalSize = 0;
|
|
391
|
+
this.categoryCount.clear();
|
|
392
|
+
this.categorySize.clear();
|
|
393
|
+
this.categoryKeys.clear();
|
|
394
|
+
this.categoryHits.clear();
|
|
395
|
+
this.bloom.reset();
|
|
396
|
+
this._bloomDirtyCount = 0;
|
|
397
|
+
return count;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Evict entries that violate current category or global limits.
|
|
402
|
+
* Returns the number of entries evicted.
|
|
403
|
+
*/
|
|
404
|
+
rebalance(): number {
|
|
405
|
+
const now = Date.now();
|
|
406
|
+
let evicted = 0;
|
|
407
|
+
|
|
408
|
+
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
409
|
+
const catKeys = this.categoryKeys.get(cat);
|
|
410
|
+
if (!catKeys || catKeys.size === 0) continue;
|
|
411
|
+
|
|
412
|
+
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
413
|
+
let catSz = this.categorySize.get(cat) ?? 0;
|
|
414
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
|
|
415
|
+
|
|
416
|
+
const candidates: Array<{ key: string; score: number }> = [];
|
|
417
|
+
for (const key of catKeys) {
|
|
418
|
+
const entry = this.cache.get(key);
|
|
419
|
+
if (!entry) continue;
|
|
420
|
+
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
421
|
+
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
422
|
+
}
|
|
423
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
424
|
+
|
|
425
|
+
for (const { key } of candidates) {
|
|
426
|
+
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
427
|
+
catSz = this.categorySize.get(cat) ?? 0;
|
|
428
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
|
|
429
|
+
const entry = this.cache.get(key);
|
|
430
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
431
|
+
this._delete(key, 'rebalance');
|
|
432
|
+
evicted++;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Global limits
|
|
437
|
+
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
438
|
+
const before = this.cache.size;
|
|
439
|
+
this.smartEvict('default', false);
|
|
440
|
+
if (this.cache.size >= before) break; // only CRITICAL entries remain
|
|
441
|
+
evicted += before - this.cache.size;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (evicted > 0) this.maybeRebuildBloom();
|
|
445
|
+
return evicted;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
450
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
451
|
+
*/
|
|
452
|
+
ttl(key: string): number | null {
|
|
453
|
+
const entry = this.cache.get(key);
|
|
454
|
+
if (!entry) return null;
|
|
455
|
+
const remaining = entry.expiresAt - Date.now();
|
|
456
|
+
return remaining > 0 ? Math.ceil(remaining / 1000) : null;
|
|
457
|
+
}
|
|
458
|
+
|
|
374
459
|
/**
|
|
375
460
|
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
376
461
|
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
@@ -393,7 +478,7 @@ export class SmartMemoryCache {
|
|
|
393
478
|
for (const { key } of candidates.slice(0, count)) {
|
|
394
479
|
const entry = this.cache.get(key);
|
|
395
480
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
396
|
-
this._delete(key);
|
|
481
|
+
this._delete(key, 'oom');
|
|
397
482
|
evicted++;
|
|
398
483
|
}
|
|
399
484
|
return evicted;
|
|
@@ -402,7 +487,7 @@ export class SmartMemoryCache {
|
|
|
402
487
|
cleanup(): number {
|
|
403
488
|
const now = Date.now();
|
|
404
489
|
let cleaned = 0;
|
|
405
|
-
for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key); cleaned++; }
|
|
490
|
+
for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key, 'ttl'); cleaned++; }
|
|
406
491
|
if (cleaned > 0) { this.bloom.rebuild(this.cache.keys()); this._bloomDirtyCount = 0; }
|
|
407
492
|
return cleaned;
|
|
408
493
|
}
|
|
@@ -435,7 +520,9 @@ export class SmartMemoryCache {
|
|
|
435
520
|
: rawData instanceof Uint8Array
|
|
436
521
|
? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
|
|
437
522
|
: rawData as Buffer; // already a Buffer
|
|
438
|
-
|
|
523
|
+
// Decode once on import so subsequent gets return the live object without unpacking.
|
|
524
|
+
const value = unpack(data);
|
|
525
|
+
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
439
526
|
this.bloom.add(key);
|
|
440
527
|
loaded++;
|
|
441
528
|
}
|
|
@@ -449,11 +536,14 @@ export class SmartMemoryCache {
|
|
|
449
536
|
get memoryUsage(): number { return this.totalSize; }
|
|
450
537
|
|
|
451
538
|
getStats() {
|
|
452
|
-
const categories: Record<string, number> = {};
|
|
453
|
-
for (const [cat, cnt] of this.categoryCount)
|
|
539
|
+
const categories: Record<string, { entries: number; hits: number }> = {};
|
|
540
|
+
for (const [cat, cnt] of this.categoryCount) {
|
|
541
|
+
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
542
|
+
}
|
|
454
543
|
return {
|
|
455
|
-
entries:
|
|
456
|
-
|
|
544
|
+
entries: this.cache.size,
|
|
545
|
+
sizeBytes: this.totalSize,
|
|
546
|
+
sizeKB: Math.round(this.totalSize / 1024),
|
|
457
547
|
categories,
|
|
458
548
|
bloom: {
|
|
459
549
|
checks: this.bloomChecks,
|
|
@@ -467,6 +557,57 @@ export class SmartMemoryCache {
|
|
|
467
557
|
};
|
|
468
558
|
}
|
|
469
559
|
|
|
560
|
+
/**
|
|
561
|
+
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
562
|
+
* Does NOT count as a hit or perform SWR logic.
|
|
563
|
+
*/
|
|
564
|
+
getEntry(key: string): SmartCacheEntry | undefined {
|
|
565
|
+
const entry = this.cache.get(key);
|
|
566
|
+
if (!entry) return undefined;
|
|
567
|
+
if (entry.expiresAt <= Date.now()) return undefined;
|
|
568
|
+
return entry;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Return true if the key exists in L1 and has not expired.
|
|
573
|
+
* Uses the bloom filter as a fast negative check.
|
|
574
|
+
*/
|
|
575
|
+
has(key: string): boolean {
|
|
576
|
+
if (!this.bloom.mightContain(key)) return false;
|
|
577
|
+
const entry = this.cache.get(key);
|
|
578
|
+
if (!entry) return false;
|
|
579
|
+
if (entry.expiresAt <= Date.now()) {
|
|
580
|
+
this._delete(key, 'ttl');
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
588
|
+
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
589
|
+
*/
|
|
590
|
+
touch(key: string, newTtlMs: number): boolean {
|
|
591
|
+
const entry = this.cache.get(key);
|
|
592
|
+
if (!entry) return false;
|
|
593
|
+
const now = Date.now();
|
|
594
|
+
if (entry.expiresAt <= now) { this._delete(key, 'ttl'); return false; }
|
|
595
|
+
entry.expiresAt = now + newTtlMs;
|
|
596
|
+
return true;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
601
|
+
* Returns `false` if the key is absent or already expired.
|
|
602
|
+
*/
|
|
603
|
+
bumpExpiry(key: string, additionalMs: number): boolean {
|
|
604
|
+
const entry = this.cache.get(key);
|
|
605
|
+
if (!entry) return false;
|
|
606
|
+
if (entry.expiresAt <= Date.now()) return false;
|
|
607
|
+
entry.expiresAt += additionalMs;
|
|
608
|
+
return true;
|
|
609
|
+
}
|
|
610
|
+
|
|
470
611
|
bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
|
|
471
612
|
bloomStats() { return this.bloom.stats; }
|
|
472
613
|
}
|
package/src/types.ts
CHANGED
|
@@ -20,6 +20,31 @@ export const consoleLogger: ILogger = {
|
|
|
20
20
|
error: (msg, meta, err) => console.error('[tricache]', msg, meta ?? '', err ?? ''),
|
|
21
21
|
};
|
|
22
22
|
|
|
23
|
+
// ─── Eviction reason ────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Reason passed to the `onEviction` callback.
|
|
27
|
+
* - `'capacity'` — L1 over-capacity; evicted during a `set()` call
|
|
28
|
+
* - `'category'` — Per-category limit exceeded
|
|
29
|
+
* - `'rebalance'` — `cache.rebalance()` was called
|
|
30
|
+
* - `'oom'` — OOM guard emergency eviction
|
|
31
|
+
* - `'ttl'` — Entry expired during periodic cleanup
|
|
32
|
+
* - `'manual'` — Explicit `cache.delete()` call
|
|
33
|
+
*/
|
|
34
|
+
export type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
|
|
35
|
+
|
|
36
|
+
// ─── Ping result ─────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
/** Per-tier latency returned by `cache.ping()`. */
|
|
39
|
+
export interface CachePingResult {
|
|
40
|
+
/** L1 RAM check latency in milliseconds */
|
|
41
|
+
l1: number;
|
|
42
|
+
/** L1.5 disk stats access in milliseconds */
|
|
43
|
+
disk: number;
|
|
44
|
+
/** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
|
|
45
|
+
l2: number | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
23
48
|
// ─── Cache priorities ────────────────────────────────────────────────────────
|
|
24
49
|
|
|
25
50
|
/** Priority levels for L1 eviction — higher = less likely to be evicted */
|
|
@@ -34,8 +59,14 @@ export enum CachePriority {
|
|
|
34
59
|
|
|
35
60
|
/** Internal representation of a single cache entry in the L1 Map */
|
|
36
61
|
export interface SmartCacheEntry {
|
|
37
|
-
/** msgpackr-packed binary payload */
|
|
62
|
+
/** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
|
|
38
63
|
data: Buffer;
|
|
64
|
+
/**
|
|
65
|
+
* Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
|
|
66
|
+
* Undefined for entries restored from disk/snapshot (populated lazily on first access).
|
|
67
|
+
* NOTE: returned by reference — callers should treat the value as immutable.
|
|
68
|
+
*/
|
|
69
|
+
value?: unknown;
|
|
39
70
|
/** always true for entries written by the current code;
|
|
40
71
|
* may be false in legacy snapshots/disk files — handled transparently on import */
|
|
41
72
|
isCompressed: boolean;
|
|
@@ -236,6 +267,16 @@ export interface CacheOptions {
|
|
|
236
267
|
* Default: `'aes-256-gcm'`
|
|
237
268
|
*/
|
|
238
269
|
encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
270
|
+
/**
|
|
271
|
+
* Fallback encryption key for zero-downtime key rotation.
|
|
272
|
+
* On every read, tricache tries the current `encryptionKey` first.
|
|
273
|
+
* If decryption fails (wrong key), it retries with `previousEncryptionKey`.
|
|
274
|
+
* All writes always use the current `encryptionKey`.
|
|
275
|
+
* Remove this field once you are confident all data has been re-encrypted.
|
|
276
|
+
*/
|
|
277
|
+
previousEncryptionKey?: string;
|
|
278
|
+
/** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
|
|
279
|
+
previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
239
280
|
|
|
240
281
|
// ── Snapshot ────────────────────────────────────────────────────────────
|
|
241
282
|
/**
|
|
@@ -270,6 +311,39 @@ export interface CacheOptions {
|
|
|
270
311
|
*/
|
|
271
312
|
namespace?: string;
|
|
272
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Seconds to extend a stale SWR entry's life when background revalidation fails.
|
|
316
|
+
* Without this, a failed revalidation leaves the entry stale until its hard TTL
|
|
317
|
+
* expires, after which the next caller blocks. With `staleIfError`, tricache bumps
|
|
318
|
+
* the expiry by this many seconds on every failed revalidation, keeping the stale
|
|
319
|
+
* value available while the underlying service is degraded.
|
|
320
|
+
* Default: `0` (disabled — entry expires normally on revalidation failure).
|
|
321
|
+
*/
|
|
322
|
+
staleIfError?: number;
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
|
|
326
|
+
* Useful for diagnosing cache pressure and tuning `categoryLimits`.
|
|
327
|
+
*/
|
|
328
|
+
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Human-readable name for this CacheService instance. Added as an `instance` label
|
|
332
|
+
* to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
|
|
333
|
+
* Required when multiple CacheService instances share a process — without it,
|
|
334
|
+
* metric names from different instances collide.
|
|
335
|
+
* Default: `''` (no label).
|
|
336
|
+
*/
|
|
337
|
+
instanceName?: string;
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Controls whether writes are propagated to L2 (Redis).
|
|
341
|
+
* - `'read-write'` (default): read from and write to L2.
|
|
342
|
+
* - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
|
|
343
|
+
* Use for shared read replicas or external Redis clusters you do not own.
|
|
344
|
+
*/
|
|
345
|
+
l2WriteMode?: 'read-write' | 'read-only';
|
|
346
|
+
|
|
273
347
|
// ── Invalidation backplane (Redis Pub/Sub) ──────────────────────────────
|
|
274
348
|
/**
|
|
275
349
|
* Enable Redis Pub/Sub invalidation backplane so every running instance
|