tricache 0.3.0 → 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 +141 -19
- package/dist/index.cjs +351 -17
- package/dist/index.d.cts +196 -6
- package/dist/index.d.ts +196 -6
- package/dist/index.js +351 -17
- package/package.json +11 -10
- package/src/cache-service.ts +399 -25
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +21 -2
- package/src/types.ts +84 -0
|
@@ -391,7 +391,7 @@ export class SmartMemoryCache {
|
|
|
391
391
|
// skipping unpack. Falls back to decode for entries restored from disk/snapshot.
|
|
392
392
|
const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
|
|
393
393
|
const isStale = entry.staleAt !== undefined && now > entry.staleAt;
|
|
394
|
-
return { value, isStale };
|
|
394
|
+
return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
|
|
395
395
|
}
|
|
396
396
|
|
|
397
397
|
set(
|
|
@@ -400,6 +400,7 @@ export class SmartMemoryCache {
|
|
|
400
400
|
ttlMs: number,
|
|
401
401
|
priority: CachePriority = 2 /* NORMAL */,
|
|
402
402
|
staleAt?: number,
|
|
403
|
+
delta?: number,
|
|
403
404
|
): void {
|
|
404
405
|
// Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
|
|
405
406
|
// "size probe" that was discarded for large payloads (the double-pass).
|
|
@@ -427,7 +428,7 @@ export class SmartMemoryCache {
|
|
|
427
428
|
this.ensureCapacity(cat, size);
|
|
428
429
|
|
|
429
430
|
const now = Date.now();
|
|
430
|
-
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
|
|
431
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
431
432
|
this.bloom.add(key);
|
|
432
433
|
this.maybeRebuildBloom();
|
|
433
434
|
this.totalSize += size;
|
|
@@ -729,4 +730,22 @@ export class SmartMemoryCache {
|
|
|
729
730
|
|
|
730
731
|
bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
|
|
731
732
|
bloomStats() { return this.bloom.stats; }
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
736
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
737
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
738
|
+
*
|
|
739
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
740
|
+
*/
|
|
741
|
+
hotKeys(n: number): Array<{ key: string; hits: number; sizeBytes: number }> {
|
|
742
|
+
const now = Date.now();
|
|
743
|
+
const out: Array<{ key: string; hits: number; sizeBytes: number }> = [];
|
|
744
|
+
for (const [key, entry] of this.cache) {
|
|
745
|
+
if (entry.expiresAt <= now) continue;
|
|
746
|
+
out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
|
|
747
|
+
}
|
|
748
|
+
out.sort((a, b) => b.hits - a.hits);
|
|
749
|
+
return out.slice(0, n);
|
|
750
|
+
}
|
|
732
751
|
}
|
package/src/types.ts
CHANGED
|
@@ -4,6 +4,25 @@
|
|
|
4
4
|
|
|
5
5
|
// ─── Logger ─────────────────────────────────────────────────────────────────
|
|
6
6
|
|
|
7
|
+
// ─── OpenTelemetry tracer interface ──────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
11
|
+
* Pass your existing OTEL tracer; no extra package required.
|
|
12
|
+
*/
|
|
13
|
+
export interface ICacheSpan {
|
|
14
|
+
setAttribute(key: string, value: string | number | boolean): this;
|
|
15
|
+
setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
|
|
16
|
+
end(): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
21
|
+
*/
|
|
22
|
+
export interface ICacheTracer {
|
|
23
|
+
startSpan(name: string): ICacheSpan;
|
|
24
|
+
}
|
|
25
|
+
|
|
7
26
|
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
8
27
|
export interface ILogger {
|
|
9
28
|
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
@@ -82,6 +101,10 @@ export interface SmartCacheEntry {
|
|
|
82
101
|
lastAccess: number;
|
|
83
102
|
/** Eviction priority */
|
|
84
103
|
priority: CachePriority;
|
|
104
|
+
/** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
|
|
105
|
+
ttlMs?: number;
|
|
106
|
+
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
107
|
+
delta?: number;
|
|
85
108
|
}
|
|
86
109
|
|
|
87
110
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
@@ -89,6 +112,13 @@ export interface CacheHit {
|
|
|
89
112
|
value: unknown;
|
|
90
113
|
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
91
114
|
isStale: boolean;
|
|
115
|
+
/** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
|
|
116
|
+
* without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
|
|
117
|
+
expiresAt: number;
|
|
118
|
+
/** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
|
|
119
|
+
ttlMs?: number;
|
|
120
|
+
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
121
|
+
delta?: number;
|
|
92
122
|
}
|
|
93
123
|
|
|
94
124
|
// ─── Disk tier ───────────────────────────────────────────────────────────────
|
|
@@ -172,6 +202,12 @@ export interface CacheMetrics {
|
|
|
172
202
|
skipped: number;
|
|
173
203
|
};
|
|
174
204
|
|
|
205
|
+
/** L2 Redis circuit breaker state */
|
|
206
|
+
l2CircuitBreaker: {
|
|
207
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
208
|
+
state: 'closed' | 'open' | 'half_open';
|
|
209
|
+
};
|
|
210
|
+
|
|
175
211
|
/** OOM guard statistics */
|
|
176
212
|
oom: {
|
|
177
213
|
enabled: boolean;
|
|
@@ -388,4 +424,52 @@ export interface CacheOptions {
|
|
|
388
424
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
389
425
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
390
426
|
metricsIntervalMs?: number;
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
430
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
431
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
432
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
433
|
+
*
|
|
434
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
435
|
+
* dependency required; the interface is structurally compatible.
|
|
436
|
+
*
|
|
437
|
+
* @example
|
|
438
|
+
* import { trace } from '@opentelemetry/api';
|
|
439
|
+
* tracer: trace.getTracer('tricache')
|
|
440
|
+
*/
|
|
441
|
+
tracer?: ICacheTracer;
|
|
442
|
+
|
|
443
|
+
// ── TTL jitter ─────────────────────────────────────────────────────────────
|
|
444
|
+
/**
|
|
445
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
446
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
447
|
+
* the same TTL and expire simultaneously.
|
|
448
|
+
*
|
|
449
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
450
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
451
|
+
*/
|
|
452
|
+
ttlJitterFactor?: number;
|
|
453
|
+
|
|
454
|
+
// ── L2 circuit breaker ─────────────────────────────────────────────────────
|
|
455
|
+
/**
|
|
456
|
+
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
457
|
+
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
458
|
+
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
459
|
+
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
460
|
+
*/
|
|
461
|
+
notFoundTtl?: number;
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
465
|
+
* attempting Redis until the cooldown elapses).
|
|
466
|
+
* Default: `5`.
|
|
467
|
+
*/
|
|
468
|
+
l2CircuitBreakerThreshold?: number;
|
|
469
|
+
/**
|
|
470
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
471
|
+
* (allows a single probe request to test recovery).
|
|
472
|
+
* Default: `30 000` ms (30 s).
|
|
473
|
+
*/
|
|
474
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
391
475
|
}
|