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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -36,16 +36,16 @@
36
36
  "LICENSE"
37
37
  ],
38
38
  "scripts": {
39
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
40
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
41
- "typecheck": "tsc --noEmit",
42
- "test": "vitest run",
39
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
40
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
41
+ "typecheck": "tsc --noEmit",
42
+ "test": "vitest run",
43
43
  "test:watch": "vitest",
44
- "bench": "node --import tsx/esm bench/benchmark.ts"
44
+ "bench": "node --import tsx/esm bench/benchmark.ts"
45
45
  },
46
46
  "dependencies": {
47
47
  "ioredis": "^5.3.2",
48
- "msgpackr": "^1.10.1"
48
+ "msgpackr": "^2.0.1"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@types/node": "^24.0.0",
@@ -57,8 +57,9 @@
57
57
  "engines": {
58
58
  "node": ">=22.13.0"
59
59
  },
60
+ "homepage": "https://github.com/Kareem411/TriCache#readme",
60
61
  "repository": {
61
62
  "type": "git",
62
- "url": "git+https://github.com/Kareem411/tricache.git"
63
+ "url": "git+https://github.com/Kareem411/TriCache.git"
63
64
  }
64
65
  }
@@ -17,11 +17,12 @@
17
17
  */
18
18
 
19
19
  import { Redis as RedisClient } from 'ioredis';
20
+ import { pack, unpack } from 'msgpackr';
20
21
  import crypto from 'crypto';
21
22
  import os from 'os';
22
23
  import fs from 'fs';
23
24
  import path from 'path';
24
- import { pack, unpack } from 'msgpackr';
25
+
25
26
 
