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.
@@ -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>;
@@ -318,23 +348,7 @@ export class CacheService {
318
348
  this.logger.debug('Backplane subscriber error', { error: e.message }));
319
349
 
320
350
  sub.on('message', (_channel: string, message: string) => {
321
- try {
322
- const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
323
- if (msg.src === this.instanceId) {
324
- this.counters.invSkipped++;
325
- return; // own message — our L1 is already current
326
- }
327
- this.counters.invReceived++;
328
- if (msg.op === 'del') {
329
- this.l1.delete(msg.key);
330
- this.disk.delete(msg.key);
331
- } else if (msg.op === 'del-glob') {
332
- this.l1.deletePattern(msg.key);
333
- }
334
- this.logger.debug('Backplane: peer invalidation applied', {
335
- op: msg.op, key: msg.key.slice(0, 60),
336
- });
337
- } catch { /* malformed message — ignore */ }
351
+ this._handleBackplaneMessage(message);
338
352
  });
339
353
 
340
354
  sub.subscribe(this.backplaneChannel)
@@ -348,6 +362,32 @@ export class CacheService {
348
362
  this.subClient = sub;
349
363
  }
350
364
 
365
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
366
+ _handleBackplaneMessage(message: string): void {
367
+ try {
368
+ const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
369
+ if (msg.src === this.instanceId) {
370
+ this.counters.invSkipped++;
371
+ return; // own message — our L1 is already current
372
+ }
373
+ this.counters.invReceived++;
374
+ if (msg.op === 'del') {
375
+ // L1 eviction is synchronous and O(1); disk delete is deferred via
376
+ // setImmediate so the event-loop tick that processes this pub/sub
377
+ // message returns immediately without blocking hot get() calls.
378
+ this.l1.delete(msg.key);
379
+ setImmediate(() => this.disk.delete(msg.key));
380
+ } else if (msg.op === 'del-glob') {
381
+ // Glob patterns clean L1 only — disk entries expire naturally via
382
+ // the background purge timer or are bypassed on the next L1 miss.
383
+ this.l1.deletePattern(msg.key);
384
+ }
385
+ this.logger.debug('Backplane: peer invalidation applied', {
386
+ op: msg.op, key: msg.key.slice(0, 60),
387
+ });
388
+ } catch { /* malformed message — ignore */ }
389
+ }
390
+
351
391
  private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
352
392
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
353
393
  try {
@@ -365,32 +405,37 @@ export class CacheService {
365
405
  if (this.redisConnecting) return this.redisConnecting;
366
406
 
367
407
  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
- });
408
+ try {
409
+ const client = new RedisClient({
410
+ host: this.opts.redisHost,
411
+ port: this.opts.redisPort,
412
+ tls: this.opts.redisTls ? {} : undefined,
413
+ connectTimeout: 10_000,
414
+ lazyConnect: false,
415
+ maxRetriesPerRequest: 3,
416
+ enableAutoPipelining: true,
417
+ keepAlive: 30_000,
418
+ family: 4,
419
+ retryStrategy: (times: number) => Math.min(times * 50, 2_000),
420
+ });
380
421
 
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'));
422
+ client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
423
+ client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
424
+ client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
384
425
 
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
- });
426
+ await new Promise<void>((resolve, reject) => {
427
+ client.once('ready', resolve);
428
+ client.once('error', reject);
429
+ setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
430
+ });
390
431
 
391
- this.redis = client;
392
- this.redisConnecting = null;
393
- return client;
432
+ this.redis = client;
433
+ this.redisConnecting = null;
434
+ return client;
435
+ } catch (err) {
436
+ this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
437
+ throw err;
438
+ }
394
439
  })();
395
440
 
396
441
  return this.redisConnecting;
