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/dist/index.d.ts
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 };
|
package/dist/index.js
CHANGED
|
@@ -1324,6 +1324,47 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
1324
1324
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
1325
1325
|
};
|
|
1326
1326
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
1327
|
+
var L2CircuitBreaker = class {
|
|
1328
|
+
constructor(threshold, cooldownMs) {
|
|
1329
|
+
this.threshold = threshold;
|
|
1330
|
+
this.cooldownMs = cooldownMs;
|
|
1331
|
+
}
|
|
1332
|
+
threshold;
|
|
1333
|
+
cooldownMs;
|
|
1334
|
+
state = 0 /* CLOSED */;
|
|
1335
|
+
failures = 0;
|
|
1336
|
+
openedAt = 0;
|
|
1337
|
+
/** Call before each Redis attempt. Returns false when the circuit is open. */
|
|
1338
|
+
isAllowed() {
|
|
1339
|
+
if (this.state === 0 /* CLOSED */) return true;
|
|
1340
|
+
if (this.state === 2 /* HALF_OPEN */) return true;
|
|
1341
|
+
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1342
|
+
this.state = 2 /* HALF_OPEN */;
|
|
1343
|
+
return true;
|
|
1344
|
+
}
|
|
1345
|
+
return false;
|
|
1346
|
+
}
|
|
1347
|
+
/** Call on Redis success. */
|
|
1348
|
+
onSuccess() {
|
|
1349
|
+
this.failures = 0;
|
|
1350
|
+
this.state = 0 /* CLOSED */;
|
|
1351
|
+
}
|
|
1352
|
+
/** Call on Redis failure. */
|
|
1353
|
+
onFailure() {
|
|
1354
|
+
this.failures++;
|
|
1355
|
+
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1356
|
+
this.state = 1 /* OPEN */;
|
|
1357
|
+
this.openedAt = Date.now();
|
|
1358
|
+
this.failures = 0;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
get isOpen() {
|
|
1362
|
+
return this.state === 1 /* OPEN */;
|
|
1363
|
+
}
|
|
1364
|
+
get currentState() {
|
|
1365
|
+
return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1327
1368
|
function inferPriority(cacheKey) {
|
|
1328
1369
|
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
1329
1370
|
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
@@ -1348,6 +1389,7 @@ var CacheService = class _CacheService {
|
|
|
1348
1389
|
tagIndex = /* @__PURE__ */ new Map();
|
|
1349
1390
|
redis = null;
|
|
1350
1391
|
redisConnecting = null;
|
|
1392
|
+
cb;
|
|
1351
1393
|
snapshotLoaded = false;
|
|
1352
1394
|
cleanupInterval = null;
|
|
1353
1395
|
oomInterval = null;
|
|
@@ -1422,8 +1464,13 @@ var CacheService = class _CacheService {
|
|
|
1422
1464
|
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1423
1465
|
staleIfError: options.staleIfError ?? 0,
|
|
1424
1466
|
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1425
|
-
instanceName: options.instanceName ?? ""
|
|
1467
|
+
instanceName: options.instanceName ?? "",
|
|
1468
|
+
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1469
|
+
tracer: options.tracer
|
|
1426
1470
|
};
|
|
1471
|
+
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1472
|
+
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
1473
|
+
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
1427
1474
|
this.disk = new DiskTier({
|
|
1428
1475
|
dir: this.opts.diskCacheDir,
|
|
1429
1476
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -1544,6 +1591,22 @@ var CacheService = class _CacheService {
|
|
|
1544
1591
|
nk(key) {
|
|
1545
1592
|
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
1546
1593
|
}
|
|
1594
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
1595
|
+
_jitterTtl(ttlMs) {
|
|
1596
|
+
const j = this.opts.ttlJitterFactor;
|
|
1597
|
+
if (j === 0) return ttlMs;
|
|
1598
|
+
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
1599
|
+
}
|
|
1600
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
1601
|
+
_startSpan(name) {
|
|
1602
|
+
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
1603
|
+
return { setAttribute() {
|
|
1604
|
+
return this;
|
|
1605
|
+
}, setStatus() {
|
|
1606
|
+
return this;
|
|
1607
|
+
}, end() {
|
|
1608
|
+
} };
|
|
1609
|
+
}
|
|
1547
1610
|
initBackplane() {
|
|
1548
1611
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1549
1612
|
if (this.subClient) return;
|
|
@@ -1605,7 +1668,7 @@ var CacheService = class _CacheService {
|
|
|
1605
1668
|
}
|
|
1606
1669
|
}
|
|
1607
1670
|
async getRedis() {
|
|
1608
|
-
if (this.
|
|
1671
|
+
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
1609
1672
|
if (this.redisConnecting) return this.redisConnecting;
|
|
1610
1673
|
this.redisConnecting = (async () => {
|
|
1611
1674
|
try {
|
|
@@ -1629,10 +1692,12 @@ var CacheService = class _CacheService {
|
|
|
1629
1692
|
client.once("error", reject);
|
|
1630
1693
|
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1631
1694
|
});
|
|
1695
|
+
this.cb.onSuccess();
|
|
1632
1696
|
this.redis = client;
|
|
1633
1697
|
this.redisConnecting = null;
|
|
1634
1698
|
return client;
|
|
1635
1699
|
} catch (err) {
|
|
1700
|
+
this.cb.onFailure();
|
|
1636
1701
|
this.redisConnecting = null;
|
|
1637
1702
|
throw err;
|
|
1638
1703
|
}
|
|
@@ -1719,6 +1784,8 @@ var CacheService = class _CacheService {
|
|
|
1719
1784
|
* instantly while a background refresh runs. Default: 0 (disabled).
|
|
1720
1785
|
*/
|
|
1721
1786
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
1787
|
+
const span = this._startSpan("tricache.get");
|
|
1788
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1722
1789
|
const k = this.nk(cacheKey);
|
|
1723
1790
|
this.counters.gets++;
|
|
1724
1791
|
const l1Hit = this.l1.get(k);
|
|
@@ -1738,24 +1805,28 @@ var CacheService = class _CacheService {
|
|
|
1738
1805
|
this.logger.debug("L1 hit");
|
|
1739
1806
|
}
|
|
1740
1807
|
this.counters.l1Hits++;
|
|
1808
|
+
span.setAttribute("cache.hit", "l1").end();
|
|
1741
1809
|
return l1Hit.value;
|
|
1742
1810
|
}
|
|
1743
|
-
const ttlMs = ttlSeconds * 1e3;
|
|
1811
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1744
1812
|
const swrGraceMs = (opts.swr ?? 0) * 1e3;
|
|
1745
1813
|
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
1746
1814
|
if (!this._redisDisabled) {
|
|
1747
1815
|
try {
|
|
1748
1816
|
const client = await this.getRedis();
|
|
1749
1817
|
const raw = await client.get(k);
|
|
1818
|
+
this.cb.onSuccess();
|
|
1750
1819
|
if (raw) {
|
|
1751
1820
|
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
1752
1821
|
const parsed = JSON.parse(decrypted);
|
|
1753
1822
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
1754
1823
|
this.counters.l2Hits++;
|
|
1755
1824
|
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
1825
|
+
span.setAttribute("cache.hit", "l2").end();
|
|
1756
1826
|
return parsed;
|
|
1757
1827
|
}
|
|
1758
1828
|
} catch (err) {
|
|
1829
|
+
this.cb.onFailure();
|
|
1759
1830
|
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
1760
1831
|
}
|
|
1761
1832
|
}
|
|
@@ -1770,14 +1841,17 @@ var CacheService = class _CacheService {
|
|
|
1770
1841
|
if (l1Check !== null) {
|
|
1771
1842
|
this.counters.diskHits++;
|
|
1772
1843
|
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
1844
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
1773
1845
|
return l1Check.value;
|
|
1774
1846
|
}
|
|
1775
1847
|
}
|
|
1776
1848
|
}
|
|
1849
|
+
span.setAttribute("cache.hit", "miss");
|
|
1777
1850
|
const existing = this.inflight.get(k);
|
|
1778
1851
|
if (existing) {
|
|
1779
1852
|
this.counters.stampedes++;
|
|
1780
1853
|
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
1854
|
+
span.end();
|
|
1781
1855
|
return existing;
|
|
1782
1856
|
}
|
|
1783
1857
|
const fetchPromise = (async () => {
|
|
@@ -1792,9 +1866,11 @@ var CacheService = class _CacheService {
|
|
|
1792
1866
|
const client = await this.getRedis();
|
|
1793
1867
|
const serialized = JSON.stringify(data);
|
|
1794
1868
|
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1795
|
-
await client.setex(k,
|
|
1869
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
|
|
1870
|
+
this.cb.onSuccess();
|
|
1796
1871
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
1797
1872
|
} catch {
|
|
1873
|
+
this.cb.onFailure();
|
|
1798
1874
|
this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
|
|
1799
1875
|
}
|
|
1800
1876
|
} else {
|
|
@@ -1803,6 +1879,7 @@ var CacheService = class _CacheService {
|
|
|
1803
1879
|
return data;
|
|
1804
1880
|
} finally {
|
|
1805
1881
|
this.inflight.delete(k);
|
|
1882
|
+
span.end();
|
|
1806
1883
|
}
|
|
1807
1884
|
})();
|
|
1808
1885
|
this.inflight.set(k, fetchPromise);
|
|
@@ -1841,7 +1918,9 @@ var CacheService = class _CacheService {
|
|
|
1841
1918
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1842
1919
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1843
1920
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1844
|
-
const
|
|
1921
|
+
const span = this._startSpan("tricache.set");
|
|
1922
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1923
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1845
1924
|
const p = priority ?? inferPriority(cacheKey);
|
|
1846
1925
|
const k = this.nk(cacheKey);
|
|
1847
1926
|
this.counters.sets++;
|
|
@@ -1866,7 +1945,9 @@ var CacheService = class _CacheService {
|
|
|
1866
1945
|
pl.expire(tagKey, ttlSeconds + 3600);
|
|
1867
1946
|
}
|
|
1868
1947
|
await pl.exec();
|
|
1948
|
+
this.cb.onSuccess();
|
|
1869
1949
|
} catch {
|
|
1950
|
+
this.cb.onFailure();
|
|
1870
1951
|
}
|
|
1871
1952
|
}
|
|
1872
1953
|
}
|
|
@@ -1875,12 +1956,15 @@ var CacheService = class _CacheService {
|
|
|
1875
1956
|
const client = await this.getRedis();
|
|
1876
1957
|
const s = JSON.stringify(data);
|
|
1877
1958
|
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1878
|
-
await client.setex(k,
|
|
1959
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
1960
|
+
this.cb.onSuccess();
|
|
1879
1961
|
} catch (err) {
|
|
1962
|
+
this.cb.onFailure();
|
|
1880
1963
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
1881
1964
|
}
|
|
1882
1965
|
}
|
|
1883
1966
|
void this.publishInvalidation("del", k);
|
|
1967
|
+
span.end();
|
|
1884
1968
|
}
|
|
1885
1969
|
/**
|
|
1886
1970
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -1890,6 +1974,8 @@ var CacheService = class _CacheService {
|
|
|
1890
1974
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
1891
1975
|
*/
|
|
1892
1976
|
async delete(cacheKey) {
|
|
1977
|
+
const span = this._startSpan("tricache.delete");
|
|
1978
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1893
1979
|
const isPattern = cacheKey.includes("*");
|
|
1894
1980
|
const k = this.nk(cacheKey);
|
|
1895
1981
|
this.counters.deletes++;
|
|
@@ -1914,11 +2000,14 @@ var CacheService = class _CacheService {
|
|
|
1914
2000
|
} else {
|
|
1915
2001
|
await client.del(k);
|
|
1916
2002
|
}
|
|
2003
|
+
this.cb.onSuccess();
|
|
1917
2004
|
} catch (err) {
|
|
2005
|
+
this.cb.onFailure();
|
|
1918
2006
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
1919
2007
|
}
|
|
1920
2008
|
}
|
|
1921
2009
|
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
2010
|
+
span.end();
|
|
1922
2011
|
}
|
|
1923
2012
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
1924
2013
|
/**
|
|
@@ -2117,6 +2206,92 @@ var CacheService = class _CacheService {
|
|
|
2117
2206
|
}
|
|
2118
2207
|
return result;
|
|
2119
2208
|
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Batch write — set multiple entries in a single call.
|
|
2211
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
2212
|
+
*
|
|
2213
|
+
* @example
|
|
2214
|
+
* await cache.mset({
|
|
2215
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
2216
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
2217
|
+
* });
|
|
2218
|
+
*/
|
|
2219
|
+
async mset(entries) {
|
|
2220
|
+
const keys = Object.keys(entries);
|
|
2221
|
+
await Promise.all(keys.map((key) => {
|
|
2222
|
+
const { value, ttl = 300, priority, tags } = entries[key];
|
|
2223
|
+
return this.set(key, value, ttl, priority, tags ? { tags } : void 0);
|
|
2224
|
+
}));
|
|
2225
|
+
}
|
|
2226
|
+
/**
|
|
2227
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
2228
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
2229
|
+
*
|
|
2230
|
+
* @example
|
|
2231
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
2232
|
+
*/
|
|
2233
|
+
async mdel(keys) {
|
|
2234
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
2235
|
+
}
|
|
2236
|
+
/**
|
|
2237
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
2238
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
2239
|
+
* the local snapshot is unavailable or too stale.
|
|
2240
|
+
*
|
|
2241
|
+
* Returns the number of keys loaded into L1.
|
|
2242
|
+
*
|
|
2243
|
+
* @example
|
|
2244
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
2245
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
2246
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
2247
|
+
*/
|
|
2248
|
+
async warmFromL2(pattern) {
|
|
2249
|
+
if (this._redisDisabled) return 0;
|
|
2250
|
+
try {
|
|
2251
|
+
const client = await this.getRedis();
|
|
2252
|
+
const nsPattern = this.nk(pattern);
|
|
2253
|
+
const matchedKeys = [];
|
|
2254
|
+
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
2255
|
+
await new Promise((resolve, reject) => {
|
|
2256
|
+
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
2257
|
+
stream.on("end", resolve);
|
|
2258
|
+
stream.on("error", reject);
|
|
2259
|
+
});
|
|
2260
|
+
if (matchedKeys.length === 0) {
|
|
2261
|
+
this.cb.onSuccess();
|
|
2262
|
+
return 0;
|
|
2263
|
+
}
|
|
2264
|
+
const pl = client.pipeline();
|
|
2265
|
+
for (const k of matchedKeys) pl.get(k);
|
|
2266
|
+
const results = await pl.exec();
|
|
2267
|
+
this.cb.onSuccess();
|
|
2268
|
+
let loaded = 0;
|
|
2269
|
+
const now = Date.now();
|
|
2270
|
+
for (let i = 0; i < matchedKeys.length; i++) {
|
|
2271
|
+
const [err, raw] = results[i];
|
|
2272
|
+
if (err || raw == null) continue;
|
|
2273
|
+
try {
|
|
2274
|
+
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2275
|
+
const parsed = JSON.parse(decrypted);
|
|
2276
|
+
const remainingMs = 10 * 60 * 1e3;
|
|
2277
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
2278
|
+
loaded++;
|
|
2279
|
+
} catch {
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
void now;
|
|
2283
|
+
this.logger.info("warmFromL2 complete", {
|
|
2284
|
+
pattern,
|
|
2285
|
+
matched: matchedKeys.length,
|
|
2286
|
+
loaded
|
|
2287
|
+
});
|
|
2288
|
+
return loaded;
|
|
2289
|
+
} catch (err) {
|
|
2290
|
+
this.cb.onFailure();
|
|
2291
|
+
this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
|
|
2292
|
+
return 0;
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2120
2295
|
/**
|
|
2121
2296
|
* Invalidate all keys associated with a tag.
|
|
2122
2297
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -2250,6 +2425,9 @@ var CacheService = class _CacheService {
|
|
|
2250
2425
|
received: c.invReceived,
|
|
2251
2426
|
skipped: c.invSkipped
|
|
2252
2427
|
},
|
|
2428
|
+
l2CircuitBreaker: {
|
|
2429
|
+
state: this.cb.currentState
|
|
2430
|
+
},
|
|
2253
2431
|
oom: {
|
|
2254
2432
|
enabled: this.opts.oomProtection,
|
|
2255
2433
|
evictions: c.oomEvictions,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"license": "MIT",
|
|
21
|
+
"packageManager": "pnpm@11.0.9",
|
|
21
22
|
"type": "module",
|
|
22
23
|
"main": "./dist/index.js",
|
|
23
24
|
"module": "./dist/index.js",
|
|
@@ -35,6 +36,14 @@
|
|
|
35
36
|
"README.md",
|
|
36
37
|
"LICENSE"
|
|
37
38
|
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
41
|
+
"dev": "tsup src/index.ts --format esm,cjs --dts --watch",
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:watch": "vitest",
|
|
45
|
+
"bench": "node --import tsx/esm bench/benchmark.ts"
|
|
46
|
+
},
|
|
38
47
|
"dependencies": {
|
|
39
48
|
"ioredis": "^5.3.2",
|
|
40
49
|
"msgpackr": "^2.0.1"
|
|
@@ -53,13 +62,5 @@
|
|
|
53
62
|
"repository": {
|
|
54
63
|
"type": "git",
|
|
55
64
|
"url": "git+https://github.com/Kareem411/TriCache.git"
|
|
56
|
-
},
|
|
57
|
-
"scripts": {
|
|
58
|
-
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
59
|
-
"dev": "tsup src/index.ts --format esm,cjs --dts --watch",
|
|
60
|
-
"typecheck": "tsc --noEmit",
|
|
61
|
-
"test": "vitest run",
|
|
62
|
-
"test:watch": "vitest",
|
|
63
|
-
"bench": "node --import tsx/esm bench/benchmark.ts"
|
|
64
65
|
}
|
|
65
|
-
}
|
|
66
|
+
}
|