tricache 0.4.0 → 0.5.1

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/dist/index.d.cts CHANGED
@@ -96,6 +96,9 @@ interface CacheHit {
96
96
  ttlMs?: number;
97
97
  /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
98
98
  delta?: number;
99
+ /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
100
+ * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
101
+ fetchedAt?: number;
99
102
  }
100
103
  /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
101
104
  * legacy disk files written by older versions may have a JSON string in data) */
@@ -418,6 +421,43 @@ interface CacheOptions {
418
421
  * Default: `30 000` ms (30 s).
419
422
  */
420
423
  l2CircuitBreakerCooldownMs?: number;
424
+ /**
425
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
426
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
427
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
428
+ */
429
+ warmKeys?: string;
430
+ /**
431
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
432
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
433
+ * metrics without waiting for the `onMetrics` interval.
434
+ *
435
+ * @example
436
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
437
+ */
438
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
439
+ /**
440
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
441
+ * Receives the caller-facing key (no namespace prefix).
442
+ *
443
+ * @example
444
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
445
+ */
446
+ onMiss?: (key: string) => void;
447
+ /**
448
+ * When `true`, every value returned from an L1 cache hit is recursively
449
+ * frozen with `Object.freeze()` before being handed to the caller.
450
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
451
+ * catching reference-semantic corruption bugs that would otherwise silently
452
+ * corrupt the cached entry.
453
+ *
454
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
455
+ * Deep-freezing large objects has measurable overhead per hit.
456
+ *
457
+ * @example
458
+ * frozen: process.env.NODE_ENV !== 'production'
459
+ */
460
+ frozen?: boolean;
421
461
  }
422
462
 
423
463
  /**
@@ -462,7 +502,9 @@ declare class CacheService {
462
502
  private redisConnecting;
463
503
  private readonly cb;
464
504
  private snapshotLoaded;
505
+ private _readyPromise;
465
506
  private cleanupInterval;
507
+ private diskJanitorInterval;
466
508
  private oomInterval;
467
509
  private metricsInterval;
468
510
  private _shutdownHandler;
@@ -503,6 +545,9 @@ declare class CacheService {
503
545
  private nk;
504
546
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
505
547
  private _jitterTtl;
548
+ /** Shared no-op span for the common case where no tracer is configured.
549
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
550
+ private static readonly _nullSpan;
506
551
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
507
552
  private _startSpan;
508
553
  private initBackplane;
@@ -537,6 +582,13 @@ declare class CacheService {
537
582
  refreshAhead?: number;
538
583
  xfetchBeta?: number;
539
584
  notFoundTtl?: number;
585
+ /**
586
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
587
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
588
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
589
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
590
+ */
591
+ tags?: string[];
540
592
  }): Promise<T>;
541
593
  private _revalidate;
542
594
  /** Explicitly write a value into L1 (+ L2 in production). */
@@ -544,6 +596,11 @@ declare class CacheService {
544
596
  tags?: string[];
545
597
  dependsOn?: string[];
546
598
  }): Promise<void>;
599
+ /**
600
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
601
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
602
+ */
603
+ private _registerTags;
547
604
  /**
548
605
  * Delete one key or a glob pattern (supports `*` wildcard).
549
606
  *
@@ -605,6 +662,27 @@ declare class CacheService {
605
662
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
606
663
  */
607
664
  entries<T = unknown>(): Generator<[string, T]>;
665
+ /**
666
+ * High-throughput bulk scan over all live L1 entries.
667
+ *
668
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
669
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
670
+ * caller uses the `offset` parameter instead of pre-slicing.
671
+ *
672
+ * ```typescript
673
+ * // Zero extra string allocations — use rawKey + offset directly:
674
+ * cache.scan((rawKey, value, offset) => {
675
+ * const key = rawKey.slice(offset); // allocate only if needed
676
+ * sync(key, value as User);
677
+ * });
678
+ * ```
679
+ *
680
+ * @param fn Called once per live L1 entry.
681
+ * `rawKey` — key with namespace prefix still attached.
682
+ * `value` — deserialized cached value.
683
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
684
+ */
685
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
608
686
  /**
609
687
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
610
688
  * Returns `false` if the key is absent or already expired.
@@ -627,9 +705,22 @@ declare class CacheService {
627
705
  *
628
706
  * @param keys - Array of cache keys.
629
707
  * @param fetchFn - Called with only the keys that missed L1.
630
- * @param ttl - TTL in seconds for newly fetched values.
708
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
709
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
710
+ */
711
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
712
+ /**
713
+ * Returns a Promise that resolves once the cache is fully initialised and any
714
+ * startup warming configured via `warmKeys` has completed.
715
+ *
716
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
717
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
718
+ *
719
+ * @example
720
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
721
+ * await cache.ready(); // gate traffic until warm
631
722
  */