26
27
  import {
27
28
  CachePriority,
@@ -30,6 +31,7 @@ import {
30
31
  DiskCacheEntry,
31
32
  CacheOptions,
32
33
  CacheMetrics,
34
+ CachePingResult,
33
35
  ILogger,
34
36
  consoleLogger,
35
37
  } from './types';
@@ -89,6 +91,9 @@ export class CacheService {
89
91
  oomCheckIntervalMs: number; oomEvictPercent: number;
90
92
  onMetrics: ((m: CacheMetrics) => void) | undefined;
91
93
  metricsIntervalMs: number;
94
+ staleIfError: number;
95
+ l2WriteMode: 'read-write' | 'read-only';
96
+ instanceName: string;
92
97
  };
93
98
  /** Pre-computed once — opts.namespace never changes after construction. */
94
99
  private readonly _namespace: string;
@@ -96,6 +101,9 @@ export class CacheService {
96
101
  private readonly _redisDisabled: boolean;
97
102
  private readonly inflight = new Map<string, Promise<unknown>>();
98
103
  private readonly revalidating = new Set<string>();
104
+ private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
105
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
106
+ private readonly tagIndex = new Map<string, Set<string>>();
99
107
  private redis: RedisClient | null = null;
100
108
  private redisConnecting: Promise<RedisClient> | null = null;
101
109
  private snapshotLoaded = false;
@@ -135,7 +143,13 @@ export class CacheService {
135
143
 
136
144
  // Resolve encryption key: option > env var
137
145
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
138
- this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode);
146
+ this.enc = new CacheEncryption(
147
+ encKeyRaw,
148
+ logger,
149
+ options.encryptionMode,
150
+ options.previousEncryptionKey,
151
+ options.previousEncryptionMode,
152
+ );
139
153
 
140
154
  // When a namespace is active, scope the forbidden prefixes so that
141
155
  // auth/session keys like `org_abc:auth:token` are still protected.
@@ -173,6 +187,9 @@ export class CacheService {
173
187
  oomEvictPercent: options.oomEvictPercent ?? 0.20,
174
188
  onMetrics: options.onMetrics,
175
189
  metricsIntervalMs: options.metricsIntervalMs ?? 60_000,
190
+ staleIfError: options.staleIfError ?? 0,
191
+ l2WriteMode: options.l2WriteMode ?? 'read-write',
192
+ instanceName: options.instanceName ?? '',
176
193
  };
177
194
 
178
195
  // L1.5 disk tier
@@ -194,6 +211,7 @@ export class CacheService {
194
211
  maxEntries: this.opts.l1MaxEntries,
195
212
  categories: this.opts.categoryLimits,
196
213
  diskSpill: (key: string, entry: SmartCacheEntry) => { void this.disk.save(key, entry as unknown as DiskCacheEntry); },
214
+ onEviction: options.onEviction,
197
215
  logger,
198
216
  });
199
217
 
@@ -269,6 +287,18 @@ export class CacheService {
269
287
  return g[key] as CacheService;
270
288
  }
271
289
 
290
+ /**
291
+ * Async factory — accepts a Promise that resolves to CacheOptions.
292
+ * Useful when config is fetched from a secret store at startup.
293
+ *
294
+ * @example
295
+ * const cache = await CacheService.createAsync(fetchSecrets());
296
+ */
297
+ static async createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService> {
298
+ const resolved = await options;
299
+ return CacheService.create(resolved);
300
+ }
301
+
272
302
  /** Replace the singleton (useful in tests). */
273
303
  static reset(options?: CacheOptions): CacheService {
274
304
  const g = globalThis as Record<string, unknown>;
@@ -365,32 +395,37 @@ export class CacheService {
365
395
  if (this.redisConnecting) return this.redisConnecting;
366
396
 
367
397
  this.redisConnecting = (async () => {
368
- const client = new RedisClient({
369
- host: this.opts.redisHost,
370
- port: this.opts.redisPort,
371
- tls: this.opts.redisTls ? {} : undefined,
372
- connectTimeout: 10_000,
373
- lazyConnect: false,
374
- maxRetriesPerRequest: 3,
375
- enableAutoPipelining: true,
376
- keepAlive: 30_000,
377
- family: 4,
378
- retryStrategy: (times: number) => Math.min(times * 50, 2_000),
379
- });
398
+ try {
399
+ const client = new RedisClient({
400
+ host: this.opts.redisHost,
401
+ port: this.opts.redisPort,
402
+ tls: this.opts.redisTls ? {} : undefined,
403
+ connectTimeout: 10_000,
404
+ lazyConnect: false,
405
+ maxRetriesPerRequest: 3,
406
+ enableAutoPipelining: true,
407
+ keepAlive: 30_000,
408
+ family: 4,
409
+ retryStrategy: (times: number) => Math.min(times * 50, 2_000),
410
+ });
380
411
 
381
- client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
382
- client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
383
- client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
412
+ client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
413
+ client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
414
+ client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
384
415
 
385
- await new Promise<void>((resolve, reject) => {
386
- client.once('ready', resolve);
387
- client.once('error', reject);
388
- setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
389
- });
416
+ await new Promise<void>((resolve, reject) => {
417
+ client.once('ready', resolve);
418
+ client.once('error', reject);
419
+ setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
420
+ });
390
421
 
391
- this.redis = client;
392
- this.redisConnecting = null;
393
- return client;
422
+ this.redis = client;
423
+ this.redisConnecting = null;
424
+ return client;
425
+ } catch (err) {
426
+ this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
427
+ throw err;
428
+ }
394
429
  })();
395
430
 
396
431
  return this.redisConnecting;
@@ -398,7 +433,7 @@ export class CacheService {
398
433
 
399
434
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
400
435
 
401
- writeSnapshot(): void {
436
+ writeSnapshot(altPath?: string): void {
402
437
  try {
403
438
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
404
439
  if (entries.length === 0) return;
@@ -406,10 +441,11 @@ export class CacheService {
406
441
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
407
442
  const packed = pack(payload);
408
443
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
444
+ const dest = altPath ?? this.opts.snapshotPath;
409
445
 
410
- fs.writeFileSync(this.opts.snapshotPath, final, { mode: 0o600 });
446
+ fs.writeFileSync(dest, final, { mode: 0o600 });
411
447
  this.logger.info('Cache snapshot written', {
412
- path: this.opts.snapshotPath, entries: entries.length,
448
+ path: dest, entries: entries.length,
413
449
  sizeKB: Math.round(final.length / 1024), encrypted: this.enc.isEnabled,
414
450
  });
415
451
  } catch (err) {
@@ -609,7 +645,7 @@ export class CacheService {
609
645
  const staleAt = Date.now() + ttlMs;
610
646
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
611
647
 
612
- if (!this._redisDisabled) {
648
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
613
649
  try {
614
650
  const client = await this.getRedis();
615
651
  const s = JSON.stringify(data);
@@ -619,7 +655,15 @@ export class CacheService {
619
655
  }
620
656
  this.logger.debug('SWR: revalidation complete', { cacheKey });
621
657
  } catch (err) {
622
- this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
658
+ if (this.opts.staleIfError > 0) {
659
+ const additionalMs = this.opts.staleIfError * 1_000;
660
+ this.l1.bumpExpiry(cacheKey, additionalMs);
661
+ this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
662
+ cacheKey, staleIfErrorSecs: this.opts.staleIfError,
663
+ });
664
+ } else {
665
+ this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
666
+ }
623
667
  } finally {
624
668
  this.revalidating.delete(cacheKey);
625
669
  }
@@ -628,14 +672,36 @@ export class CacheService {
628
672
  // ── Explicit set / delete ─────────────────────────────────────────────────
629
673
 
630
674
  /** Explicitly write a value into L1 (+ L2 in production). */
631
- async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority): Promise<void> {
675
+ async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
632
676
  const ttlMs = ttlSeconds * 1_000;
633
677
  const p = priority ?? inferPriority(cacheKey);
634
678
  const k = this.nk(cacheKey);
635
679
  this.counters.sets++;
636
680
  this.l1.set(k, data, ttlMs, p);
637
681
 
638
- if (!this._redisDisabled) {
682
+ // Register tags in the in-process index (+ Redis SADD)
683
+ if (opts?.tags?.length) {
684
+ for (const tag of opts.tags) {
685
+ const tagKey = this.nk(`_tag_:${tag}`);
686
+ let members = this.tagIndex.get(tagKey);
687
+ if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
688
+ members.add(k);
689
+ }
690
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
691
+ try {
692
+ const client = await this.getRedis();
693
+ const pl = client.pipeline();
694
+ for (const tag of opts.tags) {
695
+ const tagKey = this.nk(`_tag_:${tag}`);
696
+ pl.sadd(tagKey, k);
697
+ pl.expire(tagKey, ttlSeconds + 3_600); // keep tag set alive longer than entries
698
+ }
699
+ await pl.exec();
700
+ } catch { /* tags are best-effort */ }
701
+ }
702
+ }
703
+
704
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
639
705
  try {
640
706
  const client = await this.getRedis();
641
707
  const s = JSON.stringify(data);
@@ -668,7 +734,7 @@ export class CacheService {
668
734
  this.disk.delete(k);
669
735
  }
670
736
 
671
- if (!this._redisDisabled) {
737
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
672
738
  try {
673
739
  const client = await this.getRedis();
674
740
  if (isPattern) {
@@ -698,8 +764,20 @@ export class CacheService {
698
764
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
699
765
  */
700
766
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
701
- if (this._redisDisabled) return 0;
702
767
  const k = this.nk(cacheKey);
768
+
769
+ if (this._redisDisabled) {
770
+ const now = Date.now();
771
+ const ttlMs = (ttlSeconds ?? 60) * 1_000;
772
+ const entry = this._l1Counters.get(k);
773
+ if (entry && entry.expiresAt > now) {
774
+ entry.value++;
775
+ return entry.value;
776
+ }
777
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
778
+ return 1;
779
+ }
780
+
703
781
  try {
704
782
  const client = await this.getRedis();
705
783
  const count = await client.incr(k);
@@ -711,7 +789,256 @@ export class CacheService {
711
789
  }
712
790
  }
713
791
 
714
- // ── Stats ─────────────────────────────────────────────────────────────────
792
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
793
+
794
+ /**
795
+ * Flush all cached entries, or only those whose key starts with `prefix`.
796
+ *
797
+ * @example
798
+ * await cache.clear(); // flush everything
799
+ * await cache.clear('user:abc'); // flush all keys for one user
800
+ */
801
+ async clear(prefix?: string): Promise<void> {
802
+ this.counters.deletes++;
803
+ const k = prefix
804
+ ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
805
+ : undefined;
806
+
807
+ if (k) {
808
+ this.l1.deletePattern(k);
809
+ // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
810
+ // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
811
+ } else {
812
+ this.l1.clear();
813
+ this.disk.clear();
814
+ this._l1Counters.clear();
815
+ this.tagIndex.clear();
816
+ }
817
+
818
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
819
+ try {
820
+ const client = await this.getRedis();
821
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
822
+ const stream = client.scanStream({ match: pattern, count: 100 });
823
+ const keys: string[] = [];
824
+ await new Promise<void>((resolve, reject) => {
825
+ stream.on('data', (chunk: string[]) => keys.push(...chunk));
826
+ stream.on('end', resolve);
827
+ stream.on('error', reject);
828
+ });
829
+ if (keys.length > 0) await client.del(...keys);
830
+ } catch (err) {
831
+ this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
832
+ }
833
+ }
834
+
835
+ void this.publishInvalidation('del-glob',
836
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'));
837
+ }
838
+
839
+ /**
840
+ * Evict L1 entries that violate the current category or global capacity limits.
841
+ * Useful after a write burst or after adding stricter `categoryLimits`.
842
+ * Returns the number of entries evicted.
843
+ */
844
+ rebalance(): number {
845
+ return this.l1.rebalance();
846
+ }
847
+
848
+ /**
849
+ * Return the remaining TTL in seconds for a key currently in L1.
850
+ * Returns null if the key is absent from L1 or has already expired.
851
+ * Only reflects L1 state — does not query Redis or disk.
852
+ */
853
+ ttl(cacheKey: string): number | null {
854
+ return this.l1.ttl(this.nk(cacheKey));
855
+ }
856
+
857
+ /**
858
+ * Return true if the key exists in L1 and has not expired.
859
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
860
+ */
861
+ has(cacheKey: string): boolean {
862
+ return this.l1.has(this.nk(cacheKey));
863
+ }
864
+
865
+ /**
866
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
867
+ * Returns `false` if the key is absent or already expired.
868
+ *
869
+ * @param newTtlSeconds - The new TTL from now, in seconds.
870
+ */
871
+ async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
872
+ const k = this.nk(cacheKey);
873
+ const hit = this.l1.touch(k, newTtlSeconds * 1_000);
874
+ if (hit && !this._redisDisabled) {
875
+ try {
876
+ const client = await this.getRedis();
877
+ void client.expire(k, newTtlSeconds); // fire-and-forget
878
+ } catch { /* ok */ }
879
+ }
880
+ return hit;
881
+ }
882
+
883
+ /**
884
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
885
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
886
+ *
887
+ * @example
888
+ * const fresh = cache.getIfFresh('user:123');
889
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
890
+ */
891
+ getIfFresh<T = unknown>(cacheKey: string): T | null {
892
+ const k = this.nk(cacheKey);
893
+ const entry = this.l1.getEntry(k);
894
+ if (!entry) return null;
895
+ const now = Date.now();
896
+ if (entry.expiresAt <= now) return null; // expired
897
+ if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
898
+ return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
899
+ }
900
+
901
+ /**
902
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
903
+ * Preserves input ordering. Uses inflight coalescing per key.
904
+ *
905
+ * @param keys - Array of cache keys.
906
+ * @param fetchFn - Called with only the keys that missed L1.
907
+ * @param ttl - TTL in seconds for newly fetched values.
908
+ */
909
+ async mget<T>(
910
+ keys: string[],
911
+ fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
912
+ ttl = 300,
913
+ priority?: CachePriority,
914
+ ): Promise<(T | undefined)[]> {
915
+ const result: (T | undefined)[] = new Array(keys.length);
916
+ const missIndexes: number[] = [];
917
+ const missKeys: string[] = [];
918
+
919
+ for (let i = 0; i < keys.length; i++) {
920
+ const entry = this.l1.getEntry(this.nk(keys[i]));
921
+ if (entry && entry.expiresAt > Date.now()) {
922
+ result[i] = (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
923
+ this.counters.l1Hits++;
924
+ } else {
925
+ missIndexes.push(i);
926
+ missKeys.push(keys[i]);
927
+ }
928
+ }
929
+
930
+ if (missKeys.length > 0) {
931
+ const fetched = await fetchFn(missKeys);
932
+ for (let j = 0; j < missKeys.length; j++) {
933
+ const v = fetched[missKeys[j]];
934
+ result[missIndexes[j]] = v;
935
+ if (v !== undefined) {
936
+ await this.set(missKeys[j], v, ttl, priority);
937
+ }
938
+ }
939
+ }
940
+
941
+ return result;
942
+ }
943
+
944
+ /**
945
+ * Invalidate all keys associated with a tag.
946
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
947
+ *
948
+ * @example
949
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
950
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
951
+ */
952
+ async invalidateTag(tag: string): Promise<void> {
953
+ const tagKey = this.nk(`_tag_:${tag}`);
954
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
955
+
956
+ // Remove from L1 + disk
957
+ for (const k of members) {
958
+ this.l1.delete(k);
959
+ this.disk.delete(k);
960
+ }
961
+ this.tagIndex.delete(tagKey);
962
+
963
+ if (!this._redisDisabled) {
964
+ try {
965
+ const client = await this.getRedis();
966
+ const redisMembers: string[] = await client.smembers(tagKey);
967
+ const toDelete = [...new Set([...members, ...redisMembers])];
968
+ if (toDelete.length > 0) {
969
+ await client.del(...toDelete, tagKey);
970
+ } else {
971
+ await client.del(tagKey);
972
+ }
973
+ } catch (err) {
974
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
975
+ }
976
+ }
977
+ }
978
+
979
+ /**
980
+ * Measure L1 / disk / Redis latency.
981
+ * Useful for health checks and dashboards.
982
+ *
983
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
984
+ * `l2` is `null` when Redis is disabled.
985
+ */
986
+ async ping(): Promise<CachePingResult> {
987
+ // L1: measure a has() call
988
+ const t0 = Date.now();
989
+ this.l1.has('__ping__');
990
+ const l1 = Date.now() - t0;
991
+
992
+ // Disk: measure a stats access
993
+ const t1 = Date.now();
994
+ void this.disk.stats;
995
+ const disk = Date.now() - t1;
996
+
997
+ // L2: PING command
998
+ let l2: number | null = null;
999
+ if (!this._redisDisabled) {
1000
+ try {
1001
+ const client = await this.getRedis();
1002
+ const t2 = Date.now();
1003
+ await client.ping();
1004
+ l2 = Date.now() - t2;
1005
+ } catch { l2 = null; }
1006
+ }
1007
+
1008
+ return { l1, disk, l2 };
1009
+ }
1010
+
1011
+ /**
1012
+ * Export all live L1 entries to Redis via a single pipeline.
1013
+ * Useful for warming a new Redis instance or for zero-downtime failover.
1014
+ * Returns the number of keys written.
1015
+ */
1016
+ async drainToL2(): Promise<number> {
1017
+ if (this._redisDisabled) return 0;
1018
+ try {
1019
+ const client = await this.getRedis();
1020
+ const entries = this.l1.exportEntries([]);
1021
+ const now = Date.now();
1022
+ if (entries.length === 0) return 0;
1023
+
1024
+ const pl = client.pipeline();
1025
+ for (const { key, entry } of entries) {
1026
+ const remainingMs = entry.expiresAt - now;
1027
+ if (remainingMs <= 0) continue;
1028
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1_000));
1029
+ const s = JSON.stringify(entry.value);
1030
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1031
+ pl.setex(key, ttlSecs, stored);
1032
+ }
1033
+ await pl.exec();
1034
+ return entries.length;
1035
+ } catch (err) {
1036
+ this.logger.debug('drainToL2: Redis unavailable', { error: (err as Error).message });
1037
+ return 0;
1038
+ }
1039
+ }
1040
+
1041
+ // ── Stats ─────────────────────────────────────────────────────────────
715
1042
 
716
1043
  stats() {
717
1044
  return {
@@ -790,8 +1117,11 @@ export class CacheService {
790
1117
  * @param m - Snapshot returned by `cache.metrics()`
791
1118
  * @param prefix - Metric name prefix. Default: `"tricache"`
792
1119
  */
793
- static toPrometheusText(m: CacheMetrics, prefix = 'tricache'): string {
794
- const lbl = m.namespace ? `{namespace="${m.namespace}"}` : '';
1120
+ static toPrometheusText(m: CacheMetrics, prefix = 'tricache', instanceName?: string): string {
1121
+ const parts: string[] = [];
1122
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
1123
+ if (instanceName) parts.push(`instance="${instanceName}"`);
1124
+ const lbl = parts.length ? `{${parts.join(',')}}` : '';
795
1125
  const lines: string[] = [];
796
1126
 
797
1127
  const counter = (name: string, val: number, help: string) => {
package/src/disk-tier.ts CHANGED
@@ -18,8 +18,7 @@ import fs from 'fs';
18
18
  import path from 'path';
19
19
  import crypto from 'crypto';
20
20
  import { pack, unpack } from 'msgpackr';
21
- import type { DiskCacheEntry, ILogger } from './types';
22
-
21
+ import { DiskCacheEntry, ILogger } from './types.js';
23
22
  // ── Encryption (self-contained to avoid circular import) ─────────────────────
24
23
 
25
24
  const AES_ALGO = 'aes-256-gcm' as const;
@@ -293,6 +292,23 @@ export class DiskTier {
293
292
  return purged;
294
293
  }
295
294
 
295
+ /** Delete every file in the disk cache. Returns the count deleted. */
296
+ clear(): number {
297
+ this.ensureDir();
298
+ if (!this.dirReady) return 0;
299
+ let cleared = 0;
300
+ for (const filePath of this.walkCacheFiles()) {
301
+ try {
302
+ const stat = fs.statSync(filePath);
303
+ fs.unlinkSync(filePath);
304
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
305
+ this.fileCount = Math.max(0, this.fileCount - 1);
306
+ cleared++;
307
+ } catch { /* skip locked/gone */ }
308
+ }
309
+ return cleared;
310
+ }
311
+
296
312
  get stats(): { files: number; sizeKB: number; maxKB: number } {
297
313
  // fileCount is maintained in-memory — O(1), no filesystem scan.
298
314
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };