tricache 0.5.1 → 0.6.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 +14 -0
- package/dist/cache-service.d.ts +419 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1788 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +150 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +808 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +90 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +393 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +463 -72
- package/dist/index.d.cts +123 -6
- package/dist/index.d.ts +18 -1310
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -3131
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +208 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +933 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +537 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +20 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm/bloom-filter-wasm.d.ts +29 -0
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -0
- package/dist/wasm/bloom-filter-wasm.js +83 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +2 -2
- package/src/cache-service.ts +201 -17
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/smart-memory-cache.ts +63 -30
- package/src/types.ts +80 -0
package/README.md
CHANGED
|
@@ -46,6 +46,7 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
|
|
|
46
46
|
| **`setIfAbsent()`** | Atomic "set if not cached" — L1 `has()` check → Redis `SET NX EX` → L1 set on success; returns `true` if written, `false` if already present |
|
|
47
47
|
| **Refresh-ahead** | Proactively recompute an entry in the background when remaining TTL falls below a configured fraction — zero-latency freshness |
|
|
48
48
|
| **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
|
|
49
|
+
| **Adaptive TTL** | Tracks per-key fetch latency in a rolling ring buffer; once ≥ 5 samples are collected, automatically sets TTL = `p95LatencyMs × multiplier`. Expensive keys get cached longer; cheap keys stay close to their base TTL — no manual TTL tuning required |
|
|
49
50
|
| **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
|
|
50
51
|
| **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
|
|
51
52
|
| **`onHit` / `onMiss` callbacks** | Per-operation hit/miss hooks with tier info (`'l1'` \| `'disk'` \| `'l2'`) — no wait for the metrics interval |
|
|
@@ -170,6 +171,8 @@ CacheService.create({
|
|
|
170
171
|
// ── L1 (in-memory) ───────────────────────────────────────────────────
|
|
171
172
|
l1MaxBytes: 200 * 1024 * 1024, // 200 MB total RAM cap (default)
|
|
172
173
|
l1MaxEntries: 2_000, // max entries in L1 (default)
|
|
174
|
+
l1EvictionWatermark: 0.9, // proactive eviction fires at 90 % of l1MaxEntries / l1MaxBytes (default)
|
|
175
|
+
// lower to 0.8 to reduce GC pressure on heap-bound workloads
|
|
173
176
|
categoryLimits: {
|
|
174
177
|
// per-prefix limits — keys are matched by startsWith()
|
|
175
178
|
'user:': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
|
|
@@ -229,6 +232,17 @@ CacheService.create({
|
|
|
229
232
|
// Range [0, 1]; default 0 (no jitter).
|
|
230
233
|
ttlJitterFactor: 0.15, // ± 15 % spread
|
|
231
234
|
|
|
235
|
+
// ── Adaptive TTL ──────────────────────────────────────────────────────
|
|
236
|
+
// When true, tricache tracks per-key fetch latency in a rolling ring
|
|
237
|
+
// buffer and derives an optimal TTL from the p95 fetch duration:
|
|
238
|
+
// adaptedTtl = clamp(p95LatencyMs × multiplier, min, max)
|
|
239
|
+
// The caller-supplied ttlSeconds is used until ≥ 5 samples are collected,
|
|
240
|
+
// then the library takes over TTL management autonomously.
|
|
241
|
+
adaptiveTtl: true,
|
|
242
|
+
adaptiveTtlMin: 10, // floor: never assign TTL below 10 s (default)
|
|
243
|
+
adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
|
|
244
|
+
adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
|
|
245
|
+
|
|
232
246
|
// ── OpenTelemetry tracer ──────────────────────────────────────────────
|
|
233
247
|
// Pass any @opentelemetry/api-compatible tracer. No peer dependency.
|
|
234
248
|
// Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CacheService — three-tier cache with stampede prevention and SWR.
|
|
3
|
+
*
|
|
4
|
+
* Architecture:
|
|
5
|
+
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
6
|
+
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
7
|
+
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
8
|
+
* DB → your fetchFunction (cache miss path)
|
|
9
|
+
*
|
|
10
|
+
* Key features:
|
|
11
|
+
* - Thundering-herd / cache-stampede prevention (inflight Promise registry)
|
|
12
|
+
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
13
|
+
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
14
|
+
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
15
|
+
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
16
|
+
* - Periodic cleanup of expired entries every 5 minutes
|
|
17
|
+
*/
|
|
18
|
+
import { CachePriority, CacheOptions, CacheMetrics, CachePingResult } from './types';
|
|
19
|
+
export declare class CacheService {
|
|
20
|
+
private readonly logger;
|
|
21
|
+
private readonly enc;
|
|
22
|
+
private readonly l1;
|
|
23
|
+
private readonly disk;
|
|
24
|
+
private readonly opts;
|
|
25
|
+
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
26
|
+
private readonly _namespace;
|
|
27
|
+
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
28
|
+
private readonly _redisDisabled;
|
|
29
|
+
private readonly inflight;
|
|
30
|
+
private readonly revalidating;
|
|
31
|
+
private readonly _l1Counters;
|
|
32
|
+
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
33
|
+
private readonly tagIndex;
|
|
34
|
+
/**
|
|
35
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
36
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
37
|
+
*/
|
|
38
|
+
private readonly dependencyIndex;
|
|
39
|
+
private redis;
|
|
40
|
+
private redisConnecting;
|
|
41
|
+
private readonly cb;
|
|
42
|
+
private snapshotLoaded;
|
|
43
|
+
private _readyPromise;
|
|
44
|
+
private cleanupInterval;
|
|
45
|
+
private diskJanitorInterval;
|
|
46
|
+
private oomInterval;
|
|
47
|
+
private metricsInterval;
|
|
48
|
+
private _shutdownHandler;
|
|
49
|
+
private latencyTracker;
|
|
50
|
+
private readonly instanceId;
|
|
51
|
+
private readonly backplaneChannel;
|
|
52
|
+
private subClient;
|
|
53
|
+
private readonly counters;
|
|
54
|
+
constructor(options?: CacheOptions);
|
|
55
|
+
/**
|
|
56
|
+
* Get (or create) the process-level singleton CacheService instance.
|
|
57
|
+
*
|
|
58
|
+
* Options are only applied on first call — subsequent calls return the
|
|
59
|
+
* existing instance regardless of options passed.
|
|
60
|
+
*
|
|
61
|
+
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
62
|
+
* with different namespaces return independent instances.
|
|
63
|
+
*/
|
|
64
|
+
static create(options?: CacheOptions): CacheService;
|
|
65
|
+
/**
|
|
66
|
+
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
67
|
+
* Useful when config is fetched from a secret store at startup.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
71
|
+
*/
|
|
72
|
+
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
73
|
+
/** Replace the singleton (useful in tests). */
|
|
74
|
+
static reset(options?: CacheOptions): CacheService;
|
|
75
|
+
/** Derive the globalThis key for a given set of options. */
|
|
76
|
+
private static globalKey;
|
|
77
|
+
/**
|
|
78
|
+
* Prepend the configured namespace to a raw cache key.
|
|
79
|
+
* Returns the key unchanged when namespace is empty.
|
|
80
|
+
*
|
|
81
|
+
* This is the only place the namespace prefix is applied — callers always
|
|
82
|
+
* receive and provide un-prefixed keys in the public API.
|
|
83
|
+
*/
|
|
84
|
+
private nk;
|
|
85
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
86
|
+
private _jitterTtl;
|
|
87
|
+
/** Shared no-op span for the common case where no tracer is configured.
|
|
88
|
+
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
89
|
+
private static readonly _nullSpan;
|
|
90
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
91
|
+
private _startSpan;
|
|
92
|
+
private initBackplane;
|
|
93
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
94
|
+
_handleBackplaneMessage(message: string): void;
|
|
95
|
+
private publishInvalidation;
|
|
96
|
+
private getRedis;
|
|
97
|
+
writeSnapshot(altPath?: string): void;
|
|
98
|
+
loadSnapshot(): void;
|
|
99
|
+
/**
|
|
100
|
+
* Get a value from cache, or fetch and cache it.
|
|
101
|
+
*
|
|
102
|
+
* @param cacheKey - Unique key identifying this value
|
|
103
|
+
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
104
|
+
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
105
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
106
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
107
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
108
|
+
* is triggered proactively while the caller still receives the
|
|
109
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
110
|
+
* Requires `fetchFn` to be stable across calls.
|
|
111
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
112
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
113
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
114
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
115
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
116
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
117
|
+
*/
|
|
118
|
+
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
119
|
+
priority?: CachePriority;
|
|
120
|
+
swr?: number;
|
|
121
|
+
refreshAhead?: number;
|
|
122
|
+
xfetchBeta?: number;
|
|
123
|
+
notFoundTtl?: number;
|
|
124
|
+
/**
|
|
125
|
+
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
126
|
+
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
127
|
+
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
128
|
+
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
129
|
+
*/
|
|
130
|
+
tags?: string[];
|
|
131
|
+
}): Promise<T>;
|
|
132
|
+
private _revalidate;
|
|
133
|
+
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
134
|
+
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
135
|
+
tags?: string[];
|
|
136
|
+
dependsOn?: string[];
|
|
137
|
+
}): Promise<void>;
|
|
138
|
+
/**
|
|
139
|
+
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
140
|
+
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
141
|
+
*/
|
|
142
|
+
private _registerTags;
|
|
143
|
+
/**
|
|
144
|
+
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* await cache.delete('user:abc:profile'); // exact key
|
|
148
|
+
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
149
|
+
*/
|
|
150
|
+
delete(cacheKey: string): Promise<void>;
|
|
151
|
+
/**
|
|
152
|
+
* Atomically increment a counter in Redis. Returns the new value.
|
|
153
|
+
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
154
|
+
*/
|
|
155
|
+
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
156
|
+
/**
|
|
157
|
+
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* await cache.clear(); // flush everything
|
|
161
|
+
* await cache.clear('user:abc'); // flush all keys for one user
|
|
162
|
+
*/
|
|
163
|
+
clear(prefix?: string): Promise<void>;
|
|
164
|
+
/**
|
|
165
|
+
* Evict L1 entries that violate the current category or global capacity limits.
|
|
166
|
+
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
167
|
+
* Returns the number of entries evicted.
|
|
168
|
+
*/
|
|
169
|
+
rebalance(): number;
|
|
170
|
+
/**
|
|
171
|
+
* Return the remaining TTL in seconds for a key currently in L1.
|
|
172
|
+
* Returns null if the key is absent from L1 or has already expired.
|
|
173
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
174
|
+
*/
|
|
175
|
+
ttl(cacheKey: string): number | null;
|
|
176
|
+
/**
|
|
177
|
+
* Return true if the key exists in L1 and has not expired.
|
|
178
|
+
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
179
|
+
*/
|
|
180
|
+
has(cacheKey: string): boolean;
|
|
181
|
+
/**
|
|
182
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* for (const key of cache.keys()) console.log(key);
|
|
186
|
+
*/
|
|
187
|
+
keys(): Generator<string>;
|
|
188
|
+
/**
|
|
189
|
+
* Lazily yield every non-expired L1 value.
|
|
190
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
194
|
+
*/
|
|
195
|
+
values<T = unknown>(): Generator<T>;
|
|
196
|
+
/**
|
|
197
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
198
|
+
* Keys are stripped of their namespace prefix.
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
202
|
+
*/
|
|
203
|
+
entries<T = unknown>(): Generator<[string, T]>;
|
|
204
|
+
/**
|
|
205
|
+
* High-throughput bulk scan over all live L1 entries.
|
|
206
|
+
*
|
|
207
|
+
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
208
|
+
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
209
|
+
* caller uses the `offset` parameter instead of pre-slicing.
|
|
210
|
+
*
|
|
211
|
+
* ```typescript
|
|
212
|
+
* // Zero extra string allocations — use rawKey + offset directly:
|
|
213
|
+
* cache.scan((rawKey, value, offset) => {
|
|
214
|
+
* const key = rawKey.slice(offset); // allocate only if needed
|
|
215
|
+
* sync(key, value as User);
|
|
216
|
+
* });
|
|
217
|
+
* ```
|
|
218
|
+
*
|
|
219
|
+
* @param fn Called once per live L1 entry.
|
|
220
|
+
* `rawKey` — key with namespace prefix still attached.
|
|
221
|
+
* `value` — deserialized cached value.
|
|
222
|
+
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
223
|
+
*/
|
|
224
|
+
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
|
|
225
|
+
/**
|
|
226
|
+
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
227
|
+
* Returns `false` if the key is absent or already expired.
|
|
228
|
+
*
|
|
229
|
+
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
230
|
+
*/
|
|
231
|
+
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
232
|
+
/**
|
|
233
|
+
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
234
|
+
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* const fresh = cache.getIfFresh('user:123');
|
|
238
|
+
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
239
|
+
*/
|
|
240
|
+
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
241
|
+
/**
|
|
242
|
+
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
243
|
+
* Preserves input ordering. Uses inflight coalescing per key.
|
|
244
|
+
*
|
|
245
|
+
* @param keys - Array of cache keys.
|
|
246
|
+
* @param fetchFn - Called with only the keys that missed L1.
|
|
247
|
+
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
248
|
+
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
249
|
+
*/
|
|
250
|
+
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
251
|
+
/**
|
|
252
|
+
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
253
|
+
* startup warming configured via `warmKeys` has completed.
|
|
254
|
+
*
|
|
255
|
+
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
256
|
+
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
260
|
+
* await cache.ready(); // gate traffic until warm
|
|
261
|
+
*/
|
|
262
|
+
ready(): Promise<void>;
|
|
263
|
+
/**
|
|
264
|
+
* Batch write — set multiple entries in a single call.
|
|
265
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* await cache.mset({
|
|
269
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
270
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
271
|
+
* });
|
|
272
|
+
*/
|
|
273
|
+
mset<T = unknown>(entries: Record<string, {
|
|
274
|
+
value: T;
|
|
275
|
+
ttl?: number;
|
|
276
|
+
priority?: CachePriority;
|
|
277
|
+
tags?: string[];
|
|
278
|
+
dependsOn?: string[];
|
|
279
|
+
}>): Promise<void>;
|
|
280
|
+
/**
|
|
281
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
282
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
286
|
+
*/
|
|
287
|
+
mdel(keys: string[]): Promise<void>;
|
|
288
|
+
/**
|
|
289
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
290
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
291
|
+
* the local snapshot is unavailable or too stale.
|
|
292
|
+
*
|
|
293
|
+
* Returns the number of keys loaded into L1.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
297
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
298
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
299
|
+
*/
|
|
300
|
+
warmFromL2(pattern: string, opts?: {
|
|
301
|
+
priority?: CachePriority;
|
|
302
|
+
}): Promise<number>;
|
|
303
|
+
/**
|
|
304
|
+
* Invalidate all keys associated with a tag.
|
|
305
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
309
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
310
|
+
*/
|
|
311
|
+
invalidateTag(tag: string): Promise<void>;
|
|
312
|
+
/**
|
|
313
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
314
|
+
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
315
|
+
* reducing latency when invalidating several related tags together.
|
|
316
|
+
*
|
|
317
|
+
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
318
|
+
* synchronously before the Redis round-trip.
|
|
319
|
+
*
|
|
320
|
+
* @example
|
|
321
|
+
* // Instead of three serial round-trips:
|
|
322
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
323
|
+
*/
|
|
324
|
+
invalidateTags(tags: string[]): Promise<void>;
|
|
325
|
+
/**
|
|
326
|
+
* Measure L1 / disk / Redis latency.
|
|
327
|
+
* Useful for health checks and dashboards.
|
|
328
|
+
*
|
|
329
|
+
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
330
|
+
* `l2` is `null` when Redis is disabled.
|
|
331
|
+
*/
|
|
332
|
+
ping(): Promise<CachePingResult>;
|
|
333
|
+
/**
|
|
334
|
+
* Export all live L1 entries to Redis via a single pipeline.
|
|
335
|
+
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
336
|
+
* Returns the number of keys written.
|
|
337
|
+
*/
|
|
338
|
+
drainToL2(): Promise<number>;
|
|
339
|
+
stats(): {
|
|
340
|
+
l1: {
|
|
341
|
+
entries: number;
|
|
342
|
+
sizeBytes: number;
|
|
343
|
+
sizeKB: number;
|
|
344
|
+
categories: Record<string, {
|
|
345
|
+
entries: number;
|
|
346
|
+
hits: number;
|
|
347
|
+
}>;
|
|
348
|
+
bloom: {
|
|
349
|
+
checks: number;
|
|
350
|
+
falsePositives: number;
|
|
351
|
+
};
|
|
352
|
+
compression: {
|
|
353
|
+
compressed: number;
|
|
354
|
+
uncompressed: number;
|
|
355
|
+
bytesSaved: number;
|
|
356
|
+
};
|
|
357
|
+
};
|
|
358
|
+
disk: {
|
|
359
|
+
files: number;
|
|
360
|
+
sizeKB: number;
|
|
361
|
+
maxKB: number;
|
|
362
|
+
};
|
|
363
|
+
};
|
|
364
|
+
/**
|
|
365
|
+
* Write `value` only if the key is not already cached.
|
|
366
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
367
|
+
*
|
|
368
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
369
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
370
|
+
* multiple instances. L1 is populated on success.
|
|
371
|
+
*
|
|
372
|
+
* @example
|
|
373
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
374
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
375
|
+
*/
|
|
376
|
+
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
377
|
+
/**
|
|
378
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
379
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
380
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
381
|
+
*
|
|
382
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
383
|
+
* collection overhead.
|
|
384
|
+
*
|
|
385
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
386
|
+
*
|
|
387
|
+
* @example
|
|
388
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
389
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
390
|
+
*/
|
|
391
|
+
hotKeys(n?: number): Array<{
|
|
392
|
+
key: string;
|
|
393
|
+
hits: number;
|
|
394
|
+
sizeBytes: number;
|
|
395
|
+
}>;
|
|
396
|
+
/**
|
|
397
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
398
|
+
* pattern that may contain `*` wildcards).
|
|
399
|
+
*/
|
|
400
|
+
private _matchesGlob;
|
|
401
|
+
/**
|
|
402
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
403
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
404
|
+
*/
|
|
405
|
+
private _cascadeDependencies;
|
|
406
|
+
/** Return a full metrics snapshot. */
|
|
407
|
+
metrics(): CacheMetrics;
|
|
408
|
+
/**
|
|
409
|
+
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
410
|
+
* Paste the result into your `/metrics` endpoint.
|
|
411
|
+
*
|
|
412
|
+
* @param m - Snapshot returned by `cache.metrics()`
|
|
413
|
+
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
414
|
+
*/
|
|
415
|
+
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
416
|
+
/** Close Redis connections and stop all background timers. */
|
|
417
|
+
destroy(): Promise<void>;
|
|
418
|
+
}
|
|
419
|
+
//# sourceMappingURL=cache-service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-service.d.ts","sourceRoot":"","sources":["../src/cache-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAWH,OAAO,EACL,aAAa,EAIb,YAAY,EACZ,YAAY,EACZ,eAAe,EAKhB,MAAM,SAAS,CAAC;AA6NjB,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAyB;IAC7C,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA2B;IAC9C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiB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