@@ -398,7 +443,7 @@ export class CacheService {
398
443
 
399
444
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
400
445
 
401
- writeSnapshot(): void {
446
+ writeSnapshot(altPath?: string): void {
402
447
  try {
403
448
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
404
449
  if (entries.length === 0) return;
@@ -406,10 +451,11 @@ export class CacheService {
406
451
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
407
452
  const packed = pack(payload);
408
453
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
454
+ const dest = altPath ?? this.opts.snapshotPath;
409
455
 
410
- fs.writeFileSync(this.opts.snapshotPath, final, { mode: 0o600 });
456
+ fs.writeFileSync(dest, final, { mode: 0o600 });
411
457
  this.logger.info('Cache snapshot written', {
412
- path: this.opts.snapshotPath, entries: entries.length,
458
+ path: dest, entries: entries.length,
413
459
  sizeKB: Math.round(final.length / 1024), encrypted: this.enc.isEnabled,
414
460
  });
415
461
  } catch (err) {
@@ -609,7 +655,7 @@ export class CacheService {
609
655
  const staleAt = Date.now() + ttlMs;
610
656
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
611
657
 
612
- if (!this._redisDisabled) {
658
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
613
659
  try {
614
660
  const client = await this.getRedis();
615
661
  const s = JSON.stringify(data);
@@ -619,7 +665,15 @@ export class CacheService {
619
665
  }
620
666
  this.logger.debug('SWR: revalidation complete', { cacheKey });
621
667
  } catch (err) {
622
- this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
668
+ if (this.opts.staleIfError > 0) {
669
+ const additionalMs = this.opts.staleIfError * 1_000;
670
+ this.l1.bumpExpiry(cacheKey, additionalMs);
671
+ this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
672
+ cacheKey, staleIfErrorSecs: this.opts.staleIfError,
673
+ });
674
+ } else {
675
+ this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
676
+ }
623
677
  } finally {
624
678
  this.revalidating.delete(cacheKey);
625
679
  }
@@ -628,14 +682,36 @@ export class CacheService {
628
682
  // ── Explicit set / delete ─────────────────────────────────────────────────
629
683
 
630
684
  /** Explicitly write a value into L1 (+ L2 in production). */
631
- async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority): Promise<void> {
685
+ async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
632
686
  const ttlMs = ttlSeconds * 1_000;
633
687
  const p = priority ?? inferPriority(cacheKey);
634
688
  const k = this.nk(cacheKey);
635
689
  this.counters.sets++;
636
690
  this.l1.set(k, data, ttlMs, p);
637
691
 
638
- if (!this._redisDisabled) {
692
+ // Register tags in the in-process index (+ Redis SADD)
693
+ if (opts?.tags?.length) {
694
+ for (const tag of opts.tags) {
695
+ const tagKey = this.nk(`_tag_:${tag}`);
696
+ let members = this.tagIndex.get(tagKey);
697
+ if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
698
+ members.add(k);
699
+ }
700
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
701
+ try {
702
+ const client = await this.getRedis();
703
+ const pl = client.pipeline();
704
+ for (const tag of opts.tags) {
705
+ const tagKey = this.nk(`_tag_:${tag}`);
706
+ pl.sadd(tagKey, k);
707
+ pl.expire(tagKey, ttlSeconds + 3_600); // keep tag set alive longer than entries
708
+ }
709
+ await pl.exec();
710
+ } catch { /* tags are best-effort */ }
711
+ }
712
+ }
713
+
714
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
639
715
  try {
640
716
  const client = await this.getRedis();
641
717
  const s = JSON.stringify(data);
@@ -668,7 +744,7 @@ export class CacheService {
668
744
  this.disk.delete(k);
669
745
  }
670
746
 
671
- if (!this._redisDisabled) {
747
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
672
748
  try {
673
749
  const client = await this.getRedis();
674
750
  if (isPattern) {
@@ -698,8 +774,20 @@ export class CacheService {
698
774
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
699
775
  */
700
776
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
701
- if (this._redisDisabled) return 0;
702
777
  const k = this.nk(cacheKey);
778
+
779
+ if (this._redisDisabled) {
780
+ const now = Date.now();
781
+ const ttlMs = (ttlSeconds ?? 60) * 1_000;
782
+ const entry = this._l1Counters.get(k);
783
+ if (entry && entry.expiresAt > now) {
784
+ entry.value++;
785
+ return entry.value;
786
+ }
787
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
788
+ return 1;
789
+ }
790
+
703
791
  try {
704
792
  const client = await this.getRedis();
705
793
  const count = await client.incr(k);
@@ -711,7 +799,298 @@ export class CacheService {
711
799
  }
712
800
  }
713
801
 
714
- // ── Stats ─────────────────────────────────────────────────────────────────
802
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
803
+
804
+ /**
805
+ * Flush all cached entries, or only those whose key starts with `prefix`.
806
+ *
807
+ * @example
808
+ * await cache.clear(); // flush everything
809
+ * await cache.clear('user:abc'); // flush all keys for one user
810
+ */
811
+ async clear(prefix?: string): Promise<void> {
812
+ this.counters.deletes++;
813
+ const k = prefix
814
+ ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
815
+ : undefined;
816
+
817
+ if (k) {
818
+ this.l1.deletePattern(k);
819
+ // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
820
+ // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
821
+ } else {
822
+ this.l1.clear();
823
+ this.disk.clear();
824
+ this._l1Counters.clear();
825
+ this.tagIndex.clear();
826
+ }
827
+
828
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
829
+ try {
830
+ const client = await this.getRedis();
831
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
832
+ const stream = client.scanStream({ match: pattern, count: 100 });
833
+ const keys: string[] = [];
834
+ await new Promise<void>((resolve, reject) => {
835
+ stream.on('data', (chunk: string[]) => keys.push(...chunk));
836
+ stream.on('end', resolve);
837
+ stream.on('error', reject);
838
+ });
839
+ if (keys.length > 0) await client.del(...keys);
840
+ } catch (err) {
841
+ this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
842
+ }
843
+ }
844
+
845
+ void this.publishInvalidation('del-glob',
846
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'));
847
+ }
848
+
849
+ /**
850
+ * Evict L1 entries that violate the current category or global capacity limits.
851
+ * Useful after a write burst or after adding stricter `categoryLimits`.
852
+ * Returns the number of entries evicted.
853
+ */
854
+ rebalance(): number {
855
+ return this.l1.rebalance();
856
+ }
857
+
858
+ /**
859
+ * Return the remaining TTL in seconds for a key currently in L1.
860
+ * Returns null if the key is absent from L1 or has already expired.
861
+ * Only reflects L1 state — does not query Redis or disk.
862
+ */
863
+ ttl(cacheKey: string): number | null {
864
+ return this.l1.ttl(this.nk(cacheKey));
865
+ }
866
+
867
+ /**
868
+ * Return true if the key exists in L1 and has not expired.
869
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
870
+ */
871
+ has(cacheKey: string): boolean {
872
+ return this.l1.has(this.nk(cacheKey));
873
+ }
874
+
875
+ // ── Iteration ─────────────────────────────────────────────────────────────
876
+
877
+ /**
878
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
879
+ *
880
+ * @example
881
+ * for (const key of cache.keys()) console.log(key);
882
+ */
883
+ *keys(): Generator<string> {
884
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
885
+ for (const key of this.l1.liveKeys()) {
886
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
887
+ }
888
+ }
889
+
890
+ /**
891
+ * Lazily yield every non-expired L1 value.
892
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
893
+ *
894
+ * @example
895
+ * for (const val of cache.values<User>()) console.log(val.id);
896
+ */
897
+ *values<T = unknown>(): Generator<T> {
898
+ // yield* delegates directly into liveValues(), collapsing one generator frame.
899
+ yield* this.l1.liveValues() as Generator<T>;
900
+ }
901
+
902
+ /**
903
+ * Lazily yield every non-expired L1 [key, value] pair.
904
+ * Keys are stripped of their namespace prefix.
905
+ *
906
+ * @example
907
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
908
+ */
909
+ *entries<T = unknown>(): Generator<[string, T]> {
910
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
911
+ for (const [key, entry] of this.l1.liveEntries()) {
912
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
913
+ yield [k, (entry.value !== undefined ? entry.value : entry.data) as T];
914
+ }
915
+ }
916
+
917
+ /**
918
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
919
+ * Returns `false` if the key is absent or already expired.
920
+ *
921
+ * @param newTtlSeconds - The new TTL from now, in seconds.
922
+ */
923
+ async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
924
+ const k = this.nk(cacheKey);
925
+ const hit = this.l1.touch(k, newTtlSeconds * 1_000);
926
+ if (hit && !this._redisDisabled) {
927
+ try {
928
+ const client = await this.getRedis();
929
+ void client.expire(k, newTtlSeconds); // fire-and-forget
930
+ } catch { /* ok */ }
931
+ }
932
+ return hit;
933
+ }
934
+
935
+ /**
936
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
937
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
938
+ *
939
+ * @example
940
+ * const fresh = cache.getIfFresh('user:123');
941
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
942
+ */
943
+ getIfFresh<T = unknown>(cacheKey: string): T | null {
944
+ const k = this.nk(cacheKey);
945
+ const entry = this.l1.getEntry(k);
946
+ if (!entry) return null;
947
+ const now = Date.now();
948
+ if (entry.expiresAt <= now) return null; // expired
949
+ if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
950
+ return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
951
+ }
952
+
953
+ /**
954
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
955
+ * Preserves input ordering. Uses inflight coalescing per key.
956
+ *
957
+ * @param keys - Array of cache keys.
958
+ * @param fetchFn - Called with only the keys that missed L1.
959
+ * @param ttl - TTL in seconds for newly fetched values.
960
+ */
961
+ async mget<T>(
962
+ keys: string[],
963
+ fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
964
+ ttl = 300,
965
+ priority?: CachePriority,
966
+ ): Promise<(T | undefined)[]> {
967
+ const result: (T | undefined)[] = new Array(keys.length);
968
+ const missIndexes: number[] = [];
969
+ const missKeys: string[] = [];
970
+
971
+ for (let i = 0; i < keys.length; i++) {
972
+ const entry = this.l1.getEntry(this.nk(keys[i]));
973
+ if (entry && entry.expiresAt > Date.now()) {
974
+ result[i] = (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
975
+ this.counters.l1Hits++;
976
+ } else {
977
+ missIndexes.push(i);
978
+ missKeys.push(keys[i]);
979
+ }
980
+ }
981
+
982
+ if (missKeys.length > 0) {
983
+ const fetched = await fetchFn(missKeys);
984
+ for (let j = 0; j < missKeys.length; j++) {
985
+ const v = fetched[missKeys[j]];
986
+ result[missIndexes[j]] = v;
987
+ if (v !== undefined) {
988
+ await this.set(missKeys[j], v, ttl, priority);
989
+ }
990
+ }
991
+ }
992
+
993
+ return result;
994
+ }
995
+
996
+ /**
997
+ * Invalidate all keys associated with a tag.
998
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
999
+ *
1000
+ * @example
1001
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
1002
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
1003
+ */
1004
+ async invalidateTag(tag: string): Promise<void> {
1005
+ const tagKey = this.nk(`_tag_:${tag}`);
1006
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
1007
+
1008
+ // Remove from L1 + disk
1009
+ for (const k of members) {
1010
+ this.l1.delete(k);
1011
+ this.disk.delete(k);
1012
+ }
1013
+ this.tagIndex.delete(tagKey);
1014
+
1015
+ if (!this._redisDisabled) {
1016
+ try {
1017
+ const client = await this.getRedis();
1018
+ const redisMembers: string[] = await client.smembers(tagKey);
1019
+ const toDelete = [...new Set([...members, ...redisMembers])];
1020
+ if (toDelete.length > 0) {
1021
+ await client.del(...toDelete, tagKey);
1022
+ } else {
1023
+ await client.del(tagKey);
1024
+ }
1025
+ } catch (err) {
1026
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
1027
+ }
1028
+ }
1029
+ }
1030
+
1031
+ /**
1032
+ * Measure L1 / disk / Redis latency.
1033
+ * Useful for health checks and dashboards.
1034
+ *
1035
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
1036
+ * `l2` is `null` when Redis is disabled.
1037
+ */
1038
+ async ping(): Promise<CachePingResult> {
1039
+ // L1: measure a has() call
1040
+ const t0 = Date.now();
1041
+ this.l1.has('__ping__');
1042
+ const l1 = Date.now() - t0;
1043
+
1044
+ // Disk: measure a stats access
1045
+ const t1 = Date.now();
1046
+ void this.disk.stats;
1047
+ const disk = Date.now() - t1;
1048
+
1049
+ // L2: PING command
1050
+ let l2: number | null = null;
1051
+ if (!this._redisDisabled) {
1052
+ try {
1053
+ const client = await this.getRedis();
1054
+ const t2 = Date.now();
1055
+ await client.ping();
1056
+ l2 = Date.now() - t2;
1057
+ } catch { l2 = null; }
1058
+ }
1059
+
1060
+ return { l1, disk, l2 };
1061
+ }
1062
+
1063
+ /**
1064
+ * Export all live L1 entries to Redis via a single pipeline.
1065
+ * Useful for warming a new Redis instance or for zero-downtime failover.
1066
+ * Returns the number of keys written.
1067
+ */
1068
+ async drainToL2(): Promise<number> {
1069
+ if (this._redisDisabled) return 0;
1070
+ try {
1071
+ const client = await this.getRedis();
1072
+ const entries = this.l1.exportEntries([]);
1073
+ const now = Date.now();
1074
+ if (entries.length === 0) return 0;
1075
+
1076
+ const pl = client.pipeline();
1077
+ for (const { key, entry } of entries) {
1078
+ const remainingMs = entry.expiresAt - now;
1079
+ if (remainingMs <= 0) continue;
1080
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1_000));
1081
+ const s = JSON.stringify(entry.value);
1082
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1083
+ pl.setex(key, ttlSecs, stored);
1084
+ }
1085
+ await pl.exec();
1086
+ return entries.length;
1087
+ } catch (err) {
1088
+ this.logger.debug('drainToL2: Redis unavailable', { error: (err as Error).message });
1089
+ return 0;
1090
+ }
1091
+ }
1092
+
1093
+ // ── Stats ─────────────────────────────────────────────────────────────
715
1094
 
716
1095
  stats() {
717
1096
  return {
@@ -790,8 +1169,11 @@ export class CacheService {
790
1169
  * @param m - Snapshot returned by `cache.metrics()`
791
1170
  * @param prefix - Metric name prefix. Default: `"tricache"`
792
1171
  */
793
- static toPrometheusText(m: CacheMetrics, prefix = 'tricache'): string {
794
- const lbl = m.namespace ? `{namespace="${m.namespace}"}` : '';
1172
+ static toPrometheusText(m: CacheMetrics, prefix = 'tricache', instanceName?: string): string {
1173
+ const parts: string[] = [];
1174
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
1175
+ if (instanceName) parts.push(`instance="${instanceName}"`);
1176
+ const lbl = parts.length ? `{${parts.join(',')}}` : '';
795
1177
  const lines: string[] = [];
796
1178
 
797
1179
  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) };