tricache 0.6.3 → 0.6.5
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/dist/{chunk-F24NEZGQ.js → chunk-IB4HMBA2.js} +0 -8
- package/dist/index.cjs +25 -23
- package/dist/index.d.ts +16 -5
- package/dist/index.js +27 -25
- package/dist/serialize-worker.js +1 -1
- package/package.json +2 -1
- package/src/cache-service.ts +1 -1
- package/src/disk-tier.ts +5 -3
- package/src/smart-memory-cache.ts +35 -14
- package/src/types.ts +7 -0
- package/src/worker-pool.ts +3 -8
- package/dist/index.d.cts +0 -1559
- package/dist/serialize-worker.d.cts +0 -2
package/dist/index.d.cts
DELETED
|
@@ -1,1559 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* tricache — shared types and interfaces
|
|
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
|
-
}
|
|
22
|
-
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
23
|
-
interface ILogger {
|
|
24
|
-
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
25
|
-
info(msg: string, meta?: Record<string, unknown>): void;
|
|
26
|
-
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
27
|
-
error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
|
|
28
|
-
}
|
|
29
|
-
/** Default no-op logger — swap out via CacheService options */
|
|
30
|
-
declare const consoleLogger: ILogger;
|
|
31
|
-
/**
|
|
32
|
-
* Reason passed to the `onEviction` callback.
|
|
33
|
-
* - `'capacity'` — L1 over-capacity; evicted during a `set()` call
|
|
34
|
-
* - `'category'` — Per-category limit exceeded
|
|
35
|
-
* - `'rebalance'` — `cache.rebalance()` was called
|
|
36
|
-
* - `'oom'` — OOM guard emergency eviction
|
|
37
|
-
* - `'ttl'` — Entry expired during periodic cleanup
|
|
38
|
-
* - `'manual'` — Explicit `cache.delete()` call
|
|
39
|
-
*/
|
|
40
|
-
type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
|
|
41
|
-
/** Per-tier latency returned by `cache.ping()`. */
|
|
42
|
-
interface CachePingResult {
|
|
43
|
-
/** L1 RAM check latency in milliseconds */
|
|
44
|
-
l1: number;
|
|
45
|
-
/** L1.5 disk stats access in milliseconds */
|
|
46
|
-
disk: number;
|
|
47
|
-
/** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
|
|
48
|
-
l2: number | null;
|
|
49
|
-
}
|
|
50
|
-
/** Priority levels for L1 eviction — higher = less likely to be evicted */
|
|
51
|
-
declare enum CachePriority {
|
|
52
|
-
LOW = 1,// Easily regenerated (analytics, reports)
|
|
53
|
-
NORMAL = 2,// General data
|
|
54
|
-
HIGH = 3,// Frequently accessed (profiles, config)
|
|
55
|
-
CRITICAL = 4
|
|
56
|
-
}
|
|
57
|
-
/** Internal representation of a single cache entry in the L1 Map */
|
|
58
|
-
interface SmartCacheEntry {
|
|
59
|
-
/** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
|
|
60
|
-
data: Buffer;
|
|
61
|
-
/**
|
|
62
|
-
* Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
|
|
63
|
-
* Undefined for entries restored from disk/snapshot (populated lazily on first access).
|
|
64
|
-
* NOTE: returned by reference — callers should treat the value as immutable.
|
|
65
|
-
*/
|
|
66
|
-
value?: unknown;
|
|
67
|
-
/** always true for entries written by the current code;
|
|
68
|
-
* may be false in legacy snapshots/disk files — handled transparently on import */
|
|
69
|
-
isCompressed: boolean;
|
|
70
|
-
/** Hard expiry — entry is deleted after this timestamp */
|
|
71
|
-
expiresAt: number;
|
|
72
|
-
/** SWR soft expiry — serve stale + revalidate in background when past this */
|
|
73
|
-
staleAt?: number;
|
|
74
|
-
/** Exact byte size of the stored value */
|
|
75
|
-
size: number;
|
|
76
|
-
/** Access count (LFU numerator) */
|
|
77
|
-
hits: number;
|
|
78
|
-
/** Last access timestamp (LRU comparator) */
|
|
79
|
-
lastAccess: number;
|
|
80
|
-
/** Eviction priority */
|
|
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;
|
|
86
|
-
}
|
|
87
|
-
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
88
|
-
interface CacheHit {
|
|
89
|
-
value: unknown;
|
|
90
|
-
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
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;
|
|
99
|
-
/** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
|
|
100
|
-
* reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
|
|
101
|
-
fetchedAt?: number;
|
|
102
|
-
}
|
|
103
|
-
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
104
|
-
* legacy disk files written by older versions may have a JSON string in data) */
|
|
105
|
-
interface DiskCacheEntry {
|
|
106
|
-
data: string | Buffer | Uint8Array;
|
|
107
|
-
isCompressed: boolean;
|
|
108
|
-
expiresAt: number;
|
|
109
|
-
staleAt?: number;
|
|
110
|
-
size: number;
|
|
111
|
-
hits: number;
|
|
112
|
-
lastAccess: number;
|
|
113
|
-
priority: number;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Snapshot of runtime metrics for a CacheService instance.
|
|
117
|
-
* Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
|
|
118
|
-
* Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
|
|
119
|
-
*/
|
|
120
|
-
interface CacheMetrics {
|
|
121
|
-
/** Configured namespace (empty string = no namespace) */
|
|
122
|
-
namespace: string;
|
|
123
|
-
/** Milliseconds since the CacheService instance was constructed */
|
|
124
|
-
uptimeMs: number;
|
|
125
|
-
gets: {
|
|
126
|
-
total: number;
|
|
127
|
-
l1Hits: number;
|
|
128
|
-
/** Fraction of gets served from L1 RAM cache (0–1) */
|
|
129
|
-
l1HitRate: number;
|
|
130
|
-
diskHits: number;
|
|
131
|
-
/** Fraction of gets served from L1.5 disk tier (0–1) */
|
|
132
|
-
diskHitRate: number;
|
|
133
|
-
l2Hits: number;
|
|
134
|
-
/** Fraction of gets served from L2 Redis (0–1) */
|
|
135
|
-
l2HitRate: number;
|
|
136
|
-
/** fetchFn calls (cache misses that fell through to the DB) */
|
|
137
|
-
fetches: number;
|
|
138
|
-
/** Fraction of gets that called fetchFn (0–1) */
|
|
139
|
-
fetchRate: number;
|
|
140
|
-
/** Concurrent get() calls deduplicated by the stampede guard */
|
|
141
|
-
stampedePrevented: number;
|
|
142
|
-
};
|
|
143
|
-
sets: {
|
|
144
|
-
total: number;
|
|
145
|
-
};
|
|
146
|
-
deletes: {
|
|
147
|
-
total: number;
|
|
148
|
-
};
|
|
149
|
-
revalidations: {
|
|
150
|
-
total: number;
|
|
151
|
-
};
|
|
152
|
-
bloom: {
|
|
153
|
-
/** Total bloom-filter checks (get() calls that passed prefix filter) */
|
|
154
|
-
checksTotal: number;
|
|
155
|
-
/**
|
|
156
|
-
* Times the filter said "might contain" but the key was absent in L1.
|
|
157
|
-
* A high rate suggests the bloom filter capacity needs increasing.
|
|
158
|
-
*/
|
|
159
|
-
falsePositives: number;
|
|
160
|
-
/** falsePositives / checksTotal (0–1; ideal < 0.01) */
|
|
161
|
-
falsePositiveRate: number;
|
|
162
|
-
};
|
|
163
|
-
compression: {
|
|
164
|
-
entriesCompressed: number;
|
|
165
|
-
entriesUncompressed: number;
|
|
166
|
-
/** Approximate bytes saved by msgpackr vs raw JSON */
|
|
167
|
-
bytesSaved: number;
|
|
168
|
-
};
|
|
169
|
-
/** Pub/Sub invalidation backplane statistics */
|
|
170
|
-
backplane: {
|
|
171
|
-
enabled: boolean;
|
|
172
|
-
/** Invalidation messages published to other instances */
|
|
173
|
-
sent: number;
|
|
174
|
-
/** Invalidation messages received from other instances */
|
|
175
|
-
received: number;
|
|
176
|
-
/** Own messages silently skipped (prevents double-eviction) */
|
|
177
|
-
skipped: number;
|
|
178
|
-
};
|
|
179
|
-
/** L2 Redis circuit breaker state */
|
|
180
|
-
l2CircuitBreaker: {
|
|
181
|
-
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
182
|
-
state: 'closed' | 'open' | 'half_open';
|
|
183
|
-
};
|
|
184
|
-
/** OOM guard statistics */
|
|
185
|
-
oom: {
|
|
186
|
-
enabled: boolean;
|
|
187
|
-
/** Number of emergency L1 eviction rounds triggered */
|
|
188
|
-
evictions: number;
|
|
189
|
-
/** Timestamp of the most recent OOM eviction, or null */
|
|
190
|
-
lastTriggeredAt: number | null;
|
|
191
|
-
};
|
|
192
|
-
l1: {
|
|
193
|
-
entries: number;
|
|
194
|
-
sizeBytes: number;
|
|
195
|
-
maxBytes: number;
|
|
196
|
-
};
|
|
197
|
-
disk: {
|
|
198
|
-
files: number;
|
|
199
|
-
sizeKB: number;
|
|
200
|
-
maxKB: number;
|
|
201
|
-
disabled: boolean;
|
|
202
|
-
};
|
|
203
|
-
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
204
|
-
adaptiveTtl?: {
|
|
205
|
-
enabled: true;
|
|
206
|
-
/** Number of unique keys currently tracked in the latency ring buffers */
|
|
207
|
-
trackedKeys: number;
|
|
208
|
-
/**
|
|
209
|
-
* Top-20 slowest keys by p95 fetch latency, sorted descending.
|
|
210
|
-
* Keys are shown without the instance namespace prefix.
|
|
211
|
-
* Only keys with ≥ 5 recorded samples appear here.
|
|
212
|
-
*/
|
|
213
|
-
slowestKeys: Array<{
|
|
214
|
-
key: string;
|
|
215
|
-
p95Ms: number;
|
|
216
|
-
adaptedTtlSec: number;
|
|
217
|
-
}>;
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
/** Per-category memory limits for L1 */
|
|
221
|
-
interface CategoryLimit {
|
|
222
|
-
maxEntries: number;
|
|
223
|
-
maxSizeBytes: number;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Options accepted by CacheService.create()
|
|
227
|
-
*
|
|
228
|
-
* All fields are optional — sensible defaults are used when omitted.
|
|
229
|
-
*/
|
|
230
|
-
interface CacheOptions {
|
|
231
|
-
/**
|
|
232
|
-
* Plug in your own logger (pino, winston, bunyan, …).
|
|
233
|
-
* Defaults to a minimal console logger that only prints warn/error.
|
|
234
|
-
*/
|
|
235
|
-
logger?: ILogger;
|
|
236
|
-
/** Max total bytes held in L1 RAM cache. Default: 200 MB */
|
|
237
|
-
l1MaxBytes?: number;
|
|
238
|
-
/** Max total entries in L1. Default: 2000 */
|
|
239
|
-
l1MaxEntries?: number;
|
|
240
|
-
/**
|
|
241
|
-
* Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
|
|
242
|
-
* before the hard limit is reached. Range: 0–1. Default: 0.9.
|
|
243
|
-
* Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
|
|
244
|
-
*/
|
|
245
|
-
l1EvictionWatermark?: number;
|
|
246
|
-
/**
|
|
247
|
-
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
248
|
-
* Merged over the built-in defaults.
|
|
249
|
-
*/
|
|
250
|
-
categoryLimits?: Record<string, CategoryLimit>;
|
|
251
|
-
/**
|
|
252
|
-
* Key prefixes that are never written to disk snapshots or the disk tier.
|
|
253
|
-
* Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
|
|
254
|
-
*/
|
|
255
|
-
forbiddenSnapshotPrefixes?: string[];
|
|
256
|
-
/** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
|
|
257
|
-
diskCacheDir?: string;
|
|
258
|
-
/** Max total bytes for the disk tier. Default: 500 MB */
|
|
259
|
-
diskMaxBytes?: number;
|
|
260
|
-
/** Max bytes for a single disk entry. Default: 10 MB */
|
|
261
|
-
diskEntryMaxBytes?: number;
|
|
262
|
-
/**
|
|
263
|
-
* Redis/Valkey hostname (no `redis://` prefix).
|
|
264
|
-
* Falls back to the `REDIS_HOST` environment variable.
|
|
265
|
-
* When neither is provided, L2 is disabled.
|
|
266
|
-
*/
|
|
267
|
-
redisHost?: string;
|
|
268
|
-
/** Redis port. Default: 6379 */
|
|
269
|
-
redisPort?: number;
|
|
270
|
-
/**
|
|
271
|
-
* Whether to enable TLS for the Redis connection. Default: true in production,
|
|
272
|
-
* false otherwise.
|
|
273
|
-
*/
|
|
274
|
-
redisTls?: boolean;
|
|
275
|
-
/**
|
|
276
|
-
* Set to `true` to disable L2 Redis entirely (e.g. when running single-process
|
|
277
|
-
* services that don't need distributed caching). Default: false in production,
|
|
278
|
-
* true in development.
|
|
279
|
-
*/
|
|
280
|
-
disableRedis?: boolean;
|
|
281
|
-
/**
|
|
282
|
-
* Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
|
|
283
|
-
* disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
|
|
284
|
-
* If not provided in production, a warning is logged and data is stored plaintext.
|
|
285
|
-
*/
|
|
286
|
-
encryptionKey?: string;
|
|
287
|
-
/**
|
|
288
|
-
* Encryption algorithm used for L2 (Redis) values and disk-tier files.
|
|
289
|
-
* - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
|
|
290
|
-
* - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
|
|
291
|
-
* - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
|
|
292
|
-
* Any key length (minimum 16 bytes recommended).
|
|
293
|
-
* Use for dev environments or non-sensitive data only.
|
|
294
|
-
* Default: `'aes-256-gcm'`
|
|
295
|
-
*/
|
|
296
|
-
encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
297
|
-
/**
|
|
298
|
-
* Fallback encryption key for zero-downtime key rotation.
|
|
299
|
-
* On every read, tricache tries the current `encryptionKey` first.
|
|
300
|
-
* If decryption fails (wrong key), it retries with `previousEncryptionKey`.
|
|
301
|
-
* All writes always use the current `encryptionKey`.
|
|
302
|
-
* Remove this field once you are confident all data has been re-encrypted.
|
|
303
|
-
*/
|
|
304
|
-
previousEncryptionKey?: string;
|
|
305
|
-
/** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
|
|
306
|
-
previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
307
|
-
/**
|
|
308
|
-
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
309
|
-
* on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
|
|
310
|
-
*/
|
|
311
|
-
snapshotPath?: string;
|
|
312
|
-
/**
|
|
313
|
-
* Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
|
|
314
|
-
*/
|
|
315
|
-
snapshotMaxAgeMs?: number;
|
|
316
|
-
/**
|
|
317
|
-
* Optional namespace prefix for all cache keys.
|
|
318
|
-
*
|
|
319
|
-
* When set, every key is transparently stored as `${namespace}:${key}` in
|
|
320
|
-
* L1, L1.5 (disk), and L2 (Redis). This enables:
|
|
321
|
-
* - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
|
|
322
|
-
* — tenants sharing the same Redis instance or disk dir are fully isolated.
|
|
323
|
-
* - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
|
|
324
|
-
* - **Service-level scoping**: microservices sharing one Redis without key collisions.
|
|
325
|
-
*
|
|
326
|
-
* Consumers never see the prefix — `get('user:1')` behaves identically
|
|
327
|
-
* whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
|
|
328
|
-
* scope to the namespace.
|
|
329
|
-
*
|
|
330
|
-
* The process-level singleton, disk cache directory, and cold-start snapshot
|
|
331
|
-
* path are all scoped per namespace, so two `CacheService.create()` calls
|
|
332
|
-
* with different namespaces return completely independent instances.
|
|
333
|
-
*
|
|
334
|
-
* Default: `''` (no prefix)
|
|
335
|
-
*/
|
|
336
|
-
namespace?: string;
|
|
337
|
-
/**
|
|
338
|
-
* Seconds to extend a stale SWR entry's life when background revalidation fails.
|
|
339
|
-
* Without this, a failed revalidation leaves the entry stale until its hard TTL
|
|
340
|
-
* expires, after which the next caller blocks. With `staleIfError`, tricache bumps
|
|
341
|
-
* the expiry by this many seconds on every failed revalidation, keeping the stale
|
|
342
|
-
* value available while the underlying service is degraded.
|
|
343
|
-
* Default: `0` (disabled — entry expires normally on revalidation failure).
|
|
344
|
-
*/
|
|
345
|
-
staleIfError?: number;
|
|
346
|
-
/**
|
|
347
|
-
* Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
|
|
348
|
-
* Useful for diagnosing cache pressure and tuning `categoryLimits`.
|
|
349
|
-
*/
|
|
350
|
-
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
351
|
-
/**
|
|
352
|
-
* Human-readable name for this CacheService instance. Added as an `instance` label
|
|
353
|
-
* to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
|
|
354
|
-
* Required when multiple CacheService instances share a process — without it,
|
|
355
|
-
* metric names from different instances collide.
|
|
356
|
-
* Default: `''` (no label).
|
|
357
|
-
*/
|
|
358
|
-
instanceName?: string;
|
|
359
|
-
/**
|
|
360
|
-
* Controls whether writes are propagated to L2 (Redis).
|
|
361
|
-
* - `'read-write'` (default): read from and write to L2.
|
|
362
|
-
* - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
|
|
363
|
-
* Use for shared read replicas or external Redis clusters you do not own.
|
|
364
|
-
*/
|
|
365
|
-
l2WriteMode?: 'read-write' | 'read-only';
|
|
366
|
-
/**
|
|
367
|
-
* Enable Redis Pub/Sub invalidation backplane so every running instance
|
|
368
|
-
* evicts a key from its L1 when any peer calls `set()` or `delete()`.
|
|
369
|
-
*
|
|
370
|
-
* Gives you sub-microsecond in-process cache speed with cluster-wide
|
|
371
|
-
* consistency across all your app servers.
|
|
372
|
-
*
|
|
373
|
-
* Default: `true` (auto-activates when Redis is available).
|
|
374
|
-
* Set to `false` for single-process services or eventual-consistency scenarios.
|
|
375
|
-
*/
|
|
376
|
-
invalidationBackplane?: boolean;
|
|
377
|
-
/**
|
|
378
|
-
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
379
|
-
* `oomHeapThreshold`, a fraction of the coldest L1 entries are
|
|
380
|
-
* emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
|
|
381
|
-
* Docker/Kubernetes containers with tight memory limits.
|
|
382
|
-
*
|
|
383
|
-
* Default: `true`
|
|
384
|
-
*/
|
|
385
|
-
oomProtection?: boolean;
|
|
386
|
-
/**
|
|
387
|
-
* Heap-used / heap-total ratio that triggers emergency eviction.
|
|
388
|
-
* Default: `0.85` (85 %)
|
|
389
|
-
*/
|
|
390
|
-
oomHeapThreshold?: number;
|
|
391
|
-
/** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
|
|
392
|
-
oomCheckIntervalMs?: number;
|
|
393
|
-
/** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
|
|
394
|
-
oomEvictPercent?: number;
|
|
395
|
-
/**
|
|
396
|
-
* Callback invoked periodically with a `CacheMetrics` snapshot.
|
|
397
|
-
* Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
|
|
398
|
-
*
|
|
399
|
-
* @example
|
|
400
|
-
* onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
|
|
401
|
-
*/
|
|
402
|
-
onMetrics?: (metrics: CacheMetrics) => void;
|
|
403
|
-
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
404
|
-
metricsIntervalMs?: number;
|
|
405
|
-
/**
|
|
406
|
-
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
407
|
-
* `delete()` are each wrapped in a span with attributes:
|
|
408
|
-
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
409
|
-
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
410
|
-
*
|
|
411
|
-
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
412
|
-
* dependency required; the interface is structurally compatible.
|
|
413
|
-
*
|
|
414
|
-
* @example
|
|
415
|
-
* import { trace } from '@opentelemetry/api';
|
|
416
|
-
* tracer: trace.getTracer('tricache')
|
|
417
|
-
*/
|
|
418
|
-
tracer?: ICacheTracer;
|
|
419
|
-
/**
|
|
420
|
-
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
421
|
-
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
422
|
-
* the same TTL and expire simultaneously.
|
|
423
|
-
*
|
|
424
|
-
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
425
|
-
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
426
|
-
*/
|
|
427
|
-
ttlJitterFactor?: number;
|
|
428
|
-
/**
|
|
429
|
-
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
430
|
-
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
431
|
-
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
432
|
-
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
433
|
-
*/
|
|
434
|
-
notFoundTtl?: number;
|
|
435
|
-
/**
|
|
436
|
-
* Number of consecutive Redis errors before the circuit opens (stops
|
|
437
|
-
* attempting Redis until the cooldown elapses).
|
|
438
|
-
* Default: `5`.
|
|
439
|
-
*/
|
|
440
|
-
l2CircuitBreakerThreshold?: number;
|
|
441
|
-
/**
|
|
442
|
-
* Milliseconds the circuit stays open before transitioning to half-open
|
|
443
|
-
* (allows a single probe request to test recovery).
|
|
444
|
-
* Default: `30 000` ms (30 s).
|
|
445
|
-
*/
|
|
446
|
-
l2CircuitBreakerCooldownMs?: number;
|
|
447
|
-
/**
|
|
448
|
-
* Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
|
|
449
|
-
* `cache.ready()` returns a Promise that resolves once this warm-up completes.
|
|
450
|
-
* No-op when Redis is disabled or unreachable — safe to set unconditionally.
|
|
451
|
-
*/
|
|
452
|
-
warmKeys?: string;
|
|
453
|
-
/**
|
|
454
|
-
* Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
|
|
455
|
-
* namespace prefix) and the tier that served it. Useful for per-route hit-rate
|
|
456
|
-
* metrics without waiting for the `onMetrics` interval.
|
|
457
|
-
*
|
|
458
|
-
* @example
|
|
459
|
-
* onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
|
|
460
|
-
*/
|
|
461
|
-
onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
|
|
462
|
-
/**
|
|
463
|
-
* Called on every cache miss (after L1, disk, and L2 are all exhausted).
|
|
464
|
-
* Receives the caller-facing key (no namespace prefix).
|
|
465
|
-
*
|
|
466
|
-
* @example
|
|
467
|
-
* onMiss: (key) => cloudwatch.putMetricData({ key })
|
|
468
|
-
*/
|
|
469
|
-
onMiss?: (key: string) => void;
|
|
470
|
-
/**
|
|
471
|
-
* When `true`, every value returned from an L1 cache hit is recursively
|
|
472
|
-
* frozen with `Object.freeze()` before being handed to the caller.
|
|
473
|
-
* Any attempt to mutate the returned object throws a `TypeError` immediately,
|
|
474
|
-
* catching reference-semantic corruption bugs that would otherwise silently
|
|
475
|
-
* corrupt the cached entry.
|
|
476
|
-
*
|
|
477
|
-
* **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
|
|
478
|
-
* Deep-freezing large objects has measurable overhead per hit.
|
|
479
|
-
*
|
|
480
|
-
* @example
|
|
481
|
-
* frozen: process.env.NODE_ENV !== 'production'
|
|
482
|
-
*/
|
|
483
|
-
frozen?: boolean;
|
|
484
|
-
/**
|
|
485
|
-
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
486
|
-
* and automatically derives an optimal TTL from the p95 fetch duration:
|
|
487
|
-
*
|
|
488
|
-
* ```
|
|
489
|
-
* adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
|
|
490
|
-
* ```
|
|
491
|
-
*
|
|
492
|
-
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
493
|
-
* for a key, then the library takes over TTL management autonomously.
|
|
494
|
-
*
|
|
495
|
-
* Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
|
|
496
|
-
* their base TTL. Callers no longer need to reason about individual TTL values.
|
|
497
|
-
*
|
|
498
|
-
* Default: `false`.
|
|
499
|
-
*/
|
|
500
|
-
adaptiveTtl?: boolean;
|
|
501
|
-
/**
|
|
502
|
-
* Minimum TTL (seconds) the adaptive tuner will ever assign.
|
|
503
|
-
* Guards against extremely fast fetches producing near-zero TTLs.
|
|
504
|
-
* Default: `10`.
|
|
505
|
-
*/
|
|
506
|
-
adaptiveTtlMin?: number;
|
|
507
|
-
/**
|
|
508
|
-
* Maximum TTL (seconds) the adaptive tuner will ever assign.
|
|
509
|
-
* Guards against pathologically slow fetches producing indefinite caching.
|
|
510
|
-
* Default: `86400` (24 hours).
|
|
511
|
-
*/
|
|
512
|
-
adaptiveTtlMax?: number;
|
|
513
|
-
/**
|
|
514
|
-
* `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
|
|
515
|
-
*
|
|
516
|
-
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
517
|
-
* 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
|
|
518
|
-
* if you want the cache to absorb more upstream pressure.
|
|
519
|
-
*
|
|
520
|
-
* Default: `20`.
|
|
521
|
-
*/
|
|
522
|
-
adaptiveTtlMultiplier?: number;
|
|
523
|
-
/**
|
|
524
|
-
* Number of fetch duration samples kept per key in the ring buffer.
|
|
525
|
-
* Larger values smooth out latency spikes but use slightly more memory
|
|
526
|
-
* (~8 bytes × samples per tracked key).
|
|
527
|
-
* Default: `32`.
|
|
528
|
-
*/
|
|
529
|
-
adaptiveTtlSamples?: number;
|
|
530
|
-
/**
|
|
531
|
-
* Maximum number of distinct keys tracked by the adaptive TTL system.
|
|
532
|
-
* When the cap is reached, the oldest-tracked key is evicted from the
|
|
533
|
-
* ring-buffer store to make room for the new key.
|
|
534
|
-
* Default: `5000`.
|
|
535
|
-
*/
|
|
536
|
-
adaptiveTtlMaxKeys?: number;
|
|
537
|
-
/**
|
|
538
|
-
* When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
|
|
539
|
-
* encryption and decryption for large payloads to those threads, keeping the
|
|
540
|
-
* V8 main event loop free for concurrent HTTP requests.
|
|
541
|
-
*
|
|
542
|
-
* Only takes effect when `encryptionKey` is set — plaintext payloads are never
|
|
543
|
-
* serialized off-thread because `JSON.stringify/parse` is already fast.
|
|
544
|
-
*
|
|
545
|
-
* Default: `false`. Enable in long-running servers that write multi-megabyte
|
|
546
|
-
* encrypted payloads and observe event-loop latency spikes.
|
|
547
|
-
*/
|
|
548
|
-
workerThreads?: boolean;
|
|
549
|
-
/**
|
|
550
|
-
* Byte threshold above which an L2 payload is offloaded to a worker thread
|
|
551
|
-
* for encryption / decryption. Payloads smaller than this are processed
|
|
552
|
-
* synchronously (IPC overhead would exceed the savings).
|
|
553
|
-
* Default: `131072` (128 KB).
|
|
554
|
-
*/
|
|
555
|
-
workerThresholdBytes?: number;
|
|
556
|
-
/**
|
|
557
|
-
* Number of worker threads in the pool.
|
|
558
|
-
* Default: `Math.min(4, os.availableParallelism())`.
|
|
559
|
-
*/
|
|
560
|
-
workerPoolSize?: number;
|
|
561
|
-
/**
|
|
562
|
-
* Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
|
|
563
|
-
* disconnected before tricache considers its L1 entries potentially stale.
|
|
564
|
-
*
|
|
565
|
-
* When the subscriber reconnects after a gap longer than this value, all L1
|
|
566
|
-
* entries that were written *before* the disconnect started are evicted.
|
|
567
|
-
* This prevents the instance from silently serving data that peers may have
|
|
568
|
-
* invalidated while the backplane connection was down.
|
|
569
|
-
*
|
|
570
|
-
* Set to `0` to disable the fence entirely (accept eventual-consistency drift).
|
|
571
|
-
* Default: `5000` (5 seconds).
|
|
572
|
-
*/
|
|
573
|
-
backplaneMaxStalenessMs?: number;
|
|
574
|
-
/**
|
|
575
|
-
* Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
|
|
576
|
-
*
|
|
577
|
-
* Tricache auto-detects common serverless / ephemeral-filesystem runtimes
|
|
578
|
-
* (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
|
|
579
|
-
* Fly.io) and disables the disk tier automatically. Set this to `false` to
|
|
580
|
-
* override that detection and force the disk tier on regardless of runtime.
|
|
581
|
-
*
|
|
582
|
-
* When disabled:
|
|
583
|
-
* - L1 evictions are dropped instead of being spilled to disk.
|
|
584
|
-
* - Cold-start snapshot persistence is skipped.
|
|
585
|
-
* - The `disk` metrics field still appears but shows zeroed counters.
|
|
586
|
-
*
|
|
587
|
-
* Default: `undefined` (auto-detect).
|
|
588
|
-
*/
|
|
589
|
-
disableDisk?: boolean;
|
|
590
|
-
/**
|
|
591
|
-
* Redis Cluster node list. When provided, tricache connects using ioredis
|
|
592
|
-
* `Cluster` mode with automatic slot routing and multi-node connection
|
|
593
|
-
* pooling — no external proxy required.
|
|
594
|
-
*
|
|
595
|
-
* Takes precedence over `redisHost`/`redisPort`.
|
|
596
|
-
*
|
|
597
|
-
* @example
|
|
598
|
-
* redisClusterNodes: [
|
|
599
|
-
* { host: 'redis-1.internal', port: 6379 },
|
|
600
|
-
* { host: 'redis-2.internal', port: 6379 },
|
|
601
|
-
* { host: 'redis-3.internal', port: 6379 },
|
|
602
|
-
* ]
|
|
603
|
-
*/
|
|
604
|
-
redisClusterNodes?: Array<{
|
|
605
|
-
host: string;
|
|
606
|
-
port: number;
|
|
607
|
-
}>;
|
|
608
|
-
/**
|
|
609
|
-
* Redis Sentinel configuration for high-availability setups.
|
|
610
|
-
* When provided, tricache connects through Sentinel for automatic
|
|
611
|
-
* primary failover — no static `redisHost` / `redisPort` needed.
|
|
612
|
-
*
|
|
613
|
-
* Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
|
|
614
|
-
*
|
|
615
|
-
* @example
|
|
616
|
-
* redisSentinel: {
|
|
617
|
-
* name: 'mymaster',
|
|
618
|
-
* sentinels: [
|
|
619
|
-
* { host: 'sentinel-1.internal', port: 26379 },
|
|
620
|
-
* { host: 'sentinel-2.internal', port: 26379 },
|
|
621
|
-
* ],
|
|
622
|
-
* }
|
|
623
|
-
*/
|
|
624
|
-
redisSentinel?: {
|
|
625
|
-
/** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
|
|
626
|
-
name: string;
|
|
627
|
-
sentinels: Array<{
|
|
628
|
-
host: string;
|
|
629
|
-
port: number;
|
|
630
|
-
}>;
|
|
631
|
-
};
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* CacheService — three-tier cache with stampede prevention and SWR.
|
|
636
|
-
*
|
|
637
|
-
* Architecture:
|
|
638
|
-
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
639
|
-
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
640
|
-
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
641
|
-
* DB → your fetchFunction (cache miss path)
|
|
642
|
-
*
|
|
643
|
-
* Key features:
|
|
644
|
-
* - Thundering-herd / cache-stampede prevention (inflight Promise registry)
|
|
645
|
-
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
646
|
-
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
647
|
-
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
648
|
-
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
649
|
-
* - Periodic cleanup of expired entries every 5 minutes
|
|
650
|
-
*/
|
|
651
|
-
|
|
652
|
-
declare class CacheService {
|
|
653
|
-
private readonly logger;
|
|
654
|
-
private readonly enc;
|
|
655
|
-
private readonly l1;
|
|
656
|
-
private readonly disk;
|
|
657
|
-
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
658
|
-
private _diskDisabled;
|
|
659
|
-
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
660
|
-
private _workerPool;
|
|
661
|
-
private readonly opts;
|
|
662
|
-
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
663
|
-
private readonly _namespace;
|
|
664
|
-
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
665
|
-
private readonly _redisDisabled;
|
|
666
|
-
private readonly inflight;
|
|
667
|
-
private readonly revalidating;
|
|
668
|
-
private readonly _l1Counters;
|
|
669
|
-
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
670
|
-
private readonly tagIndex;
|
|
671
|
-
/**
|
|
672
|
-
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
673
|
-
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
674
|
-
*/
|
|
675
|
-
private readonly dependencyIndex;
|
|
676
|
-
private redis;
|
|
677
|
-
private redisConnecting;
|
|
678
|
-
private readonly cb;
|
|
679
|
-
private snapshotLoaded;
|
|
680
|
-
private _readyPromise;
|
|
681
|
-
private cleanupInterval;
|
|
682
|
-
private diskJanitorInterval;
|
|
683
|
-
private oomInterval;
|
|
684
|
-
private metricsInterval;
|
|
685
|
-
private _shutdownHandler;
|
|
686
|
-
private latencyTracker;
|
|
687
|
-
private readonly instanceId;
|
|
688
|
-
private readonly backplaneChannel;
|
|
689
|
-
private subClient;
|
|
690
|
-
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
691
|
-
private _subDisconnectedAt;
|
|
692
|
-
private readonly counters;
|
|
693
|
-
constructor(options?: CacheOptions);
|
|
694
|
-
/**
|
|
695
|
-
* Get (or create) the process-level singleton CacheService instance.
|
|
696
|
-
*
|
|
697
|
-
* Options are only applied on first call — subsequent calls return the
|
|
698
|
-
* existing instance regardless of options passed.
|
|
699
|
-
*
|
|
700
|
-
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
701
|
-
* with different namespaces return independent instances.
|
|
702
|
-
*/
|
|
703
|
-
static create(options?: CacheOptions): CacheService;
|
|
704
|
-
/**
|
|
705
|
-
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
706
|
-
* Useful when config is fetched from a secret store at startup.
|
|
707
|
-
*
|
|
708
|
-
* @example
|
|
709
|
-
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
710
|
-
*/
|
|
711
|
-
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
712
|
-
/** Replace the singleton (useful in tests). */
|
|
713
|
-
static reset(options?: CacheOptions): CacheService;
|
|
714
|
-
/** Derive the globalThis key for a given set of options. */
|
|
715
|
-
private static globalKey;
|
|
716
|
-
/**
|
|
717
|
-
* Prepend the configured namespace to a raw cache key.
|
|
718
|
-
* Returns the key unchanged when namespace is empty.
|
|
719
|
-
*
|
|
720
|
-
* This is the only place the namespace prefix is applied — callers always
|
|
721
|
-
* receive and provide un-prefixed keys in the public API.
|
|
722
|
-
*/
|
|
723
|
-
private nk;
|
|
724
|
-
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
725
|
-
private _jitterTtl;
|
|
726
|
-
/** Shared no-op span for the common case where no tracer is configured.
|
|
727
|
-
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
728
|
-
private static readonly _nullSpan;
|
|
729
|
-
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
730
|
-
private _startSpan;
|
|
731
|
-
private initBackplane;
|
|
732
|
-
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
733
|
-
_handleBackplaneMessage(message: string): void;
|
|
734
|
-
private publishInvalidation;
|
|
735
|
-
/**
|
|
736
|
-
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
737
|
-
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
738
|
-
*/
|
|
739
|
-
private _scanKeys;
|
|
740
|
-
private getRedis;
|
|
741
|
-
writeSnapshot(altPath?: string): void;
|
|
742
|
-
loadSnapshot(): void;
|
|
743
|
-
/**
|
|
744
|
-
* Get a value from cache, or fetch and cache it.
|
|
745
|
-
*
|
|
746
|
-
* @param cacheKey - Unique key identifying this value
|
|
747
|
-
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
748
|
-
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
749
|
-
* @param opts.priority - Override the auto-inferred eviction priority
|
|
750
|
-
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
751
|
-
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
752
|
-
* is triggered proactively while the caller still receives the
|
|
753
|
-
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
754
|
-
* Requires `fetchFn` to be stable across calls.
|
|
755
|
-
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
756
|
-
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
757
|
-
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
758
|
-
* decide probabilistically rather than at a fixed threshold.
|
|
759
|
-
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
760
|
-
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
761
|
-
*/
|
|
762
|
-
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
763
|
-
priority?: CachePriority;
|
|
764
|
-
swr?: number;
|
|
765
|
-
refreshAhead?: number;
|
|
766
|
-
xfetchBeta?: number;
|
|
767
|
-
notFoundTtl?: number;
|
|
768
|
-
/**
|
|
769
|
-
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
770
|
-
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
771
|
-
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
772
|
-
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
773
|
-
*/
|
|
774
|
-
tags?: string[];
|
|
775
|
-
}): Promise<T>;
|
|
776
|
-
private _revalidate;
|
|
777
|
-
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
778
|
-
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
779
|
-
tags?: string[];
|
|
780
|
-
dependsOn?: string[];
|
|
781
|
-
}): Promise<void>;
|
|
782
|
-
/**
|
|
783
|
-
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
784
|
-
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
785
|
-
*/
|
|
786
|
-
private _registerTags;
|
|
787
|
-
/**
|
|
788
|
-
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
789
|
-
*
|
|
790
|
-
* @example
|
|
791
|
-
* await cache.delete('user:abc:profile'); // exact key
|
|
792
|
-
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
793
|
-
*/
|
|
794
|
-
delete(cacheKey: string): Promise<void>;
|
|
795
|
-
/**
|
|
796
|
-
* Atomically increment a counter in Redis. Returns the new value.
|
|
797
|
-
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
798
|
-
*/
|
|
799
|
-
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
800
|
-
/**
|
|
801
|
-
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
802
|
-
*
|
|
803
|
-
* @example
|
|
804
|
-
* await cache.clear(); // flush everything
|
|
805
|
-
* await cache.clear('user:abc'); // flush all keys for one user
|
|
806
|
-
*/
|
|
807
|
-
clear(prefix?: string): Promise<void>;
|
|
808
|
-
/**
|
|
809
|
-
* Evict L1 entries that violate the current category or global capacity limits.
|
|
810
|
-
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
811
|
-
* Returns the number of entries evicted.
|
|
812
|
-
*/
|
|
813
|
-
rebalance(): number;
|
|
814
|
-
/**
|
|
815
|
-
* Return the remaining TTL in seconds for a key currently in L1.
|
|
816
|
-
* Returns null if the key is absent from L1 or has already expired.
|
|
817
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
818
|
-
*/
|
|
819
|
-
ttl(cacheKey: string): number | null;
|
|
820
|
-
/**
|
|
821
|
-
* Return true if the key exists in L1 and has not expired.
|
|
822
|
-
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
823
|
-
*/
|
|
824
|
-
has(cacheKey: string): boolean;
|
|
825
|
-
/**
|
|
826
|
-
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
827
|
-
*
|
|
828
|
-
* @example
|
|
829
|
-
* for (const key of cache.keys()) console.log(key);
|
|
830
|
-
*/
|
|
831
|
-
keys(): Generator<string>;
|
|
832
|
-
/**
|
|
833
|
-
* Lazily yield every non-expired L1 value.
|
|
834
|
-
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
835
|
-
*
|
|
836
|
-
* @example
|
|
837
|
-
* for (const val of cache.values<User>()) console.log(val.id);
|
|
838
|
-
*/
|
|
839
|
-
values<T = unknown>(): Generator<T>;
|
|
840
|
-
/**
|
|
841
|
-
* Lazily yield every non-expired L1 [key, value] pair.
|
|
842
|
-
* Keys are stripped of their namespace prefix.
|
|
843
|
-
*
|
|
844
|
-
* @example
|
|
845
|
-
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
846
|
-
*/
|
|
847
|
-
entries<T = unknown>(): Generator<[string, T]>;
|
|
848
|
-
/**
|
|
849
|
-
* High-throughput bulk scan over all live L1 entries.
|
|
850
|
-
*
|
|
851
|
-
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
852
|
-
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
853
|
-
* caller uses the `offset` parameter instead of pre-slicing.
|
|
854
|
-
*
|
|
855
|
-
* ```typescript
|
|
856
|
-
* // Zero extra string allocations — use rawKey + offset directly:
|
|
857
|
-
* cache.scan((rawKey, value, offset) => {
|
|
858
|
-
* const key = rawKey.slice(offset); // allocate only if needed
|
|
859
|
-
* sync(key, value as User);
|
|
860
|
-
* });
|
|
861
|
-
* ```
|
|
862
|
-
*
|
|
863
|
-
* @param fn Called once per live L1 entry.
|
|
864
|
-
* `rawKey` — key with namespace prefix still attached.
|
|
865
|
-
* `value` — deserialized cached value.
|
|
866
|
-
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
867
|
-
*/
|
|
868
|
-
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
|
|
869
|
-
/**
|
|
870
|
-
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
871
|
-
* Returns `false` if the key is absent or already expired.
|
|
872
|
-
*
|
|
873
|
-
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
874
|
-
*/
|
|
875
|
-
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
876
|
-
/**
|
|
877
|
-
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
878
|
-
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
879
|
-
*
|
|
880
|
-
* @example
|
|
881
|
-
* const fresh = cache.getIfFresh('user:123');
|
|
882
|
-
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
883
|
-
*/
|
|
884
|
-
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
885
|
-
/**
|
|
886
|
-
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
887
|
-
* Preserves input ordering. Uses inflight coalescing per key.
|
|
888
|
-
*
|
|
889
|
-
* @param keys - Array of cache keys.
|
|
890
|
-
* @param fetchFn - Called with only the keys that missed L1.
|
|
891
|
-
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
892
|
-
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
893
|
-
*/
|
|
894
|
-
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
895
|
-
/**
|
|
896
|
-
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
897
|
-
* startup warming configured via `warmKeys` has completed.
|
|
898
|
-
*
|
|
899
|
-
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
900
|
-
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
901
|
-
*
|
|
902
|
-
* @example
|
|
903
|
-
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
904
|
-
* await cache.ready(); // gate traffic until warm
|
|
905
|
-
*/
|
|
906
|
-
ready(): Promise<void>;
|
|
907
|
-
/**
|
|
908
|
-
* Batch write — set multiple entries in a single call.
|
|
909
|
-
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
910
|
-
*
|
|
911
|
-
* @example
|
|
912
|
-
* await cache.mset({
|
|
913
|
-
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
914
|
-
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
915
|
-
* });
|
|
916
|
-
*/
|
|
917
|
-
mset<T = unknown>(entries: Record<string, {
|
|
918
|
-
value: T;
|
|
919
|
-
ttl?: number;
|
|
920
|
-
priority?: CachePriority;
|
|
921
|
-
tags?: string[];
|
|
922
|
-
dependsOn?: string[];
|
|
923
|
-
}>): Promise<void>;
|
|
924
|
-
/**
|
|
925
|
-
* Batch delete — delete multiple exact keys in a single call.
|
|
926
|
-
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
927
|
-
*
|
|
928
|
-
* @example
|
|
929
|
-
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
930
|
-
*/
|
|
931
|
-
mdel(keys: string[]): Promise<void>;
|
|
932
|
-
/**
|
|
933
|
-
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
934
|
-
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
935
|
-
* the local snapshot is unavailable or too stale.
|
|
936
|
-
*
|
|
937
|
-
* Returns the number of keys loaded into L1.
|
|
938
|
-
*
|
|
939
|
-
* @example
|
|
940
|
-
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
941
|
-
* const loaded = await cache.warmFromL2('org:*');
|
|
942
|
-
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
943
|
-
*/
|
|
944
|
-
warmFromL2(pattern: string, opts?: {
|
|
945
|
-
priority?: CachePriority;
|
|
946
|
-
}): Promise<number>;
|
|
947
|
-
/**
|
|
948
|
-
* Invalidate all keys associated with a tag.
|
|
949
|
-
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
950
|
-
*
|
|
951
|
-
* @example
|
|
952
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
953
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
954
|
-
*/
|
|
955
|
-
invalidateTag(tag: string): Promise<void>;
|
|
956
|
-
/**
|
|
957
|
-
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
958
|
-
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
959
|
-
* reducing latency when invalidating several related tags together.
|
|
960
|
-
*
|
|
961
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
962
|
-
* synchronously before the Redis round-trip.
|
|
963
|
-
*
|
|
964
|
-
* @example
|
|
965
|
-
* // Instead of three serial round-trips:
|
|
966
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
967
|
-
*/
|
|
968
|
-
invalidateTags(tags: string[]): Promise<void>;
|
|
969
|
-
/**
|
|
970
|
-
* Measure L1 / disk / Redis latency.
|
|
971
|
-
* Useful for health checks and dashboards.
|
|
972
|
-
*
|
|
973
|
-
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
974
|
-
* `l2` is `null` when Redis is disabled.
|
|
975
|
-
*/
|
|
976
|
-
ping(): Promise<CachePingResult>;
|
|
977
|
-
/**
|
|
978
|
-
* Export all live L1 entries to Redis via a single pipeline.
|
|
979
|
-
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
980
|
-
* Returns the number of keys written.
|
|
981
|
-
*/
|
|
982
|
-
drainToL2(): Promise<number>;
|
|
983
|
-
stats(): {
|
|
984
|
-
l1: {
|
|
985
|
-
entries: number;
|
|
986
|
-
sizeBytes: number;
|
|
987
|
-
sizeKB: number;
|
|
988
|
-
categories: Record<string, {
|
|
989
|
-
entries: number;
|
|
990
|
-
hits: number;
|
|
991
|
-
}>;
|
|
992
|
-
bloom: {
|
|
993
|
-
checks: number;
|
|
994
|
-
falsePositives: number;
|
|
995
|
-
};
|
|
996
|
-
compression: {
|
|
997
|
-
compressed: number;
|
|
998
|
-
uncompressed: number;
|
|
999
|
-
bytesSaved: number;
|
|
1000
|
-
};
|
|
1001
|
-
};
|
|
1002
|
-
disk: {
|
|
1003
|
-
files: number;
|
|
1004
|
-
sizeKB: number;
|
|
1005
|
-
maxKB: number;
|
|
1006
|
-
};
|
|
1007
|
-
};
|
|
1008
|
-
/**
|
|
1009
|
-
* Write `value` only if the key is not already cached.
|
|
1010
|
-
* Returns `true` if the write happened, `false` if the key already existed.
|
|
1011
|
-
*
|
|
1012
|
-
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
1013
|
-
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
1014
|
-
* multiple instances. L1 is populated on success.
|
|
1015
|
-
*
|
|
1016
|
-
* @example
|
|
1017
|
-
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
1018
|
-
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
1019
|
-
*/
|
|
1020
|
-
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
1021
|
-
/**
|
|
1022
|
-
* Return the top-N live L1 keys by historical access frequency.
|
|
1023
|
-
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
1024
|
-
* whose historical frequency exceeds their current in-memory hit count.
|
|
1025
|
-
*
|
|
1026
|
-
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
1027
|
-
* collection overhead.
|
|
1028
|
-
*
|
|
1029
|
-
* @param n - Maximum number of keys to return. Default: 10.
|
|
1030
|
-
*
|
|
1031
|
-
* @example
|
|
1032
|
-
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
1033
|
-
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
1034
|
-
*/
|
|
1035
|
-
hotKeys(n?: number): Array<{
|
|
1036
|
-
key: string;
|
|
1037
|
-
hits: number;
|
|
1038
|
-
sizeBytes: number;
|
|
1039
|
-
}>;
|
|
1040
|
-
/**
|
|
1041
|
-
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
1042
|
-
* pattern that may contain `*` wildcards).
|
|
1043
|
-
*/
|
|
1044
|
-
private _matchesGlob;
|
|
1045
|
-
/**
|
|
1046
|
-
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
1047
|
-
* that was registered via `dependsOn` and whose source pattern matches.
|
|
1048
|
-
*/
|
|
1049
|
-
private _cascadeDependencies;
|
|
1050
|
-
/** Return a full metrics snapshot. */
|
|
1051
|
-
metrics(): CacheMetrics;
|
|
1052
|
-
/**
|
|
1053
|
-
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
1054
|
-
* Paste the result into your `/metrics` endpoint.
|
|
1055
|
-
*
|
|
1056
|
-
* @param m - Snapshot returned by `cache.metrics()`
|
|
1057
|
-
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
1058
|
-
*/
|
|
1059
|
-
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
1060
|
-
/** Close Redis connections and stop all background timers. */
|
|
1061
|
-
destroy(): Promise<void>;
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
/**
|
|
1065
|
-
* Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
|
|
1066
|
-
*
|
|
1067
|
-
* Four modes are supported via the `encryptionMode` CacheOption:
|
|
1068
|
-
*
|
|
1069
|
-
* ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
|
|
1070
|
-
* │ Mode │ Key bytes │ Notes │
|
|
1071
|
-
* ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
|
|
1072
|
-
* │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
|
|
1073
|
-
* │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
|
|
1074
|
-
* │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
|
|
1075
|
-
* │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
|
|
1076
|
-
* │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
|
|
1077
|
-
* │ │ │ Use only for dev or non-sensitive data. │
|
|
1078
|
-
* └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
|
|
1079
|
-
*
|
|
1080
|
-
* Key generation:
|
|
1081
|
-
* AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
1082
|
-
* AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
1083
|
-
* CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
1084
|
-
* XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
1085
|
-
*
|
|
1086
|
-
* Redis envelope formats:
|
|
1087
|
-
* enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
|
|
1088
|
-
* a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
|
|
1089
|
-
* ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
|
|
1090
|
-
* xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
|
|
1091
|
-
*
|
|
1092
|
-
* Disk envelope formats:
|
|
1093
|
-
* TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
|
|
1094
|
-
* TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
|
|
1095
|
-
* TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
|
|
1096
|
-
* TRIC1XOR | key⊕data[N] ← XOR
|
|
1097
|
-
*/
|
|
1098
|
-
|
|
1099
|
-
/** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
|
|
1100
|
-
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
1101
|
-
declare class CacheEncryption {
|
|
1102
|
-
private _key;
|
|
1103
|
-
private _keyObj;
|
|
1104
|
-
private readonly _mode;
|
|
1105
|
-
private _prevKey;
|
|
1106
|
-
private _prevKeyObj;
|
|
1107
|
-
private _prevMode;
|
|
1108
|
-
private readonly _ivPool;
|
|
1109
|
-
private _ivOffset;
|
|
1110
|
-
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
1111
|
-
private _nextIV;
|
|
1112
|
-
private readonly _ctrIvPool;
|
|
1113
|
-
private _ctrIvOffset;
|
|
1114
|
-
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
1115
|
-
private _nextCtrIV;
|
|
1116
|
-
/**
|
|
1117
|
-
* XOR `data` with the key, cycling through key bytes.
|
|
1118
|
-
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
1119
|
-
*
|
|
1120
|
-
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
1121
|
-
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
1122
|
-
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
1123
|
-
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
1124
|
-
*
|
|
1125
|
-
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
1126
|
-
*/
|
|
1127
|
-
private _xorBuffer;
|
|
1128
|
-
constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
|
|
1129
|
-
get isEnabled(): boolean;
|
|
1130
|
-
/**
|
|
1131
|
-
* Encrypt a string for Redis storage.
|
|
1132
|
-
* Returns a mode-prefixed base64 string when a key is configured;
|
|
1133
|
-
* otherwise returns the original string unchanged (backward-compatible).
|
|
1134
|
-
*/
|
|
1135
|
-
encrypt(plaintext: string): string;
|
|
1136
|
-
/**
|
|
1137
|
-
* Decrypt a Redis value.
|
|
1138
|
-
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
1139
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
1140
|
-
*/
|
|
1141
|
-
decrypt(value: string): string;
|
|
1142
|
-
private _decryptWithKey;
|
|
1143
|
-
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
1144
|
-
encryptBuffer(data: Buffer): Buffer;
|
|
1145
|
-
/**
|
|
1146
|
-
* Decrypt a raw Buffer from disk/snapshot.
|
|
1147
|
-
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
1148
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
1149
|
-
*/
|
|
1150
|
-
decryptBuffer(data: Buffer): Buffer;
|
|
1151
|
-
private _decryptBufferWithKey;
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
/**
|
|
1155
|
-
* SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
|
|
1156
|
-
*
|
|
1157
|
-
* Features:
|
|
1158
|
-
* - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
|
|
1159
|
-
* - msgpackr compression for entries ≥ 512 bytes
|
|
1160
|
-
* - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
|
|
1161
|
-
* - Priority-weighted adaptive eviction (LFU × LRU × priority score)
|
|
1162
|
-
* - Stale-While-Revalidate soft-expiry support (isStale flag on get())
|
|
1163
|
-
* - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
|
|
1164
|
-
* - Periodic cleanup of hard-expired entries + bloom filter rebuild
|
|
1165
|
-
* - Process-level singleton via globalThis (survives Next.js hot reloads)
|
|
1166
|
-
*/
|
|
1167
|
-
|
|
1168
|
-
interface SmartMemoryCacheOptions {
|
|
1169
|
-
maxBytes: number;
|
|
1170
|
-
maxEntries: number;
|
|
1171
|
-
categories: Record<string, CategoryLimit>;
|
|
1172
|
-
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
1173
|
-
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
1174
|
-
logger: ILogger;
|
|
1175
|
-
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
1176
|
-
evictionWatermark?: number;
|
|
1177
|
-
}
|
|
1178
|
-
declare class SmartMemoryCache {
|
|
1179
|
-
private readonly cache;
|
|
1180
|
-
private readonly opts;
|
|
1181
|
-
private bloom;
|
|
1182
|
-
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
1183
|
-
private readonly categoryPrefixes;
|
|
1184
|
-
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
1185
|
-
private readonly sketch;
|
|
1186
|
-
private totalSize;
|
|
1187
|
-
private categoryCount;
|
|
1188
|
-
private categorySize;
|
|
1189
|
-
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
1190
|
-
private categoryKeys;
|
|
1191
|
-
private bloomChecks;
|
|
1192
|
-
private bloomFalsePos;
|
|
1193
|
-
private compressions;
|
|
1194
|
-
private categoryHits;
|
|
1195
|
-
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
1196
|
-
private _bloomDirtyCount;
|
|
1197
|
-
/**
|
|
1198
|
-
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
1199
|
-
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
1200
|
-
* that is overwritten in-place rather than replaced with a new object literal.
|
|
1201
|
-
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
1202
|
-
* any other code can observe the pool state.
|
|
1203
|
-
*/
|
|
1204
|
-
private readonly _evictPool;
|
|
1205
|
-
private readonly _evictGPool;
|
|
1206
|
-
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
1207
|
-
private recalculateStats;
|
|
1208
|
-
private getCategory;
|
|
1209
|
-
private getCategoryLimit;
|
|
1210
|
-
private _delete;
|
|
1211
|
-
private ensureCapacity;
|
|
1212
|
-
private score;
|
|
1213
|
-
/**
|
|
1214
|
-
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
1215
|
-
* saturated the filter past its ~1 % FP capacity.
|
|
1216
|
-
*
|
|
1217
|
-
* Trigger: (insertions − live entries) > maxCapacity
|
|
1218
|
-
*
|
|
1219
|
-
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
1220
|
-
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
1221
|
-
* cache holds more entries than the filter's rated capacity — which would
|
|
1222
|
-
* stall the write path entirely.
|
|
1223
|
-
*
|
|
1224
|
-
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
1225
|
-
*/
|
|
1226
|
-
private maybeRebuildBloom;
|
|
1227
|
-
private smartEvict;
|
|
1228
|
-
get(key: string): CacheHit | null;
|
|
1229
|
-
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
|
|
1230
|
-
delete(key: string): boolean;
|
|
1231
|
-
private keysMatchingPattern;
|
|
1232
|
-
deletePattern(pattern: string): number;
|
|
1233
|
-
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
1234
|
-
clear(prefix?: string): number;
|
|
1235
|
-
/**
|
|
1236
|
-
* Evict entries that violate current category or global limits.
|
|
1237
|
-
* Returns the number of entries evicted.
|
|
1238
|
-
*/
|
|
1239
|
-
rebalance(): number;
|
|
1240
|
-
/**
|
|
1241
|
-
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
1242
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
1243
|
-
*/
|
|
1244
|
-
ttl(key: string): number | null;
|
|
1245
|
-
/**
|
|
1246
|
-
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
1247
|
-
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
1248
|
-
* exceeds the configured threshold.
|
|
1249
|
-
*
|
|
1250
|
-
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
1251
|
-
* @returns Number of entries evicted
|
|
1252
|
-
*/
|
|
1253
|
-
evictPercentage(pct: number): number;
|
|
1254
|
-
cleanup(): number;
|
|
1255
|
-
/**
|
|
1256
|
-
* Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
|
|
1257
|
-
*
|
|
1258
|
-
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
1259
|
-
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
1260
|
-
* Entries written before the disconnect started may have been invalidated by
|
|
1261
|
-
* peers while the backplane was down; evicting them forces a controlled
|
|
1262
|
-
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1263
|
-
*
|
|
1264
|
-
* Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
|
|
1265
|
-
* Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
|
|
1266
|
-
* conservatively.
|
|
1267
|
-
*
|
|
1268
|
-
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1269
|
-
* this time are evicted.
|
|
1270
|
-
* @returns Number of entries evicted.
|
|
1271
|
-
*/
|
|
1272
|
-
evictSetBefore(cutoffMs: number): number;
|
|
1273
|
-
exportEntries(forbiddenPrefixes: readonly string[]): Array<{
|
|
1274
|
-
key: string;
|
|
1275
|
-
entry: SmartCacheEntry;
|
|
1276
|
-
}>;
|
|
1277
|
-
importEntries(entries: Array<{
|
|
1278
|
-
key: string;
|
|
1279
|
-
entry: SmartCacheEntry;
|
|
1280
|
-
}>, forbiddenPrefixes: readonly string[]): number;
|
|
1281
|
-
/**
|
|
1282
|
-
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
1283
|
-
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
1284
|
-
* are silently skipped.
|
|
1285
|
-
*/
|
|
1286
|
-
liveEntries(): Generator<[string, SmartCacheEntry]>;
|
|
1287
|
-
/**
|
|
1288
|
-
* Non-generator bulk scan over all live entries.
|
|
1289
|
-
*
|
|
1290
|
-
* Faster than the generator-based iterators for bulk operations because:
|
|
1291
|
-
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
1292
|
-
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
1293
|
-
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
1294
|
-
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
1295
|
-
* monomorphic profile for this path.
|
|
1296
|
-
*
|
|
1297
|
-
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
1298
|
-
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
1299
|
-
* key, avoiding the allocation entirely for callers that don't.
|
|
1300
|
-
*
|
|
1301
|
-
* @param fn Called once per live entry.
|
|
1302
|
-
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
1303
|
-
* Pass 0 when no namespace is configured.
|
|
1304
|
-
*/
|
|
1305
|
-
scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
|
|
1306
|
-
/**
|
|
1307
|
-
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
1308
|
-
* Use this instead of liveEntries() when you only need keys.
|
|
1309
|
-
*/
|
|
1310
|
-
liveKeys(): Generator<string>;
|
|
1311
|
-
/**
|
|
1312
|
-
* Yields only the resolved values of live entries.
|
|
1313
|
-
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
1314
|
-
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
1315
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
1316
|
-
*/
|
|
1317
|
-
liveValues(): Generator<unknown>;
|
|
1318
|
-
get size(): number;
|
|
1319
|
-
get memoryUsage(): number;
|
|
1320
|
-
getStats(): {
|
|
1321
|
-
entries: number;
|
|
1322
|
-
sizeBytes: number;
|
|
1323
|
-
sizeKB: number;
|
|
1324
|
-
categories: Record<string, {
|
|
1325
|
-
entries: number;
|
|
1326
|
-
hits: number;
|
|
1327
|
-
}>;
|
|
1328
|
-
bloom: {
|
|
1329
|
-
checks: number;
|
|
1330
|
-
falsePositives: number;
|
|
1331
|
-
};
|
|
1332
|
-
compression: {
|
|
1333
|
-
compressed: number;
|
|
1334
|
-
uncompressed: number;
|
|
1335
|
-
bytesSaved: number;
|
|
1336
|
-
};
|
|
1337
|
-
};
|
|
1338
|
-
/**
|
|
1339
|
-
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
1340
|
-
* Does NOT count as a hit or perform SWR logic.
|
|
1341
|
-
*/
|
|
1342
|
-
getEntry(key: string): SmartCacheEntry | undefined;
|
|
1343
|
-
/**
|
|
1344
|
-
* Return true if the key exists in L1 and has not expired.
|
|
1345
|
-
* Uses the bloom filter as a fast negative check.
|
|
1346
|
-
*/
|
|
1347
|
-
has(key: string): boolean;
|
|
1348
|
-
/**
|
|
1349
|
-
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1350
|
-
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1351
|
-
*/
|
|
1352
|
-
touch(key: string, newTtlMs: number): boolean;
|
|
1353
|
-
/**
|
|
1354
|
-
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1355
|
-
* Returns `false` if the key is absent or already expired.
|
|
1356
|
-
*/
|
|
1357
|
-
bumpExpiry(key: string, additionalMs: number): boolean;
|
|
1358
|
-
bloomMightContain(key: string): boolean;
|
|
1359
|
-
bloomStats(): {
|
|
1360
|
-
bitsSet: number;
|
|
1361
|
-
fillFactor: number;
|
|
1362
|
-
} | {
|
|
1363
|
-
bitsSet: number;
|
|
1364
|
-
fillFactor: number;
|
|
1365
|
-
};
|
|
1366
|
-
/**
|
|
1367
|
-
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1368
|
-
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1369
|
-
* Useful for diagnosing which keys are driving cache pressure.
|
|
1370
|
-
*
|
|
1371
|
-
* @param n - Maximum number of entries to return. Default: 10.
|
|
1372
|
-
*/
|
|
1373
|
-
hotKeys(n: number): Array<{
|
|
1374
|
-
key: string;
|
|
1375
|
-
hits: number;
|
|
1376
|
-
sizeBytes: number;
|
|
1377
|
-
}>;
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
|
-
/**
|
|
1381
|
-
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
1382
|
-
*
|
|
1383
|
-
* When L1 evicts an entry it is spilled here instead of being discarded.
|
|
1384
|
-
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
1385
|
-
* vs 10–100 ms DB round-trip).
|
|
1386
|
-
*
|
|
1387
|
-
* Storage:
|
|
1388
|
-
* - Directory: configurable (default os.tmpdir()/tricache-disk)
|
|
1389
|
-
* - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
|
|
1390
|
-
* - Format: msgpack({ version, key, entry, writtenAt })
|
|
1391
|
-
* - Mode: 0o600 — owner read/write only
|
|
1392
|
-
*
|
|
1393
|
-
* Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
|
|
1394
|
-
*/
|
|
1395
|
-
|
|
1396
|
-
interface DiskTierOptions {
|
|
1397
|
-
dir: string;
|
|
1398
|
-
maxBytes: number;
|
|
1399
|
-
entryMaxBytes: number;
|
|
1400
|
-
forbiddenPrefixes: readonly string[];
|
|
1401
|
-
encryptionKey?: Buffer | null;
|
|
1402
|
-
logger: ILogger;
|
|
1403
|
-
}
|
|
1404
|
-
declare class DiskTier {
|
|
1405
|
-
private readonly opts;
|
|
1406
|
-
private dirReady;
|
|
1407
|
-
private diskUsageBytes;
|
|
1408
|
-
private usageCounted;
|
|
1409
|
-
private fileCount;
|
|
1410
|
-
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1411
|
-
private _nextJanitorBucket;
|
|
1412
|
-
private _db;
|
|
1413
|
-
private _stmtInsert;
|
|
1414
|
-
private _stmtSelect;
|
|
1415
|
-
private _stmtDelete;
|
|
1416
|
-
private _stmtExpire;
|
|
1417
|
-
private _stmtDelExp;
|
|
1418
|
-
private _stmtStats;
|
|
1419
|
-
constructor(opts: DiskTierOptions);
|
|
1420
|
-
private ensureDir;
|
|
1421
|
-
/**
|
|
1422
|
-
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
1423
|
-
* is confirmed to exist. On any failure the instance silently falls back to
|
|
1424
|
-
* file-only mode — all public methods handle `this._db === null`.
|
|
1425
|
-
*
|
|
1426
|
-
* Schema:
|
|
1427
|
-
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
1428
|
-
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
1429
|
-
*
|
|
1430
|
-
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
1431
|
-
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
1432
|
-
*/
|
|
1433
|
-
private _initSqlite;
|
|
1434
|
-
private ensureUsageCounted;
|
|
1435
|
-
/**
|
|
1436
|
-
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
1437
|
-
* Kept separate from path construction so callers can find files by prefix
|
|
1438
|
-
* without knowing which filename generation was used when the file was written.
|
|
1439
|
-
*/
|
|
1440
|
-
private keyToHash;
|
|
1441
|
-
/**
|
|
1442
|
-
* Build the write path for a NEW file (V3 generation).
|
|
1443
|
-
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
1444
|
-
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
1445
|
-
*
|
|
1446
|
-
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
1447
|
-
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
1448
|
-
*
|
|
1449
|
-
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1450
|
-
*/
|
|
1451
|
-
private hashToWritePath;
|
|
1452
|
-
/**
|
|
1453
|
-
* Find the on-disk file for a key hash, handling all filename generations:
|
|
1454
|
-
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
1455
|
-
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
1456
|
-
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1457
|
-
*/
|
|
1458
|
-
private findFilePath;
|
|
1459
|
-
/**
|
|
1460
|
-
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
1461
|
-
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
1462
|
-
* files written by older versions).
|
|
1463
|
-
*/
|
|
1464
|
-
private walkCacheFiles;
|
|
1465
|
-
private isForbidden;
|
|
1466
|
-
private encrypt;
|
|
1467
|
-
private decrypt;
|
|
1468
|
-
/**
|
|
1469
|
-
* V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
|
|
1470
|
-
* the outer 16-byte header alongside the plaintext expiresAt).
|
|
1471
|
-
* Returns the buffer unchanged when no encryption key is configured.
|
|
1472
|
-
*/
|
|
1473
|
-
private encryptV2;
|
|
1474
|
-
/**
|
|
1475
|
-
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
1476
|
-
* When a key is configured the format is IV(12)+TAG(16)+ciphertext;
|
|
1477
|
-
* without a key the payload is raw msgpack.
|
|
1478
|
-
*/
|
|
1479
|
-
private decryptV2;
|
|
1480
|
-
/**
|
|
1481
|
-
* Spill an evicted L1 entry to disk.
|
|
1482
|
-
*
|
|
1483
|
-
* Returns a Promise that resolves when the file is durably written. Callers
|
|
1484
|
-
* that treat the spill as fire-and-forget should do:
|
|
1485
|
-
* `void disk.save(key, entry)`
|
|
1486
|
-
*
|
|
1487
|
-
* Implementation notes:
|
|
1488
|
-
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
1489
|
-
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
1490
|
-
* on any external resource.
|
|
1491
|
-
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
1492
|
-
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
1493
|
-
*/
|
|
1494
|
-
save(key: string, entry: DiskCacheEntry): Promise<void>;
|
|
1495
|
-
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
1496
|
-
load(key: string): DiskCacheEntry | null;
|
|
1497
|
-
/** Explicitly delete a key from disk (cache invalidation). */
|
|
1498
|
-
delete(key: string): void;
|
|
1499
|
-
/** Purge all expired entries. Returns number deleted. */
|
|
1500
|
-
purgeExpired(): number;
|
|
1501
|
-
/**
|
|
1502
|
-
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
1503
|
-
*
|
|
1504
|
-
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
1505
|
-
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
1506
|
-
* wheel. All expired entries are found and deleted in a single pass — the
|
|
1507
|
-
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
1508
|
-
* incremented so tests that inspect the counter continue to work.
|
|
1509
|
-
*
|
|
1510
|
-
* File-only fallback:
|
|
1511
|
-
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
1512
|
-
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
1513
|
-
*
|
|
1514
|
-
* Returns the number of entries deleted in this tick.
|
|
1515
|
-
*/
|
|
1516
|
-
purgeNextBucket(): number;
|
|
1517
|
-
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1518
|
-
clear(): number;
|
|
1519
|
-
get stats(): {
|
|
1520
|
-
files: number;
|
|
1521
|
-
sizeKB: number;
|
|
1522
|
-
maxKB: number;
|
|
1523
|
-
};
|
|
1524
|
-
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
1525
|
-
get indexMode(): 'sqlite' | 'file-only';
|
|
1526
|
-
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1527
|
-
close(): void;
|
|
1528
|
-
}
|
|
1529
|
-
|
|
1530
|
-
declare class WasmBloomFilter {
|
|
1531
|
-
private readonly exports;
|
|
1532
|
-
private readonly mem;
|
|
1533
|
-
private readonly encoder;
|
|
1534
|
-
private readonly numBits;
|
|
1535
|
-
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
1536
|
-
private readonly _maxCapacity;
|
|
1537
|
-
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
1538
|
-
private _insertionCount;
|
|
1539
|
-
constructor();
|
|
1540
|
-
private writeKey;
|
|
1541
|
-
add(key: string): void;
|
|
1542
|
-
mightContain(key: string): boolean;
|
|
1543
|
-
reset(): void;
|
|
1544
|
-
rebuild(keys: Iterable<string>): void;
|
|
1545
|
-
get stats(): {
|
|
1546
|
-
bitsSet: number;
|
|
1547
|
-
fillFactor: number;
|
|
1548
|
-
};
|
|
1549
|
-
/** Number of add() calls since last reset/rebuild. */
|
|
1550
|
-
get insertions(): number;
|
|
1551
|
-
/**
|
|
1552
|
-
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
1553
|
-
* Exact formula for k=7 hash rounds, m=100 000 bits:
|
|
1554
|
-
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
|
|
1555
|
-
*/
|
|
1556
|
-
get maxCapacity(): number;
|
|
1557
|
-
}
|
|
1558
|
-
|
|
1559
|
-
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 };
|