tricache 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -0
- package/dist/index.cjs +171 -15
- package/dist/index.d.cts +95 -5
- package/dist/index.d.ts +95 -5
- package/dist/index.js +171 -15
- package/package.json +1 -1
- package/src/cache-service.ts +190 -18
- package/src/smart-memory-cache.ts +21 -2
- package/src/types.ts +19 -0
package/README.md
CHANGED
|
@@ -42,6 +42,12 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
|
|
|
42
42
|
| **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
|
|
43
43
|
| **L2 read-only mode** | `l2WriteMode: 'read-only'` reads from Redis but skips all writes — canary deploys, read replicas |
|
|
44
44
|
| **Eviction callback** | `onEviction(key, reason)` fires on every L1 eviction with a typed reason string |
|
|
45
|
+
| **Negative caching (`notFoundTtl`)** | Cache `null`/`undefined` fetchFn results for a configurable TTL — prevents hammering upstream on repeated misses |
|
|
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
|
+
| **Refresh-ahead** | Proactively recompute an entry in the background when remaining TTL falls below a configured fraction — zero-latency freshness |
|
|
48
|
+
| **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
|
|
49
|
+
| **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
|
|
50
|
+
| **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
|
|
45
51
|
|
|
46
52
|
---
|
|
47
53
|
|
|
@@ -115,6 +121,17 @@ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
|
|
|
115
121
|
const loaded = await cache.warmFromL2('user:*');
|
|
116
122
|
console.log(`Pre-warmed ${loaded} user entries`);
|
|
117
123
|
|
|
124
|
+
// Atomic set-if-absent — returns true if written, false if key already cached
|
|
125
|
+
const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
|
|
126
|
+
|
|
127
|
+
// Dependency cascade: deleting 'org:42' automatically evicts 'org:42:config'
|
|
128
|
+
await cache.set('org:42:config', config, 300, undefined, { dependsOn: ['org:42'] });
|
|
129
|
+
await cache.delete('org:42'); // also evicts org:42:config
|
|
130
|
+
|
|
131
|
+
// Top 10 hottest keys by Count-Min Sketch frequency
|
|
132
|
+
const hot = cache.hotKeys(10);
|
|
133
|
+
console.log(hot); // [{ key: 'user:1', hits: 842, sizeBytes: 512 }, ...]
|
|
134
|
+
|
|
118
135
|
// Tag entries for group invalidation
|
|
119
136
|
await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
|
|
120
137
|
await cache.invalidateTag('catalog'); // evict all catalog entries
|
|
@@ -217,6 +234,12 @@ CacheService.create({
|
|
|
217
234
|
l2CircuitBreakerThreshold: 5, // default
|
|
218
235
|
l2CircuitBreakerCooldownMs: 30_000, // default
|
|
219
236
|
|
|
237
|
+
// ── Negative caching ──────────────────────────────────────────────────
|
|
238
|
+
// Cache null/undefined fetchFn results for this many seconds globally.
|
|
239
|
+
// Prevents repeated upstream calls for keys that genuinely don't exist.
|
|
240
|
+
// Can be overridden per-call via opts.notFoundTtl in cache.get().
|
|
241
|
+
notFoundTtl: 30, // seconds; 0 = disabled (default)
|
|
242
|
+
|
|
220
243
|
// ── Prometheus instance label ─────────────────────────────────────────
|
|
221
244
|
// Adds an `instance` label to every metric in toPrometheusText().
|
|
222
245
|
instanceName: 'api-us-east-1',
|
|
@@ -273,6 +296,9 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
|
|
|
273
296
|
| `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
|
|
274
297
|
| `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
|
|
275
298
|
| `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
|
|
299
|
+
| `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
|
|
300
|
+
| `opts.xfetchBeta` | `number` | — | XFetch β ≥ 0 — scales probabilistic early recompute by last fetch duration; higher = recompute earlier |
|
|
301
|
+
| `opts.notFoundTtl` | `number` | — | Per-call TTL in seconds for `null`/`undefined` results (overrides global `notFoundTtl`) |
|
|
276
302
|
|
|
277
303
|
### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
|
|
278
304
|
|
|
@@ -281,9 +307,14 @@ Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
|
|
|
281
307
|
| Parameter | Type | Default | Description |
|
|
282
308
|
|---|---|---|---|
|
|
283
309
|
| `opts.tags` | `string[]` | `[]` | Associate tags with this entry for group invalidation |
|
|
310
|
+
| `opts.dependsOn` | `string[]` | `[]` | Parent keys — when any parent is deleted, this entry is automatically evicted from L1 |
|
|
284
311
|
|
|
285
312
|
```typescript
|
|
286
313
|
await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'featured'] });
|
|
314
|
+
|
|
315
|
+
// Cascade invalidation: evicting 'org:42' also evicts 'org:42:members'
|
|
316
|
+
await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42'] });
|
|
317
|
+
await cache.delete('org:42'); // org:42:members is evicted too
|
|
287
318
|
```
|
|
288
319
|
|
|
289
320
|
### `cache.mget<T>(keys, fetchFn, ttlSeconds?, priority?)` → `Promise<(T | undefined)[]>`
|
|
@@ -353,6 +384,32 @@ const fresh = cache.getIfFresh<User>('user:123');
|
|
|
353
384
|
if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
354
385
|
```
|
|
355
386
|
|
|
387
|
+
### `cache.setIfAbsent<T>(key, value, ttlSeconds?)` → `Promise<boolean>`
|
|
388
|
+
|
|
389
|
+
Atomically write `value` only if `key` is not already cached. Checks L1 first, then attempts a Redis `SET NX EX`. Returns `true` if the value was written, `false` if a live entry already existed.
|
|
390
|
+
|
|
391
|
+
Useful for distributed lock-style writes, session initialisation, or any pattern where you must not overwrite an already-cached value.
|
|
392
|
+
|
|
393
|
+
```typescript
|
|
394
|
+
const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
|
|
395
|
+
if (!written) {
|
|
396
|
+
// session already exists — do not overwrite
|
|
397
|
+
}
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
### `cache.hotKeys(n?)` → `Array<{ key: string; hits: number; sizeBytes: number }>`
|
|
401
|
+
|
|
402
|
+
Returns the top `n` live L1 keys ranked by Count-Min Sketch access frequency. Namespace prefix is stripped from each key. Expired entries are excluded. Default `n = 10`.
|
|
403
|
+
|
|
404
|
+
```typescript
|
|
405
|
+
const hot = cache.hotKeys(5);
|
|
406
|
+
// [
|
|
407
|
+
// { key: 'user:1', hits: 1024, sizeBytes: 512 },
|
|
408
|
+
// { key: 'product:7', hits: 893, sizeBytes: 256 },
|
|
409
|
+
// ...
|
|
410
|
+
// ]
|
|
411
|
+
```
|
|
412
|
+
|
|
356
413
|
### `cache.invalidateTag(tag)` → `Promise<void>`
|
|
357
414
|
|
|
358
415
|
Evict all entries associated with a tag from L1, disk, and Redis.
|
package/dist/index.cjs
CHANGED
|
@@ -769,9 +769,9 @@ var SmartMemoryCache = class {
|
|
|
769
769
|
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
770
770
|
const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
771
771
|
const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
|
|
772
|
-
return { value, isStale };
|
|
772
|
+
return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
|
|
773
773
|
}
|
|
774
|
-
set(key, data, ttlMs, priority = 2, staleAt) {
|
|
774
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta) {
|
|
775
775
|
const packed = (0, import_msgpackr.pack)(data);
|
|
776
776
|
const size = packed.byteLength;
|
|
777
777
|
this.compressions++;
|
|
@@ -791,7 +791,7 @@ var SmartMemoryCache = class {
|
|
|
791
791
|
}
|
|
792
792
|
this.ensureCapacity(cat, size);
|
|
793
793
|
const now = Date.now();
|
|
794
|
-
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
794
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
795
795
|
this.bloom.add(key);
|
|
796
796
|
this.maybeRebuildBloom();
|
|
797
797
|
this.totalSize += size;
|
|
@@ -1079,6 +1079,23 @@ var SmartMemoryCache = class {
|
|
|
1079
1079
|
bloomStats() {
|
|
1080
1080
|
return this.bloom.stats;
|
|
1081
1081
|
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1084
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1085
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
1086
|
+
*
|
|
1087
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
1088
|
+
*/
|
|
1089
|
+
hotKeys(n) {
|
|
1090
|
+
const now = Date.now();
|
|
1091
|
+
const out = [];
|
|
1092
|
+
for (const [key, entry] of this.cache) {
|
|
1093
|
+
if (entry.expiresAt <= now) continue;
|
|
1094
|
+
out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
|
|
1095
|
+
}
|
|
1096
|
+
out.sort((a, b) => b.hits - a.hits);
|
|
1097
|
+
return out.slice(0, n);
|
|
1098
|
+
}
|
|
1082
1099
|
};
|
|
1083
1100
|
|
|
1084
1101
|
// src/disk-tier.ts
|
|
@@ -1429,6 +1446,11 @@ var CacheService = class _CacheService {
|
|
|
1429
1446
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
1430
1447
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
1431
1448
|
tagIndex = /* @__PURE__ */ new Map();
|
|
1449
|
+
/**
|
|
1450
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
1451
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
1452
|
+
*/
|
|
1453
|
+
dependencyIndex = /* @__PURE__ */ new Map();
|
|
1432
1454
|
redis = null;
|
|
1433
1455
|
redisConnecting = null;
|
|
1434
1456
|
cb;
|
|
@@ -1508,7 +1530,8 @@ var CacheService = class _CacheService {
|
|
|
1508
1530
|
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1509
1531
|
instanceName: options.instanceName ?? "",
|
|
1510
1532
|
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1511
|
-
tracer: options.tracer
|
|
1533
|
+
tracer: options.tracer,
|
|
1534
|
+
notFoundTtl: options.notFoundTtl ?? 0
|
|
1512
1535
|
};
|
|
1513
1536
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1514
1537
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
@@ -1820,10 +1843,18 @@ var CacheService = class _CacheService {
|
|
|
1820
1843
|
* @param cacheKey - Unique key identifying this value
|
|
1821
1844
|
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
1822
1845
|
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
1823
|
-
* @param opts.priority
|
|
1824
|
-
* @param opts.swr
|
|
1825
|
-
*
|
|
1826
|
-
*
|
|
1846
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
1847
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
1848
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
1849
|
+
* is triggered proactively while the caller still receives the
|
|
1850
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
1851
|
+
* Requires `fetchFn` to be stable across calls.
|
|
1852
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
1853
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
1854
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
1855
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
1856
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
1857
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
1827
1858
|
*/
|
|
1828
1859
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
1829
1860
|
const span = this._startSpan("tricache.get");
|
|
@@ -1845,6 +1876,23 @@ var CacheService = class _CacheService {
|
|
|
1845
1876
|
}
|
|
1846
1877
|
} else {
|
|
1847
1878
|
this.logger.debug("L1 hit");
|
|
1879
|
+
if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
|
|
1880
|
+
const now = Date.now();
|
|
1881
|
+
const remaining = l1Hit.expiresAt - now;
|
|
1882
|
+
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
|
|
1883
|
+
const priority2 = opts.priority ?? inferPriority(cacheKey);
|
|
1884
|
+
const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
|
|
1885
|
+
const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
|
|
1886
|
+
if (shouldRefreshAhead || shouldXFetch) {
|
|
1887
|
+
this.revalidating.add(k);
|
|
1888
|
+
void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
|
|
1889
|
+
this.counters.swrRevalidations++;
|
|
1890
|
+
this.logger.debug(
|
|
1891
|
+
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
1892
|
+
{ cacheKey, remainingMs: remaining, ttlMs: entryTtl }
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1848
1896
|
}
|
|
1849
1897
|
this.counters.l1Hits++;
|
|
1850
1898
|
span.setAttribute("cache.hit", "l1").end();
|
|
@@ -1899,16 +1947,20 @@ var CacheService = class _CacheService {
|
|
|
1899
1947
|
const fetchPromise = (async () => {
|
|
1900
1948
|
try {
|
|
1901
1949
|
this.counters.fetches++;
|
|
1950
|
+
const fetchStart = Date.now();
|
|
1902
1951
|
const data = await fetchFn();
|
|
1903
|
-
const
|
|
1904
|
-
const
|
|
1905
|
-
|
|
1952
|
+
const delta = Date.now() - fetchStart;
|
|
1953
|
+
const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
1954
|
+
const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
1955
|
+
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
1956
|
+
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
1957
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta);
|
|
1906
1958
|
if (!this._redisDisabled) {
|
|
1907
1959
|
try {
|
|
1908
1960
|
const client = await this.getRedis();
|
|
1909
1961
|
const serialized = JSON.stringify(data);
|
|
1910
1962
|
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1911
|
-
await client.setex(k, Math.ceil(
|
|
1963
|
+
await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
|
|
1912
1964
|
this.cb.onSuccess();
|
|
1913
1965
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
1914
1966
|
} catch {
|
|
@@ -1929,9 +1981,11 @@ var CacheService = class _CacheService {
|
|
|
1929
1981
|
}
|
|
1930
1982
|
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
1931
1983
|
try {
|
|
1984
|
+
const fetchStart = Date.now();
|
|
1932
1985
|
const data = await fetchFn();
|
|
1986
|
+
const delta = Date.now() - fetchStart;
|
|
1933
1987
|
const staleAt = Date.now() + ttlMs;
|
|
1934
|
-
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
|
|
1988
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
|
|
1935
1989
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1936
1990
|
try {
|
|
1937
1991
|
const client = await this.getRedis();
|
|
@@ -1993,6 +2047,17 @@ var CacheService = class _CacheService {
|
|
|
1993
2047
|
}
|
|
1994
2048
|
}
|
|
1995
2049
|
}
|
|
2050
|
+
if (opts?.dependsOn?.length) {
|
|
2051
|
+
for (const pattern of opts.dependsOn) {
|
|
2052
|
+
const nsPattern = this.nk(pattern);
|
|
2053
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
2054
|
+
if (!deps) {
|
|
2055
|
+
deps = /* @__PURE__ */ new Set();
|
|
2056
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
2057
|
+
}
|
|
2058
|
+
deps.add(k);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
1996
2061
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
1997
2062
|
try {
|
|
1998
2063
|
const client = await this.getRedis();
|
|
@@ -2026,6 +2091,8 @@ var CacheService = class _CacheService {
|
|
|
2026
2091
|
} else {
|
|
2027
2092
|
this.l1.delete(k);
|
|
2028
2093
|
this.disk.delete(k);
|
|
2094
|
+
this._cascadeDependencies(k);
|
|
2095
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
2029
2096
|
}
|
|
2030
2097
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2031
2098
|
try {
|
|
@@ -2261,8 +2328,9 @@ var CacheService = class _CacheService {
|
|
|
2261
2328
|
async mset(entries) {
|
|
2262
2329
|
const keys = Object.keys(entries);
|
|
2263
2330
|
await Promise.all(keys.map((key) => {
|
|
2264
|
-
const { value, ttl = 300, priority, tags } = entries[key];
|
|
2265
|
-
|
|
2331
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
2332
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
2333
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
2266
2334
|
}));
|
|
2267
2335
|
}
|
|
2268
2336
|
/**
|
|
@@ -2427,6 +2495,94 @@ var CacheService = class _CacheService {
|
|
|
2427
2495
|
disk: this.disk.stats
|
|
2428
2496
|
};
|
|
2429
2497
|
}
|
|
2498
|
+
// ── Conditional write ─────────────────────────────────────────────────
|
|
2499
|
+
/**
|
|
2500
|
+
* Write `value` only if the key is not already cached.
|
|
2501
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
2502
|
+
*
|
|
2503
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
2504
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
2505
|
+
* multiple instances. L1 is populated on success.
|
|
2506
|
+
*
|
|
2507
|
+
* @example
|
|
2508
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
2509
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
2510
|
+
*/
|
|
2511
|
+
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
2512
|
+
const k = this.nk(cacheKey);
|
|
2513
|
+
if (this.l1.has(k)) return false;
|
|
2514
|
+
if (!this._redisDisabled) {
|
|
2515
|
+
try {
|
|
2516
|
+
const client = await this.getRedis();
|
|
2517
|
+
const serialized = JSON.stringify(value);
|
|
2518
|
+
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
2519
|
+
const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
|
|
2520
|
+
this.cb.onSuccess();
|
|
2521
|
+
if (result === null) return false;
|
|
2522
|
+
} catch (err) {
|
|
2523
|
+
this.cb.onFailure();
|
|
2524
|
+
this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
|
|
2525
|
+
if (this.l1.has(k)) return false;
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
2529
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
2530
|
+
this.l1.set(k, value, ttlMs, p);
|
|
2531
|
+
this.counters.sets++;
|
|
2532
|
+
return true;
|
|
2533
|
+
}
|
|
2534
|
+
// ── Hot key introspection ─────────────────────────────────────────────
|
|
2535
|
+
/**
|
|
2536
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
2537
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
2538
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
2539
|
+
*
|
|
2540
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
2541
|
+
* collection overhead.
|
|
2542
|
+
*
|
|
2543
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
2544
|
+
*
|
|
2545
|
+
* @example
|
|
2546
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
2547
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
2548
|
+
*/
|
|
2549
|
+
hotKeys(n = 10) {
|
|
2550
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2551
|
+
return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
|
|
2552
|
+
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
2553
|
+
hits,
|
|
2554
|
+
sizeBytes
|
|
2555
|
+
}));
|
|
2556
|
+
}
|
|
2557
|
+
// ── Dependency cascade helpers ────────────────────────────────────────
|
|
2558
|
+
/**
|
|
2559
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
2560
|
+
* pattern that may contain `*` wildcards).
|
|
2561
|
+
*/
|
|
2562
|
+
_matchesGlob(key, pattern) {
|
|
2563
|
+
if (!pattern.includes("*")) return key === pattern;
|
|
2564
|
+
const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
|
|
2565
|
+
return re.test(key);
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
2569
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
2570
|
+
*/
|
|
2571
|
+
_cascadeDependencies(deletedKey) {
|
|
2572
|
+
for (const [pattern, dependents] of this.dependencyIndex) {
|
|
2573
|
+
if (!this._matchesGlob(deletedKey, pattern)) continue;
|
|
2574
|
+
for (const dep of dependents) {
|
|
2575
|
+
if (dep === deletedKey) continue;
|
|
2576
|
+
this.l1.delete(dep);
|
|
2577
|
+
this.disk.delete(dep);
|
|
2578
|
+
void this.publishInvalidation("del", dep);
|
|
2579
|
+
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
2580
|
+
trigger: deletedKey.slice(0, 60),
|
|
2581
|
+
dependent: dep.slice(0, 60)
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
}
|
|
2430
2586
|
// ── Observability ──────────────────────────────────────────────────────────────────
|
|
2431
2587
|
/** Return a full metrics snapshot. */
|
|
2432
2588
|
metrics() {
|
package/dist/index.d.cts
CHANGED
|
@@ -79,12 +79,23 @@ interface SmartCacheEntry {
|
|
|
79
79
|
lastAccess: number;
|
|
80
80
|
/** Eviction priority */
|
|
81
81
|
priority: CachePriority;
|
|
82
|
+
/** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
|
|
83
|
+
ttlMs?: number;
|
|
84
|
+
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
85
|
+
delta?: number;
|
|
82
86
|
}
|
|
83
87
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
84
88
|
interface CacheHit {
|
|
85
89
|
value: unknown;
|
|
86
90
|
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
87
91
|
isStale: boolean;
|
|
92
|
+
/** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
|
|
93
|
+
* without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
|
|
94
|
+
expiresAt: number;
|
|
95
|
+
/** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
|
|
96
|
+
ttlMs?: number;
|
|
97
|
+
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
98
|
+
delta?: number;
|
|
88
99
|
}
|
|
89
100
|
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
90
101
|
* legacy disk files written by older versions may have a JSON string in data) */
|
|
@@ -388,6 +399,13 @@ interface CacheOptions {
|
|
|
388
399
|
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
389
400
|
*/
|
|
390
401
|
ttlJitterFactor?: number;
|
|
402
|
+
/**
|
|
403
|
+
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
404
|
+
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
405
|
+
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
406
|
+
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
407
|
+
*/
|
|
408
|
+
notFoundTtl?: number;
|
|
391
409
|
/**
|
|
392
410
|
* Number of consecutive Redis errors before the circuit opens (stops
|
|
393
411
|
* attempting Redis until the cooldown elapses).
|
|
@@ -435,6 +453,11 @@ declare class CacheService {
|
|
|
435
453
|
private readonly _l1Counters;
|
|
436
454
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
437
455
|
private readonly tagIndex;
|
|
456
|
+
/**
|
|
457
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
458
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
459
|
+
*/
|
|
460
|
+
private readonly dependencyIndex;
|
|
438
461
|
private redis;
|
|
439
462
|
private redisConnecting;
|
|
440
463
|
private readonly cb;
|
|
@@ -495,19 +518,31 @@ declare class CacheService {
|
|
|
495
518
|
* @param cacheKey - Unique key identifying this value
|
|
496
519
|
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
497
520
|
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
498
|
-
* @param opts.priority
|
|
499
|
-
* @param opts.swr
|
|
500
|
-
*
|
|
501
|
-
*
|
|
521
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
522
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
523
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
524
|
+
* is triggered proactively while the caller still receives the
|
|
525
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
526
|
+
* Requires `fetchFn` to be stable across calls.
|
|
527
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
528
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
529
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
530
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
531
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
532
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
502
533
|
*/
|
|
503
534
|
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
504
535
|
priority?: CachePriority;
|
|
505
536
|
swr?: number;
|
|
537
|
+
refreshAhead?: number;
|
|
538
|
+
xfetchBeta?: number;
|
|
539
|
+
notFoundTtl?: number;
|
|
506
540
|
}): Promise<T>;
|
|
507
541
|
private _revalidate;
|
|
508
542
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
509
543
|
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
510
544
|
tags?: string[];
|
|
545
|
+
dependsOn?: string[];
|
|
511
546
|
}): Promise<void>;
|
|
512
547
|
/**
|
|
513
548
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -610,6 +645,7 @@ declare class CacheService {
|
|
|
610
645
|
ttl?: number;
|
|
611
646
|
priority?: CachePriority;
|
|
612
647
|
tags?: string[];
|
|
648
|
+
dependsOn?: string[];
|
|
613
649
|
}>): Promise<void>;
|
|
614
650
|
/**
|
|
615
651
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -680,6 +716,48 @@ declare class CacheService {
|
|
|
680
716
|
maxKB: number;
|
|
681
717
|
};
|
|
682
718
|
};
|
|
719
|
+
/**
|
|
720
|
+
* Write `value` only if the key is not already cached.
|
|
721
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
722
|
+
*
|
|
723
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
724
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
725
|
+
* multiple instances. L1 is populated on success.
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
729
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
730
|
+
*/
|
|
731
|
+
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
732
|
+
/**
|
|
733
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
734
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
735
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
736
|
+
*
|
|
737
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
738
|
+
* collection overhead.
|
|
739
|
+
*
|
|
740
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
741
|
+
*
|
|
742
|
+
* @example
|
|
743
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
744
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
745
|
+
*/
|
|
746
|
+
hotKeys(n?: number): Array<{
|
|
747
|
+
key: string;
|
|
748
|
+
hits: number;
|
|
749
|
+
sizeBytes: number;
|
|
750
|
+
}>;
|
|
751
|
+
/**
|
|
752
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
753
|
+
* pattern that may contain `*` wildcards).
|
|
754
|
+
*/
|
|
755
|
+
private _matchesGlob;
|
|
756
|
+
/**
|
|
757
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
758
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
759
|
+
*/
|
|
760
|
+
private _cascadeDependencies;
|
|
683
761
|
/** Return a full metrics snapshot. */
|
|
684
762
|
metrics(): CacheMetrics;
|
|
685
763
|
/**
|
|
@@ -846,7 +924,7 @@ declare class SmartMemoryCache {
|
|
|
846
924
|
private maybeRebuildBloom;
|
|
847
925
|
private smartEvict;
|
|
848
926
|
get(key: string): CacheHit | null;
|
|
849
|
-
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
|
|
927
|
+
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
|
|
850
928
|
delete(key: string): boolean;
|
|
851
929
|
private keysMatchingPattern;
|
|
852
930
|
deletePattern(pattern: string): number;
|
|
@@ -946,6 +1024,18 @@ declare class SmartMemoryCache {
|
|
|
946
1024
|
bitsSet: number;
|
|
947
1025
|
fillFactor: number;
|
|
948
1026
|
};
|
|
1027
|
+
/**
|
|
1028
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1029
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1030
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
1031
|
+
*
|
|
1032
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
1033
|
+
*/
|
|
1034
|
+
hotKeys(n: number): Array<{
|
|
1035
|
+
key: string;
|
|
1036
|
+
hits: number;
|
|
1037
|
+
sizeBytes: number;
|
|
1038
|
+
}>;
|
|
949
1039
|
}
|
|
950
1040
|
|
|
951
1041
|
/**
|