tricache 0.5.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) */
@@ -424,6 +427,37 @@ interface CacheOptions {
424
427
  * No-op when Redis is disabled or unreachable — safe to set unconditionally.
425
428
  */
426
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;
427
461
  }
428
462
 
429
463
  /**
@@ -470,6 +504,7 @@ declare class CacheService {
470
504
  private snapshotLoaded;
471
505
  private _readyPromise;
472
506
  private cleanupInterval;
507
+ private diskJanitorInterval;
473
508
  private oomInterval;
474
509
  private metricsInterval;
475
510
  private _shutdownHandler;
@@ -510,6 +545,9 @@ declare class CacheService {
510
545
  private nk;
511
546
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
512
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;
513
551
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
514
552
  private _startSpan;
515
553
  private initBackplane;
@@ -544,6 +582,13 @@ declare class CacheService {
544
582
  refreshAhead?: number;
545
583
  xfetchBeta?: number;
546
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[];
547
592
  }): Promise<T>;
548
593
  private _revalidate;
549
594
  /** Explicitly write a value into L1 (+ L2 in production). */
@@ -551,6 +596,11 @@ declare class CacheService {
551
596
  tags?: string[];
552
597
  dependsOn?: string[];
553
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;
554
604
  /**
555
605
  * Delete one key or a glob pattern (supports `*` wildcard).
556
606
  *
@@ -612,6 +662,27 @@ declare class CacheService {
612
662
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
613
663
  */
614
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;
615
686
  /**
616
687
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
617
688
  * Returns `false` if the key is absent or already expired.
@@ -687,7 +758,9 @@ declare class CacheService {
687
758
  * const loaded = await cache.warmFromL2('org:*');
688
759
  * console.log(`Warmed ${loaded} keys from Redis`);
689
760
  */
690
- warmFromL2(pattern: string): Promise<number>;
761
+ warmFromL2(pattern: string, opts?: {
762
+ priority?: CachePriority;
763
+ }): Promise<number>;
691
764
  /**
692
765
  * Invalidate all keys associated with a tag.
693
766
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -697,6 +770,19 @@ declare class CacheService {
697
770
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
698
771
  */
699
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>;
700
786
  /**
701
787
  * Measure L1 / disk / Redis latency.
702
788
  * Useful for health checks and dashboards.
@@ -984,6 +1070,25 @@ declare class SmartMemoryCache {
984
1070
  * are silently skipped.
985
1071
  */
986
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;
987
1092
  /**
988
1093
  * Yields only the keys of live entries — no intermediate tuple allocation.
989
1094
  * Use this instead of liveEntries() when you only need keys.
@@ -1088,20 +1193,35 @@ declare class DiskTier {
1088
1193
  private diskUsageBytes;
1089
1194
  private usageCounted;
1090
1195
  private fileCount;
1196
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1197
+ private _nextJanitorBucket;
1091
1198
  constructor(opts: DiskTierOptions);
1092
1199
  private ensureDir;
1093
1200
  private ensureUsageCounted;
1094
1201
  /**
1095
- * 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.
1096
1211
  *
1097
- * Files are sharded into two-character hex prefix subdirectories to avoid
1098
- * putting thousands of flat files into a single directory node — which
1099
- * degrades EXT4/NTFS performance at scale.
1212
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1213
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1100
1214
  *
1101
- * key → SHA-256 hex e3b0c442...
1102
- * path → {dir}/e3/e3b0c442...
1215
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1216
+ */
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.
1103
1223
  */
1104
- private keyToPath;
1224
+ private findFilePath;
1105
1225
  /**
1106
1226
  * Recursively list all cache file paths across the 2-level sharded subdirs.
1107
1227
  * Top-level entries that are not directories are skipped (e.g. stale flat
@@ -1111,6 +1231,18 @@ declare class DiskTier {
1111
1231
  private isForbidden;
1112
1232
  private encrypt;
1113
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;
1114
1246
  /**
1115
1247
  * Spill an evicted L1 entry to disk.
1116
1248
  *
@@ -1132,6 +1264,18 @@ declare class DiskTier {
1132
1264
  delete(key: string): void;
1133
1265
  /** Purge all expired entries. Returns number deleted. */
1134
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;
1135
1279
  /** Delete every file in the disk cache. Returns the count deleted. */
1136
1280
  clear(): number;
1137
1281
  get stats(): {