632
- mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
723
+ ready(): Promise<void>;
633
724
  /**
634
725
  * Batch write — set multiple entries in a single call.
635
726
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -667,7 +758,9 @@ declare class CacheService {
667
758
  * const loaded = await cache.warmFromL2('org:*');
668
759
  * console.log(`Warmed ${loaded} keys from Redis`);
669
760
  */
670
- warmFromL2(pattern: string): Promise<number>;
761
+ warmFromL2(pattern: string, opts?: {
762
+ priority?: CachePriority;
763
+ }): Promise<number>;
671
764
  /**
672
765
  * Invalidate all keys associated with a tag.
673
766
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -677,6 +770,19 @@ declare class CacheService {
677
770
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
678
771
  */
679
772
  invalidateTag(tag: string): Promise<void>;
773
+ /**
774
+ * Invalidate all keys associated with any of the given tags in a single operation.
775
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
776
+ * reducing latency when invalidating several related tags together.
777
+ *
778
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
779
+ * synchronously before the Redis round-trip.
780
+ *
781
+ * @example
782
+ * // Instead of three serial round-trips:
783
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
784
+ */
785
+ invalidateTags(tags: string[]): Promise<void>;
680
786
  /**
681
787
  * Measure L1 / disk / Redis latency.
682
788
  * Useful for health checks and dashboards.
@@ -964,6 +1070,25 @@ declare class SmartMemoryCache {
964
1070
  * are silently skipped.
965
1071
  */
966
1072
  liveEntries(): Generator<[string, SmartCacheEntry]>;
1073
+ /**
1074
+ * Non-generator bulk scan over all live entries.
1075
+ *
1076
+ * Faster than the generator-based iterators for bulk operations because:
1077
+ * - No generator state-machine overhead (no yield/resume suspend points).
1078
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
1079
+ * - The same Map call-site is used by a single plain `for` loop instead of being
1080
+ * shared across three competing generator functions, giving V8's IC a cleaner
1081
+ * monomorphic profile for this path.
1082
+ *
1083
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
1084
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
1085
+ * key, avoiding the allocation entirely for callers that don't.
1086
+ *
1087
+ * @param fn Called once per live entry.
1088
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
1089
+ * Pass 0 when no namespace is configured.
1090
+ */
1091
+ scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
967
1092
  /**
968
1093
  * Yields only the keys of live entries — no intermediate tuple allocation.
969
1094
  * Use this instead of liveEntries() when you only need keys.
@@ -1068,20 +1193,35 @@ declare class DiskTier {
1068
1193
  private diskUsageBytes;
1069
1194
  private usageCounted;
1070
1195
  private fileCount;
1196
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1197
+ private _nextJanitorBucket;
1071
1198
  constructor(opts: DiskTierOptions);
1072
1199
  private ensureDir;
1073
1200
  private ensureUsageCounted;
1074
1201
  /**
1075
- * Map a cache key to its on-disk path.
1202
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1203
+ * Kept separate from path construction so callers can find files by prefix
1204
+ * without knowing which filename generation was used when the file was written.
1205
+ */
1206
+ private keyToHash;
1207
+ /**
1208
+ * Build the write path for a NEW file (V3 generation).
1209
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1210
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1076
1211
  *
1077
- * Files are sharded into two-character hex prefix subdirectories to avoid
1078
- * putting thousands of flat files into a single directory node — which
1079
- * degrades EXT4/NTFS performance at scale.
1212
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1213
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1080
1214
  *
1081
- * key → SHA-256 hex e3b0c442...
1082
- * path → {dir}/e3/e3b0c442...
1215
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1083
1216
  */
