tricache 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/index.cjs +518 -112
- package/dist/index.d.cts +152 -8
- package/dist/index.d.ts +1310 -18
- package/dist/index.js +3131 -25
- package/package.json +11 -10
- package/src/cache-service.ts +197 -44
- package/src/disk-tier.ts +263 -25
- package/src/encryption.ts +14 -12
- package/src/smart-memory-cache.ts +152 -13
- package/src/types.ts +37 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
- package/dist/cache-service.d.ts +0 -366
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1494
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -83
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -324
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -88
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -371
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -178
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -753
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -428
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -99
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
package/src/types.ts
CHANGED
|
@@ -119,6 +119,9 @@ export interface CacheHit {
|
|
|
119
119
|
ttlMs?: number;
|
|
120
120
|
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
121
121
|
delta?: number;
|
|
122
|
+
/** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
|
|
123
|
+
* reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
|
|
124
|
+
fetchedAt?: number;
|
|
122
125
|
}
|
|
123
126
|
|
|
124
127
|
// ─── Disk tier ───────────────────────────────────────────────────────────────
|
|
@@ -478,4 +481,38 @@ export interface CacheOptions {
|
|
|
478
481
|
* No-op when Redis is disabled or unreachable — safe to set unconditionally.
|
|
479
482
|
*/
|
|
480
483
|
warmKeys?: string;
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
|
|
487
|
+
* namespace prefix) and the tier that served it. Useful for per-route hit-rate
|
|
488
|
+
* metrics without waiting for the `onMetrics` interval.
|
|
489
|
+
*
|
|
490
|
+
* @example
|
|
491
|
+
* onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
|
|
492
|
+
*/
|
|
493
|
+
onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Called on every cache miss (after L1, disk, and L2 are all exhausted).
|
|
497
|
+
* Receives the caller-facing key (no namespace prefix).
|
|
498
|
+
*
|
|
499
|
+
* @example
|
|
500
|
+
* onMiss: (key) => cloudwatch.putMetricData({ key })
|
|
501
|
+
*/
|
|
502
|
+
onMiss?: (key: string) => void;
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* When `true`, every value returned from an L1 cache hit is recursively
|
|
506
|
+
* frozen with `Object.freeze()` before being handed to the caller.
|
|
507
|
+
* Any attempt to mutate the returned object throws a `TypeError` immediately,
|
|
508
|
+
* catching reference-semantic corruption bugs that would otherwise silently
|
|
509
|
+
* corrupt the cached entry.
|
|
510
|
+
*
|
|
511
|
+
* **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
|
|
512
|
+
* Deep-freezing large objects has measurable overhead per hit.
|
|
513
|
+
*
|
|
514
|
+
* @example
|
|
515
|
+
* frozen: process.env.NODE_ENV !== 'production'
|
|
516
|
+
*/
|
|
517
|
+
frozen?: boolean;
|
|
481
518
|
}
|
|
@@ -38,11 +38,7 @@ interface BloomWasmExports {
|
|
|
38
38
|
countBits(): number;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, 'base64');
|
|
43
|
-
const compiled = new WebAssembly.Module(wasmBytes);
|
|
44
|
-
return new WebAssembly.Instance(compiled, {});
|
|
45
|
-
}
|
|
41
|
+
const BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, 'base64'));
|
|
46
42
|
|
|
47
43
|
export class WasmBloomFilter {
|
|
48
44
|
private readonly exports: BloomWasmExports;
|
|
@@ -55,7 +51,7 @@ export class WasmBloomFilter {
|
|
|
55
51
|
private _insertionCount = 0;
|
|
56
52
|
|
|
57
53
|
constructor() {
|
|
58
|
-
const instance =
|
|
54
|
+
const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
|
|
59
55
|
this.exports = instance.exports as unknown as BloomWasmExports;
|
|
60
56
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
61
57
|
const k = 7, p = 0.01;
|
|
@@ -63,21 +59,9 @@ export class WasmBloomFilter {
|
|
|
63
59
|
}
|
|
64
60
|
|
|
65
61
|
private writeKey(key: string): number {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
// On the first non-ASCII char, fall back to TextEncoder for correct multi-byte encoding.
|
|
70
|
-
for (let i = 0; i < max; i++) {
|
|
71
|
-
const c = key.charCodeAt(i);
|
|
72
|
-
if (c > 127) {
|
|
73
|
-
const encoded = this.encoder.encode(key);
|
|
74
|
-
const len = Math.min(encoded.length, MAX_KEY_BYTES);
|
|
75
|
-
this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
|
|
76
|
-
return len;
|
|
77
|
-
}
|
|
78
|
-
this.mem[KEY_STAGING_OFFSET + i] = c;
|
|
79
|
-
}
|
|
80
|
-
return max;
|
|
62
|
+
if (key.length === 0) return 0;
|
|
63
|
+
const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
|
|
64
|
+
return this.encoder.encodeInto(key, target).written;
|
|
81
65
|
}
|
|
82
66
|
|
|
83
67
|
add(key: string): void {
|
package/dist/cache-service.d.ts
DELETED
|
@@ -1,366 +0,0 @@
|
|
|
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 oomInterval;
|
|
46
|
-
private metricsInterval;
|
|
47
|
-
private _shutdownHandler;
|
|
48
|
-
private readonly instanceId;
|
|
49
|
-
private readonly backplaneChannel;
|
|
50
|
-
private subClient;
|
|
51
|
-
private readonly counters;
|
|
52
|
-
constructor(options?: CacheOptions);
|
|
53
|
-
/**
|
|
54
|
-
* Get (or create) the process-level singleton CacheService instance.
|
|
55
|
-
*
|
|
56
|
-
* Options are only applied on first call — subsequent calls return the
|
|
57
|
-
* existing instance regardless of options passed.
|
|
58
|
-
*
|
|
59
|
-
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
60
|
-
* with different namespaces return independent instances.
|
|
61
|
-
*/
|
|
62
|
-
static create(options?: CacheOptions): CacheService;
|
|
63
|
-
/**
|
|
64
|
-
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
65
|
-
* Useful when config is fetched from a secret store at startup.
|
|
66
|
-
*
|
|
67
|
-
* @example
|
|
68
|
-
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
69
|
-
*/
|
|
70
|
-
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
71
|
-
/** Replace the singleton (useful in tests). */
|
|
72
|
-
static reset(options?: CacheOptions): CacheService;
|
|
73
|
-
/** Derive the globalThis key for a given set of options. */
|
|
74
|
-
private static globalKey;
|
|
75
|
-
/**
|
|
76
|
-
* Prepend the configured namespace to a raw cache key.
|
|
77
|
-
* Returns the key unchanged when namespace is empty.
|
|
78
|
-
*
|
|
79
|
-
* This is the only place the namespace prefix is applied — callers always
|
|
80
|
-
* receive and provide un-prefixed keys in the public API.
|
|
81
|
-
*/
|
|
82
|
-
private nk;
|
|
83
|
-
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
84
|
-
private _jitterTtl;
|
|
85
|
-
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
86
|
-
private _startSpan;
|
|
87
|
-
private initBackplane;
|
|
88
|
-
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
89
|
-
_handleBackplaneMessage(message: string): void;
|
|
90
|
-
private publishInvalidation;
|
|
91
|
-
private getRedis;
|
|
92
|
-
writeSnapshot(altPath?: string): void;
|
|
93
|
-
loadSnapshot(): void;
|
|
94
|
-
/**
|
|
95
|
-
* Get a value from cache, or fetch and cache it.
|
|
96
|
-
*
|
|
97
|
-
* @param cacheKey - Unique key identifying this value
|
|
98
|
-
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
99
|
-
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
100
|
-
* @param opts.priority - Override the auto-inferred eviction priority
|
|
101
|
-
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
102
|
-
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
103
|
-
* is triggered proactively while the caller still receives the
|
|
104
|
-
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
105
|
-
* Requires `fetchFn` to be stable across calls.
|
|
106
|
-
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
107
|
-
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
108
|
-
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
109
|
-
* decide probabilistically rather than at a fixed threshold.
|
|
110
|
-
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
111
|
-
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
112
|
-
*/
|
|
113
|
-
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
114
|
-
priority?: CachePriority;
|
|
115
|
-
swr?: number;
|
|
116
|
-
refreshAhead?: number;
|
|
117
|
-
xfetchBeta?: number;
|
|
118
|
-
notFoundTtl?: number;
|
|
119
|
-
}): Promise<T>;
|
|
120
|
-
private _revalidate;
|
|
121
|
-
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
122
|
-
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
123
|
-
tags?: string[];
|
|
124
|
-
dependsOn?: string[];
|
|
125
|
-
}): Promise<void>;
|
|
126
|
-
/**
|
|
127
|
-
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* await cache.delete('user:abc:profile'); // exact key
|
|
131
|
-
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
132
|
-
*/
|
|
133
|
-
delete(cacheKey: string): Promise<void>;
|
|
134
|
-
/**
|
|
135
|
-
* Atomically increment a counter in Redis. Returns the new value.
|
|
136
|
-
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
137
|
-
*/
|
|
138
|
-
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
139
|
-
/**
|
|
140
|
-
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
141
|
-
*
|
|
142
|
-
* @example
|
|
143
|
-
* await cache.clear(); // flush everything
|
|
144
|
-
* await cache.clear('user:abc'); // flush all keys for one user
|
|
145
|
-
*/
|
|
146
|
-
clear(prefix?: string): Promise<void>;
|
|
147
|
-
/**
|
|
148
|
-
* Evict L1 entries that violate the current category or global capacity limits.
|
|
149
|
-
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
150
|
-
* Returns the number of entries evicted.
|
|
151
|
-
*/
|
|
152
|
-
rebalance(): number;
|
|
153
|
-
/**
|
|
154
|
-
* Return the remaining TTL in seconds for a key currently in L1.
|
|
155
|
-
* Returns null if the key is absent from L1 or has already expired.
|
|
156
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
157
|
-
*/
|
|
158
|
-
ttl(cacheKey: string): number | null;
|
|
159
|
-
/**
|
|
160
|
-
* Return true if the key exists in L1 and has not expired.
|
|
161
|
-
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
162
|
-
*/
|
|
163
|
-
has(cacheKey: string): boolean;
|
|
164
|
-
/**
|
|
165
|
-
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
166
|
-
*
|
|
167
|
-
* @example
|
|
168
|
-
* for (const key of cache.keys()) console.log(key);
|
|
169
|
-
*/
|
|
170
|
-
keys(): Generator<string>;
|
|
171
|
-
/**
|
|
172
|
-
* Lazily yield every non-expired L1 value.
|
|
173
|
-
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
174
|
-
*
|
|
175
|
-
* @example
|
|
176
|
-
* for (const val of cache.values<User>()) console.log(val.id);
|
|
177
|
-
*/
|
|
178
|
-
values<T = unknown>(): Generator<T>;
|
|
179
|
-
/**
|
|
180
|
-
* Lazily yield every non-expired L1 [key, value] pair.
|
|
181
|
-
* Keys are stripped of their namespace prefix.
|
|
182
|
-
*
|
|
183
|
-
* @example
|
|
184
|
-
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
185
|
-
*/
|
|
186
|
-
entries<T = unknown>(): Generator<[string, T]>;
|
|
187
|
-
/**
|
|
188
|
-
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
189
|
-
* Returns `false` if the key is absent or already expired.
|
|
190
|
-
*
|
|
191
|
-
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
192
|
-
*/
|
|
193
|
-
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
194
|
-
/**
|
|
195
|
-
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
196
|
-
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
197
|
-
*
|
|
198
|
-
* @example
|
|
199
|
-
* const fresh = cache.getIfFresh('user:123');
|
|
200
|
-
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
201
|
-
*/
|
|
202
|
-
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
203
|
-
/**
|
|
204
|
-
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
205
|
-
* Preserves input ordering. Uses inflight coalescing per key.
|
|
206
|
-
*
|
|
207
|
-
* @param keys - Array of cache keys.
|
|
208
|
-
* @param fetchFn - Called with only the keys that missed L1.
|
|
209
|
-
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
210
|
-
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
211
|
-
*/
|
|
212
|
-
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
213
|
-
/**
|
|
214
|
-
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
215
|
-
* startup warming configured via `warmKeys` has completed.
|
|
216
|
-
*
|
|
217
|
-
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
218
|
-
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
219
|
-
*
|
|
220
|
-
* @example
|
|
221
|
-
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
222
|
-
* await cache.ready(); // gate traffic until warm
|
|
223
|
-
*/
|
|
224
|
-
ready(): Promise<void>;
|
|
225
|
-
/**
|
|
226
|
-
* Batch write — set multiple entries in a single call.
|
|
227
|
-
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
228
|
-
*
|
|
229
|
-
* @example
|
|
230
|
-
* await cache.mset({
|
|
231
|
-
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
232
|
-
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
233
|
-
* });
|
|
234
|
-
*/
|
|
235
|
-
mset<T = unknown>(entries: Record<string, {
|
|
236
|
-
value: T;
|
|
237
|
-
ttl?: number;
|
|
238
|
-
priority?: CachePriority;
|
|
239
|
-
tags?: string[];
|
|
240
|
-
dependsOn?: string[];
|
|
241
|
-
}>): Promise<void>;
|
|
242
|
-
/**
|
|
243
|
-
* Batch delete — delete multiple exact keys in a single call.
|
|
244
|
-
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
245
|
-
*
|
|
246
|
-
* @example
|
|
247
|
-
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
248
|
-
*/
|
|
249
|
-
mdel(keys: string[]): Promise<void>;
|
|
250
|
-
/**
|
|
251
|
-
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
252
|
-
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
253
|
-
* the local snapshot is unavailable or too stale.
|
|
254
|
-
*
|
|
255
|
-
* Returns the number of keys loaded into L1.
|
|
256
|
-
*
|
|
257
|
-
* @example
|
|
258
|
-
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
259
|
-
* const loaded = await cache.warmFromL2('org:*');
|
|
260
|
-
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
261
|
-
*/
|
|
262
|
-
warmFromL2(pattern: string): Promise<number>;
|
|
263
|
-
/**
|
|
264
|
-
* Invalidate all keys associated with a tag.
|
|
265
|
-
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
266
|
-
*
|
|
267
|
-
* @example
|
|
268
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
269
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
270
|
-
*/
|
|
271
|
-
invalidateTag(tag: string): Promise<void>;
|
|
272
|
-
/**
|
|
273
|
-
* Measure L1 / disk / Redis latency.
|
|
274
|
-
* Useful for health checks and dashboards.
|
|
275
|
-
*
|
|
276
|
-
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
277
|
-
* `l2` is `null` when Redis is disabled.
|
|
278
|
-
*/
|
|
279
|
-
ping(): Promise<CachePingResult>;
|
|
280
|
-
/**
|
|
281
|
-
* Export all live L1 entries to Redis via a single pipeline.
|
|
282
|
-
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
283
|
-
* Returns the number of keys written.
|
|
284
|
-
*/
|
|
285
|
-
drainToL2(): Promise<number>;
|
|
286
|
-
stats(): {
|
|
287
|
-
l1: {
|
|
288
|
-
entries: number;
|
|
289
|
-
sizeBytes: number;
|
|
290
|
-
sizeKB: number;
|
|
291
|
-
categories: Record<string, {
|
|
292
|
-
entries: number;
|
|
293
|
-
hits: number;
|
|
294
|
-
}>;
|
|
295
|
-
bloom: {
|
|
296
|
-
checks: number;
|
|
297
|
-
falsePositives: number;
|
|
298
|
-
};
|
|
299
|
-
compression: {
|
|
300
|
-
compressed: number;
|
|
301
|
-
uncompressed: number;
|
|
302
|
-
bytesSaved: number;
|
|
303
|
-
};
|
|
304
|
-
};
|
|
305
|
-
disk: {
|
|
306
|
-
files: number;
|
|
307
|
-
sizeKB: number;
|
|
308
|
-
maxKB: number;
|
|
309
|
-
};
|
|
310
|
-
};
|
|
311
|
-
/**
|
|
312
|
-
* Write `value` only if the key is not already cached.
|
|
313
|
-
* Returns `true` if the write happened, `false` if the key already existed.
|
|
314
|
-
*
|
|
315
|
-
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
316
|
-
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
317
|
-
* multiple instances. L1 is populated on success.
|
|
318
|
-
*
|
|
319
|
-
* @example
|
|
320
|
-
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
321
|
-
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
322
|
-
*/
|
|
323
|
-
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
324
|
-
/**
|
|
325
|
-
* Return the top-N live L1 keys by historical access frequency.
|
|
326
|
-
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
327
|
-
* whose historical frequency exceeds their current in-memory hit count.
|
|
328
|
-
*
|
|
329
|
-
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
330
|
-
* collection overhead.
|
|
331
|
-
*
|
|
332
|
-
* @param n - Maximum number of keys to return. Default: 10.
|
|
333
|
-
*
|
|
334
|
-
* @example
|
|
335
|
-
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
336
|
-
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
337
|
-
*/
|
|
338
|
-
hotKeys(n?: number): Array<{
|
|
339
|
-
key: string;
|
|
340
|
-
hits: number;
|
|
341
|
-
sizeBytes: number;
|
|
342
|
-
}>;
|
|
343
|
-
/**
|
|
344
|
-
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
345
|
-
* pattern that may contain `*` wildcards).
|
|
346
|
-
*/
|
|
347
|
-
private _matchesGlob;
|
|
348
|
-
/**
|
|
349
|
-
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
350
|
-
* that was registered via `dependsOn` and whose source pattern matches.
|
|
351
|
-
*/
|
|
352
|
-
private _cascadeDependencies;
|
|
353
|
-
/** Return a full metrics snapshot. */
|
|
354
|
-
metrics(): CacheMetrics;
|
|
355
|
-
/**
|
|
356
|
-
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
357
|
-
* Paste the result into your `/metrics` endpoint.
|
|
358
|
-
*
|
|
359
|
-
* @param m - Snapshot returned by `cache.metrics()`
|
|
360
|
-
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
361
|
-
*/
|
|
362
|
-
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
363
|
-
/** Close Redis connections and stop all background timers. */
|
|
364
|
-
destroy(): Promise<void>;
|
|
365
|
-
}
|
|
366
|
-
//# sourceMappingURL=cache-service.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cache-service.d.ts","sourceRoot":"","sources":["../src/cache-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAUH,OAAO,EACL,aAAa,EAIb,YAAY,EACZ,YAAY,EACZ,eAAe,EAKhB,MAAM,SAAS,CAAC;AA0FjB,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;IACtC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAoBnB;IACF,2EAA2E;IAC3E,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAc;IACzC,sFAAsF;IACtF,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAW;IAC1C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA0C;IACnE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAqB;IAClD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA2D;IACvF,yFAAyF;IACzF,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqC;IAC9D;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAkC;IAClE,OAAO,CAAC,KAAK,CAA0C;IACvD,OAAO,CAAC,eAAe,CAAyC;IAChE,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA2B;IAC9C,OAAO,CAAC,cAAc,CAAe;IACrC,OAAO,CAAC,aAAa,CAA0C;IAC/D,OAAO,CAAC,eAAe,CAAmD;IAC1E,OAAO,C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