tricache 0.4.0 → 0.5.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 +63 -27
- package/dist/cache-service.d.ts +366 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1494 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +83 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +324 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +88 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +371 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +51 -23
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +18 -1146
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -2697
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +178 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +753 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +428 -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 +99 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +10 -11
- package/src/cache-service.ts +36 -4
- package/src/smart-memory-cache.ts +36 -27
- package/src/types.ts +6 -0
package/README.md
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
[](https://nodejs.org)
|
|
8
8
|
[](https://www.typescriptlang.org)
|
|
9
|
-
[](BENCHMARKS.md)
|
|
10
10
|
[](BENCHMARKS.md)
|
|
11
11
|
|
|
12
|
-
tricache is an extremely fast three-tier Node.js cache library. It serves warm reads at **2.
|
|
12
|
+
tricache is an extremely fast three-tier Node.js cache library. It serves warm reads at **2.81 million operations per second** from a single thread — over 100× faster than a localhost Redis round-trip and below any network latency floor. When L1 fills, evicted entries spill to a local NVMe disk tier rather than being dropped, keeping hit rates high without unbounded RAM growth. Cache misses that reach L2 (Redis or Valkey) are automatically coalesced: no matter how many concurrent callers miss the same key, `fetchFn` fires exactly once. See the [performance section](#-performance) for full numbers. Stale-While-Revalidate, AES-256-GCM at-rest encryption, pub/sub fleet-wide invalidation, OOM guard, cold-start snapshots, and Prometheus metrics are also supported through optional configuration — with zero required fields to get started.
|
|
13
13
|
|
|
14
14
|
<img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
|
|
15
15
|
|
|
@@ -121,6 +121,10 @@ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
|
|
|
121
121
|
const loaded = await cache.warmFromL2('user:*');
|
|
122
122
|
console.log(`Pre-warmed ${loaded} user entries`);
|
|
123
123
|
|
|
124
|
+
// Or auto-warm at construction + gate traffic with ready()
|
|
125
|
+
const cache2 = CacheService.create({ warmKeys: 'user:*' });
|
|
126
|
+
await cache2.ready(); // resolves once warm-up completes — ideal for k8s readiness probes
|
|
127
|
+
|
|
124
128
|
// Atomic set-if-absent — returns true if written, false if key already cached
|
|
125
129
|
const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
|
|
126
130
|
|
|
@@ -240,6 +244,12 @@ CacheService.create({
|
|
|
240
244
|
// Can be overridden per-call via opts.notFoundTtl in cache.get().
|
|
241
245
|
notFoundTtl: 30, // seconds; 0 = disabled (default)
|
|
242
246
|
|
|
247
|
+
// ── Startup warm-up ───────────────────────────────────────────────────
|
|
248
|
+
// Auto-call warmFromL2(pattern) at construction time.
|
|
249
|
+
// cache.ready() resolves once warm-up finishes — use as a k8s readiness gate.
|
|
250
|
+
// No-op when Redis is disabled or unreachable.
|
|
251
|
+
warmKeys: 'user:*',
|
|
252
|
+
|
|
243
253
|
// ── Prometheus instance label ─────────────────────────────────────────
|
|
244
254
|
// Adds an `instance` label to every metric in toPrometheusText().
|
|
245
255
|
instanceName: 'api-us-east-1',
|
|
@@ -317,16 +327,26 @@ await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42
|
|
|
317
327
|
await cache.delete('org:42'); // org:42:members is evicted too
|
|
318
328
|
```
|
|
319
329
|
|
|
320
|
-
### `cache.mget<T>(keys, fetchFn,
|
|
330
|
+
### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
|
|
321
331
|
|
|
322
332
|
Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
|
|
323
333
|
|
|
334
|
+
`ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
|
|
335
|
+
|
|
324
336
|
```typescript
|
|
337
|
+
// Uniform TTL
|
|
325
338
|
const [userA, userB] = await cache.mget(
|
|
326
339
|
['user:1', 'user:2'],
|
|
327
340
|
(missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
|
|
328
341
|
300,
|
|
329
342
|
);
|
|
343
|
+
|
|
344
|
+
// Per-key TTL — heterogeneous data in one batch call
|
|
345
|
+
const results = await cache.mget(
|
|
346
|
+
['user:1', 'config:global', 'feature:flags'],
|
|
347
|
+
fetchFn,
|
|
348
|
+
(key) => key.startsWith('config:') ? 3600 : 300,
|
|
349
|
+
);
|
|
330
350
|
```
|
|
331
351
|
|
|
332
352
|
### `cache.mset<T>(entries)` → `Promise<void>`
|
|
@@ -358,6 +378,22 @@ const loaded = await cache.warmFromL2('user:*');
|
|
|
358
378
|
console.log(`Pre-warmed ${loaded} user entries from Redis`);
|
|
359
379
|
```
|
|
360
380
|
|
|
381
|
+
### `cache.ready()` → `Promise<void>`
|
|
382
|
+
|
|
383
|
+
Returns a Promise that resolves once the cache is fully initialised. Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once the automatic `warmFromL2` call completes.
|
|
384
|
+
|
|
385
|
+
Designed for k8s readiness probes — await before accepting traffic, then never call again:
|
|
386
|
+
|
|
387
|
+
```typescript
|
|
388
|
+
const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
389
|
+
|
|
390
|
+
// k8s readiness probe endpoint
|
|
391
|
+
app.get('/ready', async (_req, res) => {
|
|
392
|
+
await cache.ready();
|
|
393
|
+
res.sendStatus(200);
|
|
394
|
+
});
|
|
395
|
+
```
|
|
396
|
+
|
|
361
397
|
### `cache.has(key)` → `boolean`
|
|
362
398
|
|
|
363
399
|
Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
|
|
@@ -669,52 +705,52 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
|
|
|
669
705
|
|
|
670
706
|
| Operation | Throughput | Latency | Notes |
|
|
671
707
|
|---|---|---|---|
|
|
672
|
-
| `get` — hot hit (8K entries) | **2.
|
|
673
|
-
| `get` — cold miss | **7.
|
|
708
|
+
| `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
|
|
709
|
+
| `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
|
|
674
710
|
| `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
|
|
675
711
|
| `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
|
|
676
712
|
| `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
|
|
677
713
|
| `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
|
|
678
|
-
| `delete` — exact key | **
|
|
714
|
+
| `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
|
|
679
715
|
| `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
|
|
680
|
-
| Count-Min Sketch estimate | **
|
|
716
|
+
| Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
|
|
681
717
|
|
|
682
718
|
**Iterator interface (L1 live entries, 500 entries)**
|
|
683
719
|
|
|
684
720
|
| Method | Throughput | Latency | Notes |
|
|
685
721
|
|---|---|---|---|
|
|
686
|
-
| `cache.keys()` |
|
|
687
|
-
| `cache.values()` |
|
|
688
|
-
| `cache.entries()` | 24.
|
|
689
|
-
| raw `Map` iteration (baseline) |
|
|
722
|
+
| `cache.keys()` | 26.6 K/s | 37.53 µs | no `[key,entry]` tuple allocation |
|
|
723
|
+
| `cache.values()` | 35.5 K/s | 28.19 µs | `yield*` delegation |
|
|
724
|
+
| `cache.entries()` | 24.0 K/s | 41.73 µs | `[strippedKey, value]` pairs |
|
|
725
|
+
| raw `Map` iteration (baseline) | 277.2 K/s | 3.61 µs | no expiry check, no generator overhead |
|
|
690
726
|
|
|
691
727
|
**CacheService (end-to-end)**
|
|
692
728
|
|
|
693
729
|
| Operation | Throughput | Latency | Notes |
|
|
694
730
|
|---|---|---|---|
|
|
695
|
-
| `get` — L1 warm hit | **
|
|
696
|
-
| `get` — SWR stale serve | **
|
|
731
|
+
| `get` — L1 warm hit | **2.03 M/s** | 491 ns | inflight check → l1.get → return cached value |
|
|
732
|
+
| `get` — SWR stale serve | **1.78 M/s** | 562 ns | serves stale; revalidates async |
|
|
697
733
|
| `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
|
|
698
|
-
| `set` |
|
|
699
|
-
| `delete` — exact key | 7.
|
|
734
|
+
| `set` | 28.7 K/s | 34.86 µs | l1.set + disk.save (fire-and-forget) |
|
|
735
|
+
| `delete` — exact key | 7.3 K/s | 137.82 µs | l1.delete + disk.delete + backplane |
|
|
700
736
|
| `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
|
|
701
737
|
|
|
702
738
|
**Encryption** (IV pool, pre-allocated output buffers)
|
|
703
739
|
|
|
704
740
|
| Mode | Payload | Encrypt | Decrypt |
|
|
705
741
|
|---|---|---|---|
|
|
706
|
-
| AES-256-GCM | 64 B |
|
|
707
|
-
| AES-256-GCM | 512 B |
|
|
708
|
-
| AES-256-GCM | 4 KB |
|
|
709
|
-
| AES-128-GCM | 64 B |
|
|
710
|
-
| AES-128-GCM | 512 B |
|
|
711
|
-
| AES-128-GCM | 4 KB |
|
|
712
|
-
| AES-128-CTR | 64 B |
|
|
713
|
-
| AES-128-CTR | 512 B |
|
|
714
|
-
| AES-128-CTR | 4 KB |
|
|
715
|
-
| XOR _(obfuscation only)_ | 64 B | 2.
|
|
716
|
-
| XOR _(obfuscation only)_ | 512 B |
|
|
717
|
-
| XOR _(obfuscation only)_ | 4 KB |
|
|
742
|
+
| AES-256-GCM | 64 B | 140.4 K/s / 7.12 µs | 155.5 K/s / 6.43 µs |
|
|
743
|
+
| AES-256-GCM | 512 B | 103.1 K/s / 9.70 µs | 142.9 K/s / 6.99 µs |
|
|
744
|
+
| AES-256-GCM | 4 KB | 58.4 K/s / 17.12 µs | 48.0 K/s / 20.84 µs |
|
|
745
|
+
| AES-128-GCM | 64 B | 148.8 K/s / 6.72 µs | 173.0 K/s / 5.78 µs |
|
|
746
|
+
| AES-128-GCM | 512 B | 135.7 K/s / 7.37 µs | 158.8 K/s / 6.30 µs |
|
|
747
|
+
| AES-128-GCM | 4 KB | 70.2 K/s / 14.24 µs | 53.2 K/s / 18.79 µs |
|
|
748
|
+
| AES-128-CTR | 64 B | 187.9 K/s / 5.32 µs | 196.9 K/s / 5.08 µs |
|
|
749
|
+
| AES-128-CTR | 512 B | 183.5 K/s / 5.45 µs | 185.6 K/s / 5.39 µs |
|
|
750
|
+
| AES-128-CTR | 4 KB | 78.4 K/s / 12.75 µs | 71.8 K/s / 13.93 µs |
|
|
751
|
+
| XOR _(obfuscation only)_ | 64 B | 2.43 M/s / 412 ns | 2.10 M/s / 476 ns |
|
|
752
|
+
| XOR _(obfuscation only)_ | 512 B | 665.5 K/s / 1.50 µs | 715.3 K/s / 1.40 µs |
|
|
753
|
+
| XOR _(obfuscation only)_ | 4 KB | 114.5 K/s / 8.73 µs | 77.6 K/s / 12.89 µs |
|
|
718
754
|
|
|
719
755
|
> AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
|
|
720
756
|
> AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).
|
|
@@ -0,0 +1,366 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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,CAAC,W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