1084
- private keyToPath;
1217
+ private hashToWritePath;
1218
+ /**
1219
+ * Find the on-disk file for a key hash, handling all filename generations:
1220
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1221
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1222
+ * Returns null when the bucket dir does not exist or the key is absent.
1223
+ */
1224
+ private findFilePath;
1085
1225
  /**
1086
1226
  * Recursively list all cache file paths across the 2-level sharded subdirs.
1087
1227
  * Top-level entries that are not directories are skipped (e.g. stale flat
@@ -1091,6 +1231,18 @@ declare class DiskTier {
1091
1231
  private isForbidden;
1092
1232
  private encrypt;
1093
1233
  private decrypt;
1234
+ /**
1235
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1236
+ * the outer 16-byte header alongside the plaintext expiresAt).
1237
+ * Returns the buffer unchanged when no encryption key is configured.
1238
+ */
1239
+ private encryptV2;
1240
+ /**
1241
+ * V2 decryption — inner payload after stripping the 16-byte header.
1242
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1243
+ * without a key the payload is raw msgpack.
1244
+ */
1245
+ private decryptV2;
1094
1246
  /**
1095
1247
  * Spill an evicted L1 entry to disk.
1096
1248
  *
@@ -1112,6 +1264,18 @@ declare class DiskTier {
1112
1264
  delete(key: string): void;
1113
1265
  /** Purge all expired entries. Returns number deleted. */
1114
1266
  purgeExpired(): number;
1267
+ /**
1268
+ * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1269
+ * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1270
+ * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1271
+ * of landing as one large synchronous burst every 5 minutes.
1272
+ *
1273
+ * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1274
+ * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1275
+ *
1276
+ * Returns the number of entries deleted in this tick.
1277
+ */
1278
+ purgeNextBucket(): number;
1115
1279
  /** Delete every file in the disk cache. Returns the count deleted. */
1116
1280
  clear(): number;
1117
1281
  get stats(): {
package/dist/index.d.ts CHANGED
@@ -96,6 +96,9 @@ interface CacheHit {
96
96
  ttlMs?: number;
97
97
  /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
98
98
  delta?: number;
99
+ /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
100
+ * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
101
+ fetchedAt?: number;
99
102
  }
100
103
  /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
101
104
  * legacy disk files written by older versions may have a JSON string in data) */
@@ -418,6 +421,43 @@ interface CacheOptions {
418
421
  * Default: `30 000` ms (30 s).
419
422
  */
420
423
  l2CircuitBreakerCooldownMs?: number;
424
+ /**
425
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
426
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
427
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
428
+ */
429
+ warmKeys?: string;
430
+ /**
431
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
432
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
433
+ * metrics without waiting for the `onMetrics` interval.
434
+ *
435
+ * @example
436
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
437
+ */
438
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
439
+ /**
440
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
441
+ * Receives the caller-facing key (no namespace prefix).
442
+ *
443
+ * @example
444
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
445
+ */
446
+ onMiss?: (key: string) => void;
447
+ /**
448
+ * When `true`, every value returned from an L1 cache hit is recursively
449
+ * frozen with `Object.freeze()` before being handed to the caller.
450
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
451
+ * catching reference-semantic corruption bugs that would otherwise silently
452
+ * corrupt the cached entry.
453
+ *
454
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
455
+ * Deep-freezing large objects has measurable overhead per hit.
456
+ *
457
+ * @example
458
+ * frozen: process.env.NODE_ENV !== 'production'
459
+ */
460
+ frozen?: boolean;
421
461
  }
422
462
 
