tricache 0.3.0 → 0.3.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 +84 -19
- package/dist/index.cjs +184 -6
- package/dist/index.d.cts +101 -1
- package/dist/index.d.ts +101 -1
- package/dist/index.js +184 -6
- package/package.json +11 -10
- package/src/cache-service.ts +213 -11
- package/src/index.ts +2 -0
- package/src/types.ts +65 -0
package/README.md
CHANGED
|
@@ -29,6 +29,11 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
|
|
|
29
29
|
| **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
|
|
30
30
|
| **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
|
|
31
31
|
| **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
|
|
32
|
+
| **Batch write** | `mset()` / `mdel()` write or delete many keys in a single `Promise.all` call |
|
|
33
|
+
| **TTL jitter** | `ttlJitterFactor` spreads expirations across a configurable ± window — prevents thundering-cliff mass-expiry |
|
|
34
|
+
| **OpenTelemetry spans** | Structural `ICacheTracer` / `ICacheSpan` interfaces — pass any OTEL-compatible tracer; no peer dep required |
|
|
35
|
+
| **L2 circuit breaker** | Suspends Redis after N consecutive failures; auto-probes after cooldown; state visible in `metrics()` |
|
|
36
|
+
| **`warmFromL2(pattern)`** | Scan Redis and pre-populate L1 at startup; returns count loaded; no-op when Redis unavailable |
|
|
32
37
|
| **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
|
|
33
38
|
| **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
|
|
34
39
|
| **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
|
|
@@ -97,6 +102,19 @@ const [userA, userB] = await cache.mget(
|
|
|
97
102
|
300,
|
|
98
103
|
);
|
|
99
104
|
|
|
105
|
+
// Batch write
|
|
106
|
+
await cache.mset({
|
|
107
|
+
[`user:${userIdA}`]: { value: userA, ttl: 300 },
|
|
108
|
+
[`user:${userIdB}`]: { value: userB, ttl: 300 },
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// Batch delete
|
|
112
|
+
await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
|
|
113
|
+
|
|
114
|
+
// Warm L1 from Redis at startup
|
|
115
|
+
const loaded = await cache.warmFromL2('user:*');
|
|
116
|
+
console.log(`Pre-warmed ${loaded} user entries`);
|
|
117
|
+
|
|
100
118
|
// Tag entries for group invalidation
|
|
101
119
|
await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
|
|
102
120
|
await cache.invalidateTag('catalog'); // evict all catalog entries
|
|
@@ -181,6 +199,24 @@ CacheService.create({
|
|
|
181
199
|
// reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
|
|
182
200
|
onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
|
|
183
201
|
|
|
202
|
+
// ── TTL jitter ────────────────────────────────────────────────────────
|
|
203
|
+
// Multiply each TTL by a random factor in [1-j, 1+j] to spread expiry.
|
|
204
|
+
// Prevents mass-expiry stampedes ("thundering cliff").
|
|
205
|
+
// Range [0, 1]; default 0 (no jitter).
|
|
206
|
+
ttlJitterFactor: 0.15, // ± 15 % spread
|
|
207
|
+
|
|
208
|
+
// ── OpenTelemetry tracer ──────────────────────────────────────────────
|
|
209
|
+
// Pass any @opentelemetry/api-compatible tracer. No peer dependency.
|
|
210
|
+
// Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
|
|
211
|
+
// Attributes: cache.key_prefix, cache.hit ('l1'|'disk'|'l2'|'miss')
|
|
212
|
+
tracer: trace.getTracer('my-app'),
|
|
213
|
+
|
|
214
|
+
// ── L2 circuit breaker ────────────────────────────────────────────────
|
|
215
|
+
// Opens after N consecutive Redis errors; probes after cooldown ms.
|
|
216
|
+
// State visible in cache.metrics().l2CircuitBreaker.state
|
|
217
|
+
l2CircuitBreakerThreshold: 5, // default
|
|
218
|
+
l2CircuitBreakerCooldownMs: 30_000, // default
|
|
219
|
+
|
|
184
220
|
// ── Prometheus instance label ─────────────────────────────────────────
|
|
185
221
|
// Adds an `instance` label to every metric in toPrometheusText().
|
|
186
222
|
instanceName: 'api-us-east-1',
|
|
@@ -262,6 +298,35 @@ const [userA, userB] = await cache.mget(
|
|
|
262
298
|
);
|
|
263
299
|
```
|
|
264
300
|
|
|
301
|
+
### `cache.mset<T>(entries)` → `Promise<void>`
|
|
302
|
+
|
|
303
|
+
Write multiple entries in a single call. Each entry accepts `value`, `ttl`, `priority`, and `tags`.
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
await cache.mset({
|
|
307
|
+
'user:1': { value: alice, ttl: 300, priority: CachePriority.HIGH, tags: ['users'] },
|
|
308
|
+
'user:2': { value: bob, ttl: 300 },
|
|
309
|
+
});
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
### `cache.mdel(keys)` → `Promise<void>`
|
|
313
|
+
|
|
314
|
+
Delete multiple keys in a single call. No-op for keys that do not exist.
|
|
315
|
+
|
|
316
|
+
```typescript
|
|
317
|
+
await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### `cache.warmFromL2(pattern)` → `Promise<number>`
|
|
321
|
+
|
|
322
|
+
Scan Redis for keys matching a glob pattern (e.g. `'user:*'`) and load their values into L1 with a 10-minute TTL. Returns the number of keys loaded. Returns `0` immediately when Redis is disabled or unreachable — safe to call unconditionally at startup.
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
// In your application startup
|
|
326
|
+
const loaded = await cache.warmFromL2('user:*');
|
|
327
|
+
console.log(`Pre-warmed ${loaded} user entries from Redis`);
|
|
328
|
+
```
|
|
329
|
+
|
|
265
330
|
### `cache.has(key)` → `boolean`
|
|
266
331
|
|
|
267
332
|
Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
|
|
@@ -547,35 +612,35 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
|
|
|
547
612
|
|
|
548
613
|
| Operation | Throughput | Latency | Notes |
|
|
549
614
|
|---|---|---|---|
|
|
550
|
-
| `get` — hot hit (8K entries) | **2.
|
|
551
|
-
| `get` — cold miss | **
|
|
552
|
-
| `set` — tiny payload |
|
|
553
|
-
| `set` — small payload (≈ 512 B) |
|
|
554
|
-
| `set` — large payload (≥ 512 B) |
|
|
555
|
-
| `set` — CRITICAL priority |
|
|
556
|
-
| `delete` — exact key | **
|
|
557
|
-
| `deletePattern` — glob wildcard | 7.
|
|
558
|
-
| Count-Min Sketch estimate | **
|
|
615
|
+
| `get` — hot hit (8K entries) | **2.60 M/s** | 385 ns | bloom → Map lookup → return cached value |
|
|
616
|
+
| `get` — cold miss | **7.07 M/s** | 141 ns | bloom gates → early return |
|
|
617
|
+
| `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
|
|
618
|
+
| `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
|
|
619
|
+
| `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
|
|
620
|
+
| `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
|
|
621
|
+
| `delete` — exact key | **3.94 M/s** | 254 ns | Map.delete |
|
|
622
|
+
| `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
|
|
623
|
+
| Count-Min Sketch estimate | **2.97 M/s** | 336 ns | 4 row lookups — called on every `get()` hit and `set()` |
|
|
559
624
|
|
|
560
625
|
**Iterator interface (L1 live entries, 500 entries)**
|
|
561
626
|
|
|
562
627
|
| Method | Throughput | Latency | Notes |
|
|
563
628
|
|---|---|---|---|
|
|
564
|
-
| `cache.keys()` | 34.
|
|
565
|
-
| `cache.values()` |
|
|
566
|
-
| `cache.entries()` |
|
|
567
|
-
| raw `Map` iteration (baseline) |
|
|
629
|
+
| `cache.keys()` | 34.1 K/s | 29 µs | no `[key,entry]` tuple allocation — +19 % vs v0.2.0 |
|
|
630
|
+
| `cache.values()` | 33.6 K/s | 30 µs | `yield*` delegation — +4 % vs v0.2.0 |
|
|
631
|
+
| `cache.entries()` | 24.5 K/s | 41 µs | `[strippedKey, value]` pairs |
|
|
632
|
+
| raw `Map` iteration (baseline) | 351 K/s | 2.85 µs | no expiry check, no generator overhead |
|
|
568
633
|
|
|
569
634
|
**CacheService (end-to-end)**
|
|
570
635
|
|
|
571
636
|
| Operation | Throughput | Latency | Notes |
|
|
572
637
|
|---|---|---|---|
|
|
573
|
-
| `get` — L1 warm hit | **
|
|
574
|
-
| `get` — SWR stale serve | **
|
|
575
|
-
| `get` — miss + fetchFn |
|
|
576
|
-
| `set` |
|
|
577
|
-
| `delete` — exact key |
|
|
578
|
-
| `delete` — glob `*` |
|
|
638
|
+
| `get` — L1 warm hit | **1.86 M/s** | 539 ns | inflight check → l1.get → return cached value |
|
|
639
|
+
| `get` — SWR stale serve | **796 K/s** | 1.26 µs | serves stale; revalidates async |
|
|
640
|
+
| `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
|
|
641
|
+
| `set` | 31.0 K/s | 32 µs | l1.set + disk.save (fire-and-forget) |
|
|
642
|
+
| `delete` — exact key | 7.9 K/s | 126 µs | l1.delete + disk.delete + backplane |
|
|
643
|
+
| `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
|
|
579
644
|
|
|
580
645
|
**Encryption** (IV pool, pre-allocated output buffers)
|
|
581
646
|
|
package/dist/index.cjs
CHANGED
|
@@ -1366,6 +1366,47 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
1366
1366
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
1367
1367
|
};
|
|
1368
1368
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
1369
|
+
var L2CircuitBreaker = class {
|
|
1370
|
+
constructor(threshold, cooldownMs) {
|
|
1371
|
+
this.threshold = threshold;
|
|
1372
|
+
this.cooldownMs = cooldownMs;
|
|
1373
|
+
}
|
|
1374
|
+
threshold;
|
|
1375
|
+
cooldownMs;
|
|
1376
|
+
state = 0 /* CLOSED */;
|
|
1377
|
+
failures = 0;
|
|
1378
|
+
openedAt = 0;
|
|
1379
|
+
/** Call before each Redis attempt. Returns false when the circuit is open. */
|
|
1380
|
+
isAllowed() {
|
|
1381
|
+
if (this.state === 0 /* CLOSED */) return true;
|
|
1382
|
+
if (this.state === 2 /* HALF_OPEN */) return true;
|
|
1383
|
+
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1384
|
+
this.state = 2 /* HALF_OPEN */;
|
|
1385
|
+
return true;
|
|
1386
|
+
}
|
|
1387
|
+
return false;
|
|
1388
|
+
}
|
|
1389
|
+
/** Call on Redis success. */
|
|
1390
|
+
onSuccess() {
|
|
1391
|
+
this.failures = 0;
|
|
1392
|
+
this.state = 0 /* CLOSED */;
|
|
1393
|
+
}
|
|
1394
|
+
/** Call on Redis failure. */
|
|
1395
|
+
onFailure() {
|
|
1396
|
+
this.failures++;
|
|
1397
|
+
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1398
|
+
this.state = 1 /* OPEN */;
|
|
1399
|
+
this.openedAt = Date.now();
|
|
1400
|
+
this.failures = 0;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
get isOpen() {
|
|
1404
|
+
return this.state === 1 /* OPEN */;
|
|
1405
|
+
}
|
|
1406
|
+
get currentState() {
|
|
1407
|
+
return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1369
1410
|
function inferPriority(cacheKey) {
|
|
1370
1411
|
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
1371
1412
|
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
@@ -1390,6 +1431,7 @@ var CacheService = class _CacheService {
|
|
|
1390
1431
|
tagIndex = /* @__PURE__ */ new Map();
|
|
1391
1432
|
redis = null;
|
|
1392
1433
|
redisConnecting = null;
|
|
1434
|
+
cb;
|
|
1393
1435
|
snapshotLoaded = false;
|
|
1394
1436
|
cleanupInterval = null;
|
|
1395
1437
|
oomInterval = null;
|
|
@@ -1464,8 +1506,13 @@ var CacheService = class _CacheService {
|
|
|
1464
1506
|
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1465
1507
|
staleIfError: options.staleIfError ?? 0,
|
|
1466
1508
|
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1467
|
-
instanceName: options.instanceName ?? ""
|
|
1509
|
+
instanceName: options.instanceName ?? "",
|
|
1510
|
+
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1511
|
+
tracer: options.tracer
|
|
1468
1512
|
};
|
|
1513
|
+
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1514
|
+
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
1515
|
+
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
1469
1516
|
this.disk = new DiskTier({
|
|
1470
1517
|
dir: this.opts.diskCacheDir,
|
|
1471
1518
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -1586,6 +1633,22 @@ var CacheService = class _CacheService {
|
|
|
1586
1633
|
nk(key) {
|
|
1587
1634
|
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
1588
1635
|
}
|
|
1636
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
1637
|
+
_jitterTtl(ttlMs) {
|
|
1638
|
+
const j = this.opts.ttlJitterFactor;
|
|
1639
|
+
if (j === 0) return ttlMs;
|
|
1640
|
+
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
1641
|
+
}
|
|
1642
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
1643
|
+
_startSpan(name) {
|
|
1644
|
+
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
1645
|
+
return { setAttribute() {
|
|
1646
|
+
return this;
|
|
1647
|
+
}, setStatus() {
|
|
1648
|
+
return this;
|
|
1649
|
+
}, end() {
|
|
1650
|
+
} };
|
|
1651
|
+
}
|
|
1589
1652
|
initBackplane() {
|
|
1590
1653
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1591
1654
|
if (this.subClient) return;
|
|
@@ -1647,7 +1710,7 @@ var CacheService = class _CacheService {
|
|
|
1647
1710
|
}
|
|
1648
1711
|
}
|
|
1649
1712
|
async getRedis() {
|
|
1650
|
-
if (this.
|
|
1713
|
+
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
1651
1714
|
if (this.redisConnecting) return this.redisConnecting;
|
|
1652
1715
|
this.redisConnecting = (async () => {
|
|
1653
1716
|
try {
|
|
@@ -1671,10 +1734,12 @@ var CacheService = class _CacheService {
|
|
|
1671
1734
|
client.once("error", reject);
|
|
1672
1735
|
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1673
1736
|
});
|
|
1737
|
+
this.cb.onSuccess();
|
|
1674
1738
|
this.redis = client;
|
|
1675
1739
|
this.redisConnecting = null;
|
|
1676
1740
|
return client;
|
|
1677
1741
|
} catch (err) {
|
|
1742
|
+
this.cb.onFailure();
|
|
1678
1743
|
this.redisConnecting = null;
|
|
1679
1744
|
throw err;
|
|
1680
1745
|
}
|
|
@@ -1761,6 +1826,8 @@ var CacheService = class _CacheService {
|
|
|
1761
1826
|
* instantly while a background refresh runs. Default: 0 (disabled).
|
|
1762
1827
|
*/
|
|
1763
1828
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
1829
|
+
const span = this._startSpan("tricache.get");
|
|
1830
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1764
1831
|
const k = this.nk(cacheKey);
|
|
1765
1832
|
this.counters.gets++;
|
|
1766
1833
|
const l1Hit = this.l1.get(k);
|
|
@@ -1780,24 +1847,28 @@ var CacheService = class _CacheService {
|
|
|
1780
1847
|
this.logger.debug("L1 hit");
|
|
1781
1848
|
}
|
|
1782
1849
|
this.counters.l1Hits++;
|
|
1850
|
+
span.setAttribute("cache.hit", "l1").end();
|
|
1783
1851
|
return l1Hit.value;
|
|
1784
1852
|
}
|
|
1785
|
-
const ttlMs = ttlSeconds * 1e3;
|
|
1853
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1786
1854
|
const swrGraceMs = (opts.swr ?? 0) * 1e3;
|
|
1787
1855
|
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
1788
1856
|
if (!this._redisDisabled) {
|
|
1789
1857
|
try {
|
|
1790
1858
|
const client = await this.getRedis();
|
|
1791
1859
|
const raw = await client.get(k);
|
|
1860
|
+
this.cb.onSuccess();
|
|
1792
1861
|
if (raw) {
|
|
1793
1862
|
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
1794
1863
|
const parsed = JSON.parse(decrypted);
|
|
1795
1864
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
1796
1865
|
this.counters.l2Hits++;
|
|
1797
1866
|
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
1867
|
+
span.setAttribute("cache.hit", "l2").end();
|
|
1798
1868
|
return parsed;
|
|
1799
1869
|
}
|
|
1800
1870
|
} catch (err) {
|
|
1871
|
+
this.cb.onFailure();
|
|
1801
1872
|
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
1802
1873
|
}
|
|
1803
1874
|
}
|
|
@@ -1812,14 +1883,17 @@ var CacheService = class _CacheService {
|
|
|
1812
1883
|
if (l1Check !== null) {
|
|
1813
1884
|
this.counters.diskHits++;
|
|
1814
1885
|
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
1886
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
1815
1887
|
return l1Check.value;
|
|
1816
1888
|
}
|
|
1817
1889
|
}
|
|
1818
1890
|
}
|
|
1891
|
+
span.setAttribute("cache.hit", "miss");
|
|
1819
1892
|
const existing = this.inflight.get(k);
|
|
1820
1893
|
if (existing) {
|
|
1821
1894
|
this.counters.stampedes++;
|
|
1822
1895
|
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
1896
|
+
span.end();
|
|
1823
1897
|
return existing;
|
|
1824
1898
|
}
|
|
1825
1899
|
const fetchPromise = (async () => {
|
|
@@ -1834,9 +1908,11 @@ var CacheService = class _CacheService {
|
|
|
1834
1908
|
const client = await this.getRedis();
|
|
1835
1909
|
const serialized = JSON.stringify(data);
|
|
1836
1910
|
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1837
|
-
await client.setex(k,
|
|
1911
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
|
|
1912
|
+
this.cb.onSuccess();
|
|
1838
1913
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
1839
1914
|
} catch {
|
|
1915
|
+
this.cb.onFailure();
|
|
1840
1916
|
this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
|
|
1841
1917
|
}
|
|
1842
1918
|
} else {
|
|
@@ -1845,6 +1921,7 @@ var CacheService = class _CacheService {
|
|
|
1845
1921
|
return data;
|
|
1846
1922
|
} finally {
|
|
1847
1923
|
this.inflight.delete(k);
|
|
1924
|
+
span.end();
|
|
1848
1925
|
}
|
|
1849
1926
|
})();
|
|
1850
1927
|
this.inflight.set(k, fetchPromise);
|
|
@@ -1883,7 +1960,9 @@ var CacheService = class _CacheService {
|
|
|
1883
1960
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1884
1961
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1885
1962
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1886
|
-
const
|
|
1963
|
+
const span = this._startSpan("tricache.set");
|
|
1964
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1965
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1887
1966
|
const p = priority ?? inferPriority(cacheKey);
|
|
1888
1967
|
const k = this.nk(cacheKey);
|
|
1889
1968
|
this.counters.sets++;
|
|
@@ -1908,7 +1987,9 @@ var CacheService = class _CacheService {
|
|
|
1908
1987
|
pl.expire(tagKey, ttlSeconds + 3600);
|
|
1909
1988
|
}
|
|
1910
1989
|
await pl.exec();
|
|
1990
|
+
this.cb.onSuccess();
|
|
1911
1991
|
} catch {
|
|
1992
|
+
this.cb.onFailure();
|
|
1912
1993
|
}
|
|
1913
1994
|
}
|
|
1914
1995
|
}
|
|
@@ -1917,12 +1998,15 @@ var CacheService = class _CacheService {
|
|
|
1917
1998
|
const client = await this.getRedis();
|
|
1918
1999
|
const s = JSON.stringify(data);
|
|
1919
2000
|
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1920
|
-
await client.setex(k,
|
|
2001
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
2002
|
+
this.cb.onSuccess();
|
|
1921
2003
|
} catch (err) {
|
|
2004
|
+
this.cb.onFailure();
|
|
1922
2005
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
1923
2006
|
}
|
|
1924
2007
|
}
|
|
1925
2008
|
void this.publishInvalidation("del", k);
|
|
2009
|
+
span.end();
|
|
1926
2010
|
}
|
|
1927
2011
|
/**
|
|
1928
2012
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -1932,6 +2016,8 @@ var CacheService = class _CacheService {
|
|
|
1932
2016
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
1933
2017
|
*/
|
|
1934
2018
|
async delete(cacheKey) {
|
|
2019
|
+
const span = this._startSpan("tricache.delete");
|
|
2020
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1935
2021
|
const isPattern = cacheKey.includes("*");
|
|
1936
2022
|
const k = this.nk(cacheKey);
|
|
1937
2023
|
this.counters.deletes++;
|
|
@@ -1956,11 +2042,14 @@ var CacheService = class _CacheService {
|
|
|
1956
2042
|
} else {
|
|
1957
2043
|
await client.del(k);
|
|
1958
2044
|
}
|
|
2045
|
+
this.cb.onSuccess();
|
|
1959
2046
|
} catch (err) {
|
|
2047
|
+
this.cb.onFailure();
|
|
1960
2048
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
1961
2049
|
}
|
|
1962
2050
|
}
|
|
1963
2051
|
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
2052
|
+
span.end();
|
|
1964
2053
|
}
|
|
1965
2054
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
1966
2055
|
/**
|
|
@@ -2159,6 +2248,92 @@ var CacheService = class _CacheService {
|
|
|
2159
2248
|
}
|
|
2160
2249
|
return result;
|
|
2161
2250
|
}
|
|
2251
|
+
/**
|
|
2252
|
+
* Batch write — set multiple entries in a single call.
|
|
2253
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
2254
|
+
*
|
|
2255
|
+
* @example
|
|
2256
|
+
* await cache.mset({
|
|
2257
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
2258
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
2259
|
+
* });
|
|
2260
|
+
*/
|
|
2261
|
+
async mset(entries) {
|
|
2262
|
+
const keys = Object.keys(entries);
|
|
2263
|
+
await Promise.all(keys.map((key) => {
|
|
2264
|
+
const { value, ttl = 300, priority, tags } = entries[key];
|
|
2265
|
+
return this.set(key, value, ttl, priority, tags ? { tags } : void 0);
|
|
2266
|
+
}));
|
|
2267
|
+
}
|
|
2268
|
+
/**
|
|
2269
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
2270
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
2271
|
+
*
|
|
2272
|
+
* @example
|
|
2273
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
2274
|
+
*/
|
|
2275
|
+
async mdel(keys) {
|
|
2276
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
2280
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
2281
|
+
* the local snapshot is unavailable or too stale.
|
|
2282
|
+
*
|
|
2283
|
+
* Returns the number of keys loaded into L1.
|
|
2284
|
+
*
|
|
2285
|
+
* @example
|
|
2286
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
2287
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
2288
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
2289
|
+
*/
|
|
2290
|
+
async warmFromL2(pattern) {
|
|
2291
|
+
if (this._redisDisabled) return 0;
|
|
2292
|
+
try {
|
|
2293
|
+
const client = await this.getRedis();
|
|
2294
|
+
const nsPattern = this.nk(pattern);
|
|
2295
|
+
const matchedKeys = [];
|
|
2296
|
+
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
2297
|
+
await new Promise((resolve, reject) => {
|
|
2298
|
+
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
2299
|
+
stream.on("end", resolve);
|
|
2300
|
+
stream.on("error", reject);
|
|
2301
|
+
});
|
|
2302
|
+
if (matchedKeys.length === 0) {
|
|
2303
|
+
this.cb.onSuccess();
|
|
2304
|
+
return 0;
|
|
2305
|
+
}
|
|
2306
|
+
const pl = client.pipeline();
|
|
2307
|
+
for (const k of matchedKeys) pl.get(k);
|
|
2308
|
+
const results = await pl.exec();
|
|
2309
|
+
this.cb.onSuccess();
|
|
2310
|
+
let loaded = 0;
|
|
2311
|
+
const now = Date.now();
|
|
2312
|
+
for (let i = 0; i < matchedKeys.length; i++) {
|
|
2313
|
+
const [err, raw] = results[i];
|
|
2314
|
+
if (err || raw == null) continue;
|
|
2315
|
+
try {
|
|
2316
|
+
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2317
|
+
const parsed = JSON.parse(decrypted);
|
|
2318
|
+
const remainingMs = 10 * 60 * 1e3;
|
|
2319
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
2320
|
+
loaded++;
|
|
2321
|
+
} catch {
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
void now;
|
|
2325
|
+
this.logger.info("warmFromL2 complete", {
|
|
2326
|
+
pattern,
|
|
2327
|
+
matched: matchedKeys.length,
|
|
2328
|
+
loaded
|
|
2329
|
+
});
|
|
2330
|
+
return loaded;
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
this.cb.onFailure();
|
|
2333
|
+
this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
|
|
2334
|
+
return 0;
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2162
2337
|
/**
|
|
2163
2338
|
* Invalidate all keys associated with a tag.
|
|
2164
2339
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -2292,6 +2467,9 @@ var CacheService = class _CacheService {
|
|
|
2292
2467
|
received: c.invReceived,
|
|
2293
2468
|
skipped: c.invSkipped
|
|
2294
2469
|
},
|
|
2470
|
+
l2CircuitBreaker: {
|
|
2471
|
+
state: this.cb.currentState
|
|
2472
|
+
},
|
|
2295
2473
|
oom: {
|
|
2296
2474
|
enabled: this.opts.oomProtection,
|
|
2297
2475
|
evictions: c.oomEvictions,
|
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;
|
|
@@ -144,6 +162,11 @@ interface CacheMetrics {
|
|
|
144
162
|
/** Own messages silently skipped (prevents double-eviction) */
|
|
145
163
|
skipped: number;
|
|
146
164
|
};
|
|
165
|
+
/** L2 Redis circuit breaker state */
|
|
166
|
+
l2CircuitBreaker: {
|
|
167
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
168
|
+
state: 'closed' | 'open' | 'half_open';
|
|
169
|
+
};
|
|
147
170
|
/** OOM guard statistics */
|
|
148
171
|
oom: {
|
|
149
172
|
enabled: boolean;
|
|
@@ -342,6 +365,41 @@ interface CacheOptions {
|
|
|
342
365
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
343
366
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
344
367
|
metricsIntervalMs?: number;
|
|
368
|
+
/**
|
|
369
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
370
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
371
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
372
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
373
|
+
*
|
|
374
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
375
|
+
* dependency required; the interface is structurally compatible.
|
|
376
|
+
*
|
|
377
|
+
* @example
|
|
378
|
+
* import { trace } from '@opentelemetry/api';
|
|
379
|
+
* tracer: trace.getTracer('tricache')
|
|
380
|
+
*/
|
|
381
|
+
tracer?: ICacheTracer;
|
|
382
|
+
/**
|
|
383
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
384
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
385
|
+
* the same TTL and expire simultaneously.
|
|
386
|
+
*
|
|
387
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
388
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
389
|
+
*/
|
|
390
|
+
ttlJitterFactor?: number;
|
|
391
|
+
/**
|
|
392
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
393
|
+
* attempting Redis until the cooldown elapses).
|
|
394
|
+
* Default: `5`.
|
|
395
|
+
*/
|
|
396
|
+
l2CircuitBreakerThreshold?: number;
|
|
397
|
+
/**
|
|
398
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
399
|
+
* (allows a single probe request to test recovery).
|
|
400
|
+
* Default: `30 000` ms (30 s).
|
|
401
|
+
*/
|
|
402
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
345
403
|
}
|
|
346
404
|
|
|
347
405
|
/**
|
|
@@ -379,6 +437,7 @@ declare class CacheService {
|
|
|
379
437
|
private readonly tagIndex;
|
|
380
438
|
private redis;
|
|
381
439
|
private redisConnecting;
|
|
440
|
+
private readonly cb;
|
|
382
441
|
private snapshotLoaded;
|
|
383
442
|
private cleanupInterval;
|
|
384
443
|
private oomInterval;
|
|
@@ -419,6 +478,10 @@ declare class CacheService {
|
|
|
419
478
|
* receive and provide un-prefixed keys in the public API.
|
|
420
479
|
*/
|
|
421
480
|
private nk;
|
|
481
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
482
|
+
private _jitterTtl;
|
|
483
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
484
|
+
private _startSpan;
|
|
422
485
|
private initBackplane;
|
|
423
486
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
424
487
|
_handleBackplaneMessage(message: string): void;
|
|
@@ -532,6 +595,43 @@ declare class CacheService {
|
|
|
532
595
|
* @param ttl - TTL in seconds for newly fetched values.
|
|
533
596
|
*/
|
|
534
597
|
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
598
|
+
/**
|
|
599
|
+
* Batch write — set multiple entries in a single call.
|
|
600
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
601
|
+
*
|
|
602
|
+
* @example
|
|
603
|
+
* await cache.mset({
|
|
604
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
605
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
606
|
+
* });
|
|
607
|
+
*/
|
|
608
|
+
mset<T = unknown>(entries: Record<string, {
|
|
609
|
+
value: T;
|
|
610
|
+
ttl?: number;
|
|
611
|
+
priority?: CachePriority;
|
|
612
|
+
tags?: string[];
|
|
613
|
+
}>): Promise<void>;
|
|
614
|
+
/**
|
|
615
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
616
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
617
|
+
*
|
|
618
|
+
* @example
|
|
619
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
620
|
+
*/
|
|
621
|
+
mdel(keys: string[]): Promise<void>;
|
|
622
|
+
/**
|
|
623
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
624
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
625
|
+
* the local snapshot is unavailable or too stale.
|
|
626
|
+
*
|
|
627
|
+
* Returns the number of keys loaded into L1.
|
|
628
|
+
*
|
|
629
|
+
* @example
|
|
630
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
631
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
632
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
633
|
+
*/
|
|
634
|
+
warmFromL2(pattern: string): Promise<number>;
|
|
535
635
|
/**
|
|
536
636
|
* Invalidate all keys associated with a tag.
|
|
537
637
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -960,4 +1060,4 @@ declare class WasmBloomFilter {
|
|
|
960
1060
|
get maxCapacity(): number;
|
|
961
1061
|
}
|
|
962
1062
|
|
|
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 };
|
|
1063
|
+
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 };
|