tricache 0.3.0 → 0.4.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/README.md +141 -19
- package/dist/index.cjs +351 -17
- package/dist/index.d.cts +196 -6
- package/dist/index.d.ts +196 -6
- package/dist/index.js +351 -17
- package/package.json +11 -10
- package/src/cache-service.ts +399 -25
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +21 -2
- package/src/types.ts +84 -0
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* tricache — shared types and interfaces
|
|
3
3
|
*/
|
|
4
|
+
/**
|
|
5
|
+
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
6
|
+
* Pass your existing OTEL tracer; no extra package required.
|
|
7
|
+
*/
|
|
8
|
+
interface ICacheSpan {
|
|
9
|
+
setAttribute(key: string, value: string | number | boolean): this;
|
|
10
|
+
setStatus(status: {
|
|
11
|
+
code: 0 | 1 | 2;
|
|
12
|
+
message?: string;
|
|
13
|
+
}): this;
|
|
14
|
+
end(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
18
|
+
*/
|
|
19
|
+
interface ICacheTracer {
|
|
20
|
+
startSpan(name: string): ICacheSpan;
|
|
21
|
+
}
|
|
4
22
|
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
5
23
|
interface ILogger {
|
|
6
24
|
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
@@ -61,12 +79,23 @@ interface SmartCacheEntry {
|
|
|
61
79
|
lastAccess: number;
|
|
62
80
|
/** Eviction priority */
|
|
63
81
|
priority: CachePriority;
|
|
82
|
+
/** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
|
|
83
|
+
ttlMs?: number;
|
|
84
|
+
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
85
|
+
delta?: number;
|
|
64
86
|
}
|
|
65
87
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
66
88
|
interface CacheHit {
|
|
67
89
|
value: unknown;
|
|
68
90
|
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
69
91
|
isStale: boolean;
|
|
92
|
+
/** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
|
|
93
|
+
* without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
|
|
94
|
+
expiresAt: number;
|
|
95
|
+
/** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
|
|
96
|
+
ttlMs?: number;
|
|
97
|
+
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
98
|
+
delta?: number;
|
|
70
99
|
}
|
|
71
100
|
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
72
101
|
* legacy disk files written by older versions may have a JSON string in data) */
|
|
@@ -144,6 +173,11 @@ interface CacheMetrics {
|
|
|
144
173
|
/** Own messages silently skipped (prevents double-eviction) */
|
|
145
174
|
skipped: number;
|
|
146
175
|
};
|
|
176
|
+
/** L2 Redis circuit breaker state */
|
|
177
|
+
l2CircuitBreaker: {
|
|
178
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
179
|
+
state: 'closed' | 'open' | 'half_open';
|
|
180
|
+
};
|
|
147
181
|
/** OOM guard statistics */
|
|
148
182
|
oom: {
|
|
149
183
|
enabled: boolean;
|
|
@@ -342,6 +376,48 @@ interface CacheOptions {
|
|
|
342
376
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
343
377
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
344
378
|
metricsIntervalMs?: number;
|
|
379
|
+
/**
|
|
380
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
381
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
382
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
383
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
384
|
+
*
|
|
385
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
386
|
+
* dependency required; the interface is structurally compatible.
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* import { trace } from '@opentelemetry/api';
|
|
390
|
+
* tracer: trace.getTracer('tricache')
|
|
391
|
+
*/
|
|
392
|
+
tracer?: ICacheTracer;
|
|
393
|
+
/**
|
|
394
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
395
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
396
|
+
* the same TTL and expire simultaneously.
|
|
397
|
+
*
|
|
398
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
399
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
400
|
+
*/
|
|
401
|
+
ttlJitterFactor?: number;
|
|
402
|
+
/**
|
|
403
|
+
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
404
|
+
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
405
|
+
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
406
|
+
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
407
|
+
*/
|
|
408
|
+
notFoundTtl?: number;
|
|
409
|
+
/**
|
|
410
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
411
|
+
* attempting Redis until the cooldown elapses).
|
|
412
|
+
* Default: `5`.
|
|
413
|
+
*/
|
|
414
|
+
l2CircuitBreakerThreshold?: number;
|
|
415
|
+
/**
|
|
416
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
417
|
+
* (allows a single probe request to test recovery).
|
|
418
|
+
* Default: `30 000` ms (30 s).
|
|
419
|
+
*/
|
|
420
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
345
421
|
}
|
|
346
422
|
|
|
347
423
|
/**
|
|
@@ -377,8 +453,14 @@ declare class CacheService {
|
|
|
377
453
|
private readonly _l1Counters;
|
|
378
454
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
379
455
|
private readonly tagIndex;
|
|
456
|
+
/**
|
|
457
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
458
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
459
|
+
*/
|
|
460
|
+
private readonly dependencyIndex;
|
|
380
461
|
private redis;
|
|
381
462
|
private redisConnecting;
|
|
463
|
+
private readonly cb;
|
|
382
464
|
private snapshotLoaded;
|
|
383
465
|
private cleanupInterval;
|
|
384
466
|
private oomInterval;
|
|
@@ -419,6 +501,10 @@ declare class CacheService {
|
|
|
419
501
|
* receive and provide un-prefixed keys in the public API.
|
|
420
502
|
*/
|
|
421
503
|
private nk;
|
|
504
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
505
|
+
private _jitterTtl;
|
|
506
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
507
|
+
private _startSpan;
|
|
422
508
|
private initBackplane;
|
|
423
509
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
424
510
|
_handleBackplaneMessage(message: string): void;
|
|
@@ -432,19 +518,31 @@ declare class CacheService {
|
|
|
432
518
|
* @param cacheKey - Unique key identifying this value
|
|
433
519
|
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
434
520
|
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
435
|
-
* @param opts.priority
|
|
436
|
-
* @param opts.swr
|
|
437
|
-
*
|
|
438
|
-
*
|
|
521
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
522
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
523
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
524
|
+
* is triggered proactively while the caller still receives the
|
|
525
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
526
|
+
* Requires `fetchFn` to be stable across calls.
|
|
527
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
528
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
529
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
530
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
531
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
532
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
439
533
|
*/
|
|
440
534
|
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
441
535
|
priority?: CachePriority;
|
|
442
536
|
swr?: number;
|
|
537
|
+
refreshAhead?: number;
|
|
538
|
+
xfetchBeta?: number;
|
|
539
|
+
notFoundTtl?: number;
|
|
443
540
|
}): Promise<T>;
|
|
444
541
|
private _revalidate;
|
|
445
542
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
446
543
|
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
447
544
|
tags?: string[];
|
|
545
|
+
dependsOn?: string[];
|
|
448
546
|
}): Promise<void>;
|
|
449
547
|
/**
|
|
450
548
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -532,6 +630,44 @@ declare class CacheService {
|
|
|
532
630
|
* @param ttl - TTL in seconds for newly fetched values.
|
|
533
631
|
*/
|
|
534
632
|
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
633
|
+
/**
|
|
634
|
+
* Batch write — set multiple entries in a single call.
|
|
635
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
636
|
+
*
|
|
637
|
+
* @example
|
|
638
|
+
* await cache.mset({
|
|
639
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
640
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
641
|
+
* });
|
|
642
|
+
*/
|
|
643
|
+
mset<T = unknown>(entries: Record<string, {
|
|
644
|
+
value: T;
|
|
645
|
+
ttl?: number;
|
|
646
|
+
priority?: CachePriority;
|
|
647
|
+
tags?: string[];
|
|
648
|
+
dependsOn?: string[];
|
|
649
|
+
}>): Promise<void>;
|
|
650
|
+
/**
|
|
651
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
652
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
656
|
+
*/
|
|
657
|
+
mdel(keys: string[]): Promise<void>;
|
|
658
|
+
/**
|
|
659
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
660
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
661
|
+
* the local snapshot is unavailable or too stale.
|
|
662
|
+
*
|
|
663
|
+
* Returns the number of keys loaded into L1.
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
667
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
668
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
669
|
+
*/
|
|
670
|
+
warmFromL2(pattern: string): Promise<number>;
|
|
535
671
|
/**
|
|
536
672
|
* Invalidate all keys associated with a tag.
|
|
537
673
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -580,6 +716,48 @@ declare class CacheService {
|
|
|
580
716
|
maxKB: number;
|
|
581
717
|
};
|
|
582
718
|
};
|
|
719
|
+
/**
|
|
720
|
+
* Write `value` only if the key is not already cached.
|
|
721
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
722
|
+
*
|
|
723
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
724
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
725
|
+
* multiple instances. L1 is populated on success.
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
729
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
730
|
+
*/
|
|
731
|
+
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
732
|
+
/**
|
|
733
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
734
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
735
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
736
|
+
*
|
|
737
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
738
|
+
* collection overhead.
|
|
739
|
+
*
|
|
740
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
741
|
+
*
|
|
742
|
+
* @example
|
|
743
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
744
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
745
|
+
*/
|
|
746
|
+
hotKeys(n?: number): Array<{
|
|
747
|
+
key: string;
|
|
748
|
+
hits: number;
|
|
749
|
+
sizeBytes: number;
|
|
750
|
+
}>;
|
|
751
|
+
/**
|
|
752
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
753
|
+
* pattern that may contain `*` wildcards).
|
|
754
|
+
*/
|
|
755
|
+
private _matchesGlob;
|
|
756
|
+
/**
|
|
757
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
758
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
759
|
+
*/
|
|
760
|
+
private _cascadeDependencies;
|
|
583
761
|
/** Return a full metrics snapshot. */
|
|
584
762
|
metrics(): CacheMetrics;
|
|
585
763
|
/**
|
|
@@ -746,7 +924,7 @@ declare class SmartMemoryCache {
|
|
|
746
924
|
private maybeRebuildBloom;
|
|
747
925
|
private smartEvict;
|
|
748
926
|
get(key: string): CacheHit | null;
|
|
749
|
-
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
|
|
927
|
+
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
|
|
750
928
|
delete(key: string): boolean;
|
|
751
929
|
private keysMatchingPattern;
|
|
752
930
|
deletePattern(pattern: string): number;
|
|
@@ -846,6 +1024,18 @@ declare class SmartMemoryCache {
|
|
|
846
1024
|
bitsSet: number;
|
|
847
1025
|
fillFactor: number;
|
|
848
1026
|
};
|
|
1027
|
+
/**
|
|
1028
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1029
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1030
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
1031
|
+
*
|
|
1032
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
1033
|
+
*/
|
|
1034
|
+
hotKeys(n: number): Array<{
|
|
1035
|
+
key: string;
|
|
1036
|
+
hits: number;
|
|
1037
|
+
sizeBytes: number;
|
|
1038
|
+
}>;
|
|
849
1039
|
}
|
|
850
1040
|
|
|
851
1041
|
/**
|
|
@@ -960,4 +1150,4 @@ declare class WasmBloomFilter {
|
|
|
960
1150
|
get maxCapacity(): number;
|
|
961
1151
|
}
|
|
962
1152
|
|
|
963
|
-
export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
|
|
1153
|
+
export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ICacheSpan, type ICacheTracer, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* tricache — shared types and interfaces
|
|
3
3
|
*/
|
|
4
|
+
/**
|
|
5
|
+
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
6
|
+
* Pass your existing OTEL tracer; no extra package required.
|
|
7
|
+
*/
|
|
8
|
+
interface ICacheSpan {
|
|
9
|
+
setAttribute(key: string, value: string | number | boolean): this;
|
|
10
|
+
setStatus(status: {
|
|
11
|
+
code: 0 | 1 | 2;
|
|
12
|
+
message?: string;
|
|
13
|
+
}): this;
|
|
14
|
+
end(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
18
|
+
*/
|
|
19
|
+
interface ICacheTracer {
|
|
20
|
+
startSpan(name: string): ICacheSpan;
|
|
21
|
+
}
|
|
4
22
|
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
5
23
|
interface ILogger {
|
|
6
24
|
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
@@ -61,12 +79,23 @@ interface SmartCacheEntry {
|
|
|
61
79
|
lastAccess: number;
|
|
62
80
|
/** Eviction priority */
|
|
63
81
|
priority: CachePriority;
|
|
82
|
+
/** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
|
|
83
|
+
ttlMs?: number;
|
|
84
|
+
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
85
|
+
delta?: number;
|
|
64
86
|
}
|
|
65
87
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
66
88
|
interface CacheHit {
|
|
67
89
|
value: unknown;
|
|
68
90
|
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
69
91
|
isStale: boolean;
|
|
92
|
+
/** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
|
|
93
|
+
* without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
|
|
94
|
+
expiresAt: number;
|
|
95
|
+
/** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
|
|
96
|
+
ttlMs?: number;
|
|
97
|
+
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
98
|
+
delta?: number;
|
|
70
99
|
}
|
|
71
100
|
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
72
101
|
* legacy disk files written by older versions may have a JSON string in data) */
|
|
@@ -144,6 +173,11 @@ interface CacheMetrics {
|
|
|
144
173
|
/** Own messages silently skipped (prevents double-eviction) */
|
|
145
174
|
skipped: number;
|
|
146
175
|
};
|
|
176
|
+
/** L2 Redis circuit breaker state */
|
|
177
|
+
l2CircuitBreaker: {
|
|
178
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
179
|
+
state: 'closed' | 'open' | 'half_open';
|
|
180
|
+
};
|
|
147
181
|
/** OOM guard statistics */
|
|
148
182
|
oom: {
|
|
149
183
|
enabled: boolean;
|
|
@@ -342,6 +376,48 @@ interface CacheOptions {
|
|
|
342
376
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
343
377
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
344
378
|
metricsIntervalMs?: number;
|
|
379
|
+
/**
|
|
380
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
381
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
382
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
383
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
384
|
+
*
|
|
385
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
386
|
+
* dependency required; the interface is structurally compatible.
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* import { trace } from '@opentelemetry/api';
|
|
390
|
+
* tracer: trace.getTracer('tricache')
|
|
391
|
+
*/
|
|
392
|
+
tracer?: ICacheTracer;
|
|
393
|
+
/**
|
|
394
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
395
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
396
|
+
* the same TTL and expire simultaneously.
|
|
397
|
+
*
|
|
398
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
399
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
400
|
+
*/
|
|
401
|
+
ttlJitterFactor?: number;
|
|
402
|
+
/**
|
|
403
|
+
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
404
|
+
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
405
|
+
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
406
|
+
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
407
|
+
*/
|
|
408
|
+
notFoundTtl?: number;
|
|
409
|
+
/**
|
|
410
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
411
|
+
* attempting Redis until the cooldown elapses).
|
|
412
|
+
* Default: `5`.
|
|
413
|
+
*/
|
|
414
|
+
l2CircuitBreakerThreshold?: number;
|
|
415
|
+
/**
|
|
416
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
417
|
+
* (allows a single probe request to test recovery).
|
|
418
|
+
* Default: `30 000` ms (30 s).
|
|
419
|
+
*/
|
|
420
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
345
421
|
}
|
|
346
422
|
|
|
347
423
|
/**
|
|
@@ -377,8 +453,14 @@ declare class CacheService {
|
|
|
377
453
|
private readonly _l1Counters;
|
|
378
454
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
379
455
|
private readonly tagIndex;
|
|
456
|
+
/**
|
|
457
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
458
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
459
|
+
*/
|
|
460
|
+
private readonly dependencyIndex;
|
|
380
461
|
private redis;
|
|
381
462
|
private redisConnecting;
|
|
463
|
+
private readonly cb;
|
|
382
464
|
private snapshotLoaded;
|
|
383
465
|
private cleanupInterval;
|
|
384
466
|
private oomInterval;
|
|
@@ -419,6 +501,10 @@ declare class CacheService {
|
|
|
419
501
|
* receive and provide un-prefixed keys in the public API.
|
|
420
502
|
*/
|
|
421
503
|
private nk;
|
|
504
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
505
|
+
private _jitterTtl;
|
|
506
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
507
|
+
private _startSpan;
|
|
422
508
|
private initBackplane;
|
|
423
509
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
424
510
|
_handleBackplaneMessage(message: string): void;
|
|
@@ -432,19 +518,31 @@ declare class CacheService {
|
|
|
432
518
|
* @param cacheKey - Unique key identifying this value
|
|
433
519
|
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
434
520
|
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
435
|
-
* @param opts.priority
|
|
436
|
-
* @param opts.swr
|
|
437
|
-
*
|
|
438
|
-
*
|
|
521
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
522
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
523
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
524
|
+
* is triggered proactively while the caller still receives the
|
|
525
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
526
|
+
* Requires `fetchFn` to be stable across calls.
|
|
527
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
528
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
529
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
530
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
531
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
532
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
439
533
|
*/
|
|
440
534
|
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
441
535
|
priority?: CachePriority;
|
|
442
536
|
swr?: number;
|
|
537
|
+
refreshAhead?: number;
|
|
538
|
+
xfetchBeta?: number;
|
|
539
|
+
notFoundTtl?: number;
|
|
443
540
|
}): Promise<T>;
|
|
444
541
|
private _revalidate;
|
|
445
542
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
446
543
|
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
447
544
|
tags?: string[];
|
|
545
|
+
dependsOn?: string[];
|
|
448
546
|
}): Promise<void>;
|
|
449
547
|
/**
|
|
450
548
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -532,6 +630,44 @@ declare class CacheService {
|
|
|
532
630
|
* @param ttl - TTL in seconds for newly fetched values.
|
|
533
631
|
*/
|
|
534
632
|
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
633
|
+
/**
|
|
634
|
+
* Batch write — set multiple entries in a single call.
|
|
635
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
636
|
+
*
|
|
637
|
+
* @example
|
|
638
|
+
* await cache.mset({
|
|
639
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
640
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
641
|
+
* });
|
|
642
|
+
*/
|
|
643
|
+
mset<T = unknown>(entries: Record<string, {
|
|
644
|
+
value: T;
|
|
645
|
+
ttl?: number;
|
|
646
|
+
priority?: CachePriority;
|
|
647
|
+
tags?: string[];
|
|
648
|
+
dependsOn?: string[];
|
|
649
|
+
}>): Promise<void>;
|
|
650
|
+
/**
|
|
651
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
652
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
656
|
+
*/
|
|
657
|
+
mdel(keys: string[]): Promise<void>;
|
|
658
|
+
/**
|
|
659
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
660
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
661
|
+
* the local snapshot is unavailable or too stale.
|
|
662
|
+
*
|
|
663
|
+
* Returns the number of keys loaded into L1.
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
667
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
668
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
669
|
+
*/
|
|
670
|
+
warmFromL2(pattern: string): Promise<number>;
|
|
535
671
|
/**
|
|
536
672
|
* Invalidate all keys associated with a tag.
|
|
537
673
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -580,6 +716,48 @@ declare class CacheService {
|
|
|
580
716
|
maxKB: number;
|
|
581
717
|
};
|
|
582
718
|
};
|
|
719
|
+
/**
|
|
720
|
+
* Write `value` only if the key is not already cached.
|
|
721
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
722
|
+
*
|
|
723
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
724
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
725
|
+
* multiple instances. L1 is populated on success.
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
729
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
730
|
+
*/
|
|
731
|
+
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
732
|
+
/**
|
|
733
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
734
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
735
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
736
|
+
*
|
|
737
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
738
|
+
* collection overhead.
|
|
739
|
+
*
|
|
740
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
741
|
+
*
|
|
742
|
+
* @example
|
|
743
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
744
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
745
|
+
*/
|
|
746
|
+
hotKeys(n?: number): Array<{
|
|
747
|
+
key: string;
|
|
748
|
+
hits: number;
|
|
749
|
+
sizeBytes: number;
|
|
750
|
+
}>;
|
|
751
|
+
/**
|
|
752
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
753
|
+
* pattern that may contain `*` wildcards).
|
|
754
|
+
*/
|
|
755
|
+
private _matchesGlob;
|
|
756
|
+
/**
|
|
757
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
758
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
759
|
+
*/
|
|
760
|
+
private _cascadeDependencies;
|
|
583
761
|
/** Return a full metrics snapshot. */
|
|
584
762
|
metrics(): CacheMetrics;
|
|
585
763
|
/**
|
|
@@ -746,7 +924,7 @@ declare class SmartMemoryCache {
|
|
|
746
924
|
private maybeRebuildBloom;
|
|
747
925
|
private smartEvict;
|
|
748
926
|
get(key: string): CacheHit | null;
|
|
749
|
-
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
|
|
927
|
+
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
|
|
750
928
|
delete(key: string): boolean;
|
|
751
929
|
private keysMatchingPattern;
|
|
752
930
|
deletePattern(pattern: string): number;
|
|
@@ -846,6 +1024,18 @@ declare class SmartMemoryCache {
|
|
|
846
1024
|
bitsSet: number;
|
|
847
1025
|
fillFactor: number;
|
|
848
1026
|
};
|
|
1027
|
+
/**
|
|
1028
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1029
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1030
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
1031
|
+
*
|
|
1032
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
1033
|
+
*/
|
|
1034
|
+
hotKeys(n: number): Array<{
|
|
1035
|
+
key: string;
|
|
1036
|
+
hits: number;
|
|
1037
|
+
sizeBytes: number;
|
|
1038
|
+
}>;
|
|
849
1039
|
}
|
|
850
1040
|
|
|
851
1041
|
/**
|
|
@@ -960,4 +1150,4 @@ declare class WasmBloomFilter {
|
|
|
960
1150
|
get maxCapacity(): number;
|
|
961
1151
|
}
|
|
962
1152
|
|
|
963
|
-
export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
|
|
1153
|
+
export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ICacheSpan, type ICacheTracer, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
|