423
463
  /**
@@ -462,7 +502,9 @@ declare class CacheService {
462
502
  private redisConnecting;
463
503
  private readonly cb;
464
504
  private snapshotLoaded;
505
+ private _readyPromise;
465
506
  private cleanupInterval;
507
+ private diskJanitorInterval;
466
508
  private oomInterval;
467
509
  private metricsInterval;
468
510
  private _shutdownHandler;
@@ -503,6 +545,9 @@ declare class CacheService {
503
545
  private nk;
504
546
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
505
547
  private _jitterTtl;
548
+ /** Shared no-op span for the common case where no tracer is configured.
549
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
550
+ private static readonly _nullSpan;
506
551
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
507
552
  private _startSpan;
508
553
  private initBackplane;
@@ -537,6 +582,13 @@ declare class CacheService {
537
582
  refreshAhead?: number;
538
583
  xfetchBeta?: number;
539
584
  notFoundTtl?: number;
585
+ /**
586
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
587
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
588
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
589
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
590
+ */
591
+ tags?: string[];
540
592
  }): Promise<T>;
541
593
  private _revalidate;
542
594
  /** Explicitly write a value into L1 (+ L2 in production). */
@@ -544,6 +596,11 @@ declare class CacheService {
544
596
  tags?: string[];
545
597
  dependsOn?: string[];
546
598
  }): Promise<void>;
599
+ /**
600
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
601
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
602
+ */
603
+ private _registerTags;
547
604
  /**
548
605
  * Delete one key or a glob pattern (supports `*` wildcard).
549
606
  *
@@ -605,6 +662,27 @@ declare class CacheService {
605
662
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
606
663
  */
607
664
  entries<T = unknown>(): Generator<[string, T]>;
665
+ /**
666
+ * High-throughput bulk scan over all live L1 entries.
667
+ *
668
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
669
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
670
+ * caller uses the `offset` parameter instead of pre-slicing.
671
+ *
672
+ * ```typescript
673
+ * // Zero extra string allocations — use rawKey + offset directly:
674
+ * cache.scan((rawKey, value, offset) => {
675
+ * const key = rawKey.slice(offset); // allocate only if needed
676
+ * sync(key, value as User);
677
+ * });
678
+ * ```
679
+ *
680
+ * @param fn Called once per live L1 entry.
681
+ * `rawKey` — key with namespace prefix still attached.
682
+ * `value` — deserialized cached value.
683
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
684
+ */
685
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
608
686
  /**
609
687
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
610
688
  * Returns `false` if the key is absent or already expired.
@@ -627,9 +705,22 @@ declare class CacheService {
627
705
  *
628
706
  * @param keys - Array of cache keys.
629
707
  * @param fetchFn - Called with only the keys that missed L1.
630
- * @param ttl - TTL in seconds for newly fetched values.
708
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
709
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
710
+ */
711
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
712
+ /**
713
+ * Returns a Promise that resolves once the cache is fully initialised and any
714
+ * startup warming configured via `warmKeys` has completed.
715
+ *
716
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
717
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
718
+ *
719
+ * @example
720
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
721
+ * await cache.ready(); // gate traffic until warm
631
722
  */
632
- mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
723
+ ready(): Promise<void>;
633
724
  /**
634
725
  * Batch write — set multiple entries in a single call.
635
726
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -667,7 +758,9 @@ declare class CacheService {
667
758
  * const loaded = await cache.warmFromL2('org:*');
668
759
  * console.log(`Warmed ${loaded} keys from Redis`);
669
760
  */
670
- warmFromL2(pattern: string): Promise<number>;
761
+ warmFromL2(pattern: string, opts?: {
762
+ priority?: CachePriority;
763
+ }): Promise<number>;
671
764
  /**
672
765
  * Invalidate all keys associated with a tag.
673
766
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -677,6 +770,19 @@ declare class CacheService {
677
770
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
678
771
  */
679
772
  invalidateTag(tag: string): Promise<void>;
773
+ /**
774
+ * Invalidate all keys associated with any of the given tags in a single operation.
775
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
776
+ * reducing latency when invalidating several related tags together.
777
+ *
778
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
779
+ * synchronously before the Redis round-trip.
780
+ *
781
+ * @example
782
+ * // Instead of three serial round-trips:
783
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
784
+ */
785
+ invalidateTags(tags: string[]): Promise<void>;
680
786
  /**
681
787
  * Measure L1 / disk / Redis latency.
682
788
  * Useful for health checks and dashboards.
@@ -964,6 +1070,25 @@ declare class SmartMemoryCache {
964
1070
  * are silently skipped.
965
1071
  */
