tricache 0.1.0 → 0.3.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/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(keyBase64: string | undefined, logger: ILogger, mode: EncryptionMode = 'aes-256-gcm') {
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 (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
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
- return this._xorBuffer(masked).toString('utf8');
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 (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
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', this._key, iv);
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 (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
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, this._key, iv);
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 (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
364
+ if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
313
365
  // WARNING: XOR is NOT cryptographic — obfuscation only.
314
- return this._xorBuffer(data.subarray(MAGIC_LEN));
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 (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
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', this._key, iv);
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 (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
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, this._key, iv);
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
@@ -33,4 +33,6 @@ export {
33
33
  type SmartCacheEntry,
34
34
  type DiskCacheEntry,
35
35
  type CacheHit,
36
+ type EvictionReason,
37
+ type CachePingResult,
36
38
  } from './types';
@@ -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
 
@@ -100,6 +100,79 @@ function createBloomFilter(logger: ILogger): AnyBloomFilter {
100
100
  }
101
101
  }
102
102
 
103
+ // ─── Count-Min Sketch ─────────────────────────────────────────────────────────
104
+ //
105
+ // Estimates historical access frequency across eviction boundaries — a per-entry
106
+ // `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
107
+ // the sketch remembers the key's frequency in a fixed-size typed array that
108
+ // survives evictions. This closes the same-priority burst-flood gap: a key that
109
+ // has been accessed 80 times over the last hour but was evicted 5 minutes ago
110
+ // will score far above a brand-new burst key whose hits = 1.
111
+ //
112
+ // Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
113
+ // Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
114
+ // Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
115
+ // (frequency-ageing prevents indefinitely growing hot-key counts).
116
+
117
+ const SKETCH_ROWS = 4;
118
+ const SKETCH_WIDTH = 512; // must be power of two
119
+ const SKETCH_MASK = SKETCH_WIDTH - 1;
120
+ const SKETCH_DECAY_THRESHOLD = 100_000;
121
+
122
+ class CountMinSketch {
123
+ private readonly table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
124
+ private inserts = 0;
125
+
126
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
127
+ private fnv32(key: string): number {
128
+ let h = 0x811c9dc5;
129
+ for (let i = 0; i < key.length; i++) {
130
+ h ^= key.charCodeAt(i);
131
+ h = (Math.imul(h, 0x01000193) >>> 0);
132
+ }
133
+ return h;
134
+ }
135
+
136
+ /** Four independent bit-mixes from one FNV-1a seed. */
137
+ private hashes(key: string): [number, number, number, number] {
138
+ const h = this.fnv32(key);
139
+ const h1 = (h ^ (h >>> 16)) >>> 0;
140
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
141
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
142
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
143
+ return [h1, h2, h3, h4];
144
+ }
145
+
146
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
147
+ increment(key: string): void {
148
+ const [h1, h2, h3, h4] = this.hashes(key);
149
+ const t = this.table;
150
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(0xffff, (t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1));
151
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(0xffff, (t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1));
152
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(0xffff, (t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1));
153
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(0xffff, (t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1));
154
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
155
+ }
156
+
157
+ /** Minimum-across-rows frequency estimate. */
158
+ estimate(key: string): number {
159
+ const [h1, h2, h3, h4] = this.hashes(key);
160
+ const t = this.table;
161
+ return Math.min(
162
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
163
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
164
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
165
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
166
+ );
167
+ }
168
+
169
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
170
+ private decay(): void {
171
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
172
+ this.inserts = 0;
173
+ }
174
+ }
175
+
103
176
  // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
104
177
 
105
178
  export interface SmartMemoryCacheOptions {
@@ -107,6 +180,7 @@ export interface SmartMemoryCacheOptions {
107
180
  maxEntries: number;
108
181
  categories: Record<string, CategoryLimit>;
109
182
  diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
183
+ onEviction?: (key: string, reason: EvictionReason) => void;
110
184
  logger: ILogger;
111
185
  }
112
186
 
@@ -116,6 +190,8 @@ export class SmartMemoryCache {
116
190
  private bloom: AnyBloomFilter;
117
191
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
118
192
  private readonly categoryPrefixes: string[];
193
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
194
+ private readonly sketch = new CountMinSketch();
119
195
  private totalSize = 0;
120
196
  private categoryCount = new Map<string, number>();
121
197
  private categorySize = new Map<string, number>();
@@ -125,8 +201,7 @@ export class SmartMemoryCache {
125
201
  // ── Observability counters ──────────────────────────────────────────────────────
126
202
  private bloomChecks = 0;
127
203
  private bloomFalsePos = 0;
128
- private compressions = 0;
129
-
204
+ private compressions = 0; private categoryHits = new Map<string, number>();
130
205
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
131
206
  private _bloomDirtyCount = 0;
132
207
 
@@ -171,7 +246,7 @@ export class SmartMemoryCache {
171
246
  return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
172
247
  }
173
248
 
174
- private _delete(key: string): boolean {
249
+ private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
175
250
  const entry = this.cache.get(key);
176
251
  if (!entry) return false;
177
252
  const cat = this.getCategory(key);
@@ -180,7 +255,11 @@ export class SmartMemoryCache {
180
255
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
181
256
  this.categoryKeys.get(cat)?.delete(key);
182
257
  this._bloomDirtyCount++;
183
- return this.cache.delete(key);
258
+ const deleted = this.cache.delete(key);
259
+ if (deleted && this.opts.onEviction) {
260
+ try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
261
+ }
262
+ return deleted;
184
263
  }
185
264
 
186
265
  private ensureCapacity(category: string, neededSize: number): void {
@@ -193,10 +272,13 @@ export class SmartMemoryCache {
193
272
  this.smartEvict(category, catOvf);
194
273
  }
195
274
 
196
- private score(entry: SmartCacheEntry, catBonus: number, now: number): number {
275
+ private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
197
276
  const age = now - entry.lastAccess;
198
277
  const ttl = Math.max(0, entry.expiresAt - now);
199
- const freq = Math.min(entry.hits, 100);
278
+ // Use the sketch's cross-eviction frequency estimate when it exceeds the
279
+ // entry's current-tenure hit count — protects long-resident keys that were
280
+ // recently re-admitted (hits reset to 1) from same-priority burst floods.
281
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
200
282
  return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
201
283
  }
202
284
 
@@ -246,7 +328,7 @@ export class SmartMemoryCache {
246
328
  const entry = this.cache.get(key);
247
329
  if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
248
330
  catSeen++;
249
- const s = this.score(entry, 100, now);
331
+ const s = this.score(entry, 100, now, key);
250
332
  if (pool.length < EVICT) {
251
333
  pool.push({ key, score: s });
252
334
  } else {
@@ -269,7 +351,7 @@ export class SmartMemoryCache {
269
351
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
270
352
  if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
271
353
  globalSeen++;
272
- const s = this.score(entry, 0, now);
354
+ const s = this.score(entry, 0, now, key);
273
355
  if (globalPool.length < remaining) {
274
356
  globalPool.push({ key, score: s });
275
357
  } else {
@@ -287,7 +369,7 @@ export class SmartMemoryCache {
287
369
  for (const { key } of pool.slice(0, EVICT)) {
288
370
  const entry = this.cache.get(key);
289
371
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
290
- this._delete(key);
372
+ this._delete(key, 'capacity');
291
373
  }
292
374
  }
293
375
 
@@ -299,10 +381,15 @@ export class SmartMemoryCache {
299
381
  const entry = this.cache.get(key);
300
382
  if (!entry) { this.bloomFalsePos++; return null; }
301
383
  const now = Date.now();
302
- if (entry.expiresAt < now) { this._delete(key); return null; }
384
+ if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
303
385
  entry.hits++;
304
386
  entry.lastAccess = now;
305
- const value = unpack(entry.data as Buffer);
387
+ this.sketch.increment(key);
388
+ const cat = this.getCategory(key);
389
+ this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
390
+ // value is cached at write time — hot reads return the live object directly,
391
+ // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
392
+ const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
306
393
  const isStale = entry.staleAt !== undefined && now > entry.staleAt;
307
394
  return { value, isStale };
308
395
  }
@@ -319,6 +406,7 @@ export class SmartMemoryCache {
319
406
  const packed = pack(data);
320
407
  const size = packed.byteLength;
321
408
  this.compressions++;
409
+ this.sketch.increment(key);
322
410
 
323
411
  const cat = this.getCategory(key);
324
412
  const lim = this.getCategoryLimit(cat);
@@ -339,7 +427,7 @@ export class SmartMemoryCache {
339
427
  this.ensureCapacity(cat, size);
340
428
 
341
429
  const now = Date.now();
342
- this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
430
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
343
431
  this.bloom.add(key);
344
432
  this.maybeRebuildBloom();
345
433
  this.totalSize += size;
@@ -351,7 +439,7 @@ export class SmartMemoryCache {
351
439
  }
352
440
 
353
441
  delete(key: string): boolean {
354
- const deleted = this._delete(key);
442
+ const deleted = this._delete(key, 'manual');
355
443
  if (deleted) this.maybeRebuildBloom();
356
444
  return deleted;
357
445
  }
@@ -366,11 +454,88 @@ export class SmartMemoryCache {
366
454
 
367
455
  deletePattern(pattern: string): number {
368
456
  let n = 0;
369
- for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
457
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, 'manual')) n++;
370
458
  if (n > 0) this.maybeRebuildBloom();
371
459
  return n;
372
460
  }
373
461
 
462
+ /** Flush all entries, or only those whose key starts with `prefix`. */
463
+ clear(prefix?: string): number {
464
+ if (prefix) {
465
+ const pattern = prefix.includes('*') ? prefix : `${prefix}*`;
466
+ return this.deletePattern(pattern);
467
+ }
468
+ const count = this.cache.size;
469
+ this.cache.clear();
470
+ this.totalSize = 0;
471
+ this.categoryCount.clear();
472
+ this.categorySize.clear();
473
+ this.categoryKeys.clear();
474
+ this.categoryHits.clear();
475
+ this.bloom.reset();
476
+ this._bloomDirtyCount = 0;
477
+ return count;
478
+ }
479
+
480
+ /**
481
+ * Evict entries that violate current category or global limits.
482
+ * Returns the number of entries evicted.
483
+ */
484
+ rebalance(): number {
485
+ const now = Date.now();
486
+ let evicted = 0;
487
+
488
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
489
+ const catKeys = this.categoryKeys.get(cat);
490
+ if (!catKeys || catKeys.size === 0) continue;
491
+
492
+ let catCnt = this.categoryCount.get(cat) ?? 0;
493
+ let catSz = this.categorySize.get(cat) ?? 0;
494
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
495
+
496
+ const candidates: Array<{ key: string; score: number }> = [];
497
+ for (const key of catKeys) {
498
+ const entry = this.cache.get(key);
499
+ if (!entry) continue;
500
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
501
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
502
+ }
503
+ candidates.sort((a, b) => a.score - b.score);
504
+
505
+ for (const { key } of candidates) {
506
+ catCnt = this.categoryCount.get(cat) ?? 0;
507
+ catSz = this.categorySize.get(cat) ?? 0;
508
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
509
+ const entry = this.cache.get(key);
510
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
511
+ this._delete(key, 'rebalance');
512
+ evicted++;
513
+ }
514
+ }
515
+
516
+ // Global limits
517
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
518
+ const before = this.cache.size;
519
+ this.smartEvict('default', false);
520
+ if (this.cache.size >= before) break; // only CRITICAL entries remain
521
+ evicted += before - this.cache.size;
522
+ }
523
+
524
+ if (evicted > 0) this.maybeRebuildBloom();
525
+ return evicted;
526
+ }
527
+
528
+ /**
529
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
530
+ * Only reflects L1 state — does not query Redis or disk.
531
+ */
532
+ ttl(key: string): number | null {
533
+ const entry = this.cache.get(key);
534
+ if (!entry) return null;
535
+ const remaining = entry.expiresAt - Date.now();
536
+ return remaining > 0 ? Math.ceil(remaining / 1000) : null;
537
+ }
538
+
374
539
  /**
375
540
  * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
376
541
  * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
@@ -385,7 +550,7 @@ export class SmartMemoryCache {
385
550
  const candidates: Array<{ key: string; score: number }> = [];
386
551
  for (const [key, entry] of this.cache) {
387
552
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
388
- candidates.push({ key, score: this.score(entry, 0, now) });
553
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
389
554
  }
390
555
  candidates.sort((a, b) => a.score - b.score);
391
556
  const count = Math.max(1, Math.ceil(candidates.length * pct));
@@ -393,7 +558,7 @@ export class SmartMemoryCache {
393
558
  for (const { key } of candidates.slice(0, count)) {
394
559
  const entry = this.cache.get(key);
395
560
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
396
- this._delete(key);
561
+ this._delete(key, 'oom');
397
562
  evicted++;
398
563
  }
399
564
  return evicted;
@@ -402,7 +567,7 @@ export class SmartMemoryCache {
402
567
  cleanup(): number {
403
568
  const now = Date.now();
404
569
  let cleaned = 0;
405
- for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key); cleaned++; }
570
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key, 'ttl'); cleaned++; }
406
571
  if (cleaned > 0) { this.bloom.rebuild(this.cache.keys()); this._bloomDirtyCount = 0; }
407
572
  return cleaned;
408
573
  }
@@ -435,7 +600,9 @@ export class SmartMemoryCache {
435
600
  : rawData instanceof Uint8Array
436
601
  ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
437
602
  : rawData as Buffer; // already a Buffer
438
- this.cache.set(key, { ...entry, data, isCompressed: true });
603
+ // Decode once on import so subsequent gets return the live object without unpacking.
604
+ const value = unpack(data);
605
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
439
606
  this.bloom.add(key);
440
607
  loaded++;
441
608
  }
@@ -443,17 +610,59 @@ export class SmartMemoryCache {
443
610
  return loaded;
444
611
  }
445
612
 
613
+ // ── Iterators ─────────────────────────────────────────────────────────────
614
+
615
+ /**
616
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
617
+ * Expired entries that are still in the Map (awaiting background cleanup)
618
+ * are silently skipped.
619
+ */
620
+ *liveEntries(): Generator<[string, SmartCacheEntry]> {
621
+ const now = Date.now();
622
+ for (const [key, entry] of this.cache) {
623
+ if (entry.expiresAt > now) yield [key, entry];
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Yields only the keys of live entries — no intermediate tuple allocation.
629
+ * Use this instead of liveEntries() when you only need keys.
630
+ */
631
+ *liveKeys(): Generator<string> {
632
+ const now = Date.now();
633
+ for (const [key, entry] of this.cache) {
634
+ if (entry.expiresAt > now) yield key;
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Yields only the resolved values of live entries.
640
+ * Iterates Map.values() so the key is never loaded into the yielded path.
641
+ * Returns the cached deserialized object when available (entry.value), otherwise
642
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
643
+ */
644
+ *liveValues(): Generator<unknown> {
645
+ const now = Date.now();
646
+ for (const entry of this.cache.values()) {
647
+ if (entry.expiresAt > now)
648
+ yield entry.value !== undefined ? entry.value : entry.data;
649
+ }
650
+ }
651
+
446
652
  // ── Stats ─────────────────────────────────────────────────────────────────
447
653
 
448
654
  get size(): number { return this.cache.size; }
449
655
  get memoryUsage(): number { return this.totalSize; }
450
656
 
451
657
  getStats() {
452
- const categories: Record<string, number> = {};
453
- for (const [cat, cnt] of this.categoryCount) categories[cat] = cnt;
658
+ const categories: Record<string, { entries: number; hits: number }> = {};
659
+ for (const [cat, cnt] of this.categoryCount) {
660
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
661
+ }
454
662
  return {
455
- entries: this.cache.size,
456
- sizeKB: Math.round(this.totalSize / 1024),
663
+ entries: this.cache.size,
664
+ sizeBytes: this.totalSize,
665
+ sizeKB: Math.round(this.totalSize / 1024),
457
666
  categories,
458
667
  bloom: {
459
668
  checks: this.bloomChecks,
@@ -467,6 +676,57 @@ export class SmartMemoryCache {
467
676
  };
468
677
  }
469
678
 
679
+ /**
680
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
681
+ * Does NOT count as a hit or perform SWR logic.
682
+ */
683
+ getEntry(key: string): SmartCacheEntry | undefined {
684
+ const entry = this.cache.get(key);
685
+ if (!entry) return undefined;
686
+ if (entry.expiresAt <= Date.now()) return undefined;
687
+ return entry;
688
+ }
689
+
690
+ /**
691
+ * Return true if the key exists in L1 and has not expired.
692
+ * Uses the bloom filter as a fast negative check.
693
+ */
694
+ has(key: string): boolean {
695
+ if (!this.bloom.mightContain(key)) return false;
696
+ const entry = this.cache.get(key);
697
+ if (!entry) return false;
698
+ if (entry.expiresAt <= Date.now()) {
699
+ this._delete(key, 'ttl');
700
+ return false;
701
+ }
702
+ return true;
703
+ }
704
+
705
+ /**
706
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
707
+ * @param newTtlMs - New TTL from now, in milliseconds.
708
+ */
709
+ touch(key: string, newTtlMs: number): boolean {
710
+ const entry = this.cache.get(key);
711
+ if (!entry) return false;
712
+ const now = Date.now();
713
+ if (entry.expiresAt <= now) { this._delete(key, 'ttl'); return false; }
714
+ entry.expiresAt = now + newTtlMs;
715
+ return true;
716
+ }
717
+
718
+ /**
719
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
720
+ * Returns `false` if the key is absent or already expired.
721
+ */
722
+ bumpExpiry(key: string, additionalMs: number): boolean {
723
+ const entry = this.cache.get(key);
724
+ if (!entry) return false;
725
+ if (entry.expiresAt <= Date.now()) return false;
726
+ entry.expiresAt += additionalMs;
727
+ return true;
728
+ }
729
+
470
730
  bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
471
731
  bloomStats() { return this.bloom.stats; }
472
732
  }