966
1072
  liveEntries(): Generator<[string, SmartCacheEntry]>;
1073
+ /**
1074
+ * Non-generator bulk scan over all live entries.
1075
+ *
1076
+ * Faster than the generator-based iterators for bulk operations because:
1077
+ * - No generator state-machine overhead (no yield/resume suspend points).
1078
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
1079
+ * - The same Map call-site is used by a single plain `for` loop instead of being
1080
+ * shared across three competing generator functions, giving V8's IC a cleaner
1081
+ * monomorphic profile for this path.
1082
+ *
1083
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
1084
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
1085
+ * key, avoiding the allocation entirely for callers that don't.
1086
+ *
1087
+ * @param fn Called once per live entry.
1088
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
1089
+ * Pass 0 when no namespace is configured.
1090
+ */
1091
+ scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
967
1092
  /**
968
1093
  * Yields only the keys of live entries — no intermediate tuple allocation.
969
1094
  * Use this instead of liveEntries() when you only need keys.
@@ -1068,20 +1193,35 @@ declare class DiskTier {
1068
1193
  private diskUsageBytes;
1069
1194
  private usageCounted;
1070
1195
  private fileCount;
1196
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1197
+ private _nextJanitorBucket;
1071
1198
  constructor(opts: DiskTierOptions);
1072
1199
  private ensureDir;
1073
1200
  private ensureUsageCounted;
1074
1201
  /**
1075
- * Map a cache key to its on-disk path.
1202
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1203
+ * Kept separate from path construction so callers can find files by prefix
1204
+ * without knowing which filename generation was used when the file was written.
1205
+ */
1206
+ private keyToHash;
1207
+ /**
1208
+ * Build the write path for a NEW file (V3 generation).
1209
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1210
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1076
1211
  *
1077
- * Files are sharded into two-character hex prefix subdirectories to avoid
1078
- * putting thousands of flat files into a single directory node — which
1079
- * degrades EXT4/NTFS performance at scale.
1212
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1213
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1080
1214
  *
1081
- * key → SHA-256 hex e3b0c442...
1082
- * path → {dir}/e3/e3b0c442...
1215
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1083
1216
  */
1084
- private keyToPath;
1217
+ private hashToWritePath;
1218
+ /**
1219
+ * Find the on-disk file for a key hash, handling all filename generations:
1220
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1221
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1222
+ * Returns null when the bucket dir does not exist or the key is absent.
1223
+ */
1224
+ private findFilePath;
1085
1225
  /**
1086
1226
  * Recursively list all cache file paths across the 2-level sharded subdirs.
1087
1227
  * Top-level entries that are not directories are skipped (e.g. stale flat
@@ -1091,6 +1231,18 @@ declare class DiskTier {
1091
1231
  private isForbidden;
1092
1232
  private encrypt;
1093
1233
  private decrypt;
1234
+ /**
1235
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1236
+ * the outer 16-byte header alongside the plaintext expiresAt).
1237
+ * Returns the buffer unchanged when no encryption key is configured.
1238
+ */
1239
+ private encryptV2;
1240
+ /**
1241
+ * V2 decryption — inner payload after stripping the 16-byte header.
1242
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1243
+ * without a key the payload is raw msgpack.
1244
+ */
1245
+ private decryptV2;
1094
1246
  /**
1095
1247
  * Spill an evicted L1 entry to disk.
1096
1248
  *
@@ -1112,6 +1264,18 @@ declare class DiskTier {
1112
1264
  delete(key: string): void;
1113
1265
  /** Purge all expired entries. Returns number deleted. */
1114
1266
  purgeExpired(): number;
1267
+ /**
1268
+ * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1269
+ * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1270
+ * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1271
+ * of landing as one large synchronous burst every 5 minutes.
1272
+ *
1273
+ * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1274
+ * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1275
+ *
1276
+ * Returns the number of entries deleted in this tick.
1277
+ */
1278
+ purgeNextBucket(): number;
1115
1279
  /** Delete every file in the disk cache. Returns the count deleted. */
1116
1280
  clear(): number;
1117
1281
  get stats(): {