tricache 0.4.0 → 0.5.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 +63 -27
- package/dist/cache-service.d.ts +366 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1494 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +83 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +324 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +88 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +371 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +51 -23
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +18 -1146
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -2697
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +178 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +753 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +428 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +20 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm/bloom-filter-wasm.d.ts +29 -0
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -0
- package/dist/wasm/bloom-filter-wasm.js +99 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +10 -11
- package/src/cache-service.ts +36 -4
- package/src/smart-memory-cache.ts +36 -27
- package/src/types.ts +6 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,1153 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* tricache —
|
|
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
|
-
}
|
|
100
|
-
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
101
|
-
* legacy disk files written by older versions may have a JSON string in data) */
|
|
102
|
-
interface DiskCacheEntry {
|
|
103
|
-
data: string | Buffer | Uint8Array;
|
|
104
|
-
isCompressed: boolean;
|
|
105
|
-
expiresAt: number;
|
|
106
|
-
staleAt?: number;
|
|
107
|
-
size: number;
|
|
108
|
-
hits: number;
|
|
109
|
-
lastAccess: number;
|
|
110
|
-
priority: number;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Snapshot of runtime metrics for a CacheService instance.
|
|
114
|
-
* Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
|
|
115
|
-
* Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
|
|
116
|
-
*/
|
|
117
|
-
interface CacheMetrics {
|
|
118
|
-
/** Configured namespace (empty string = no namespace) */
|
|
119
|
-
namespace: string;
|
|
120
|
-
/** Milliseconds since the CacheService instance was constructed */
|
|
121
|
-
uptimeMs: number;
|
|
122
|
-
gets: {
|
|
123
|
-
total: number;
|
|
124
|
-
l1Hits: number;
|
|
125
|
-
/** Fraction of gets served from L1 RAM cache (0–1) */
|
|
126
|
-
l1HitRate: number;
|
|
127
|
-
diskHits: number;
|
|
128
|
-
/** Fraction of gets served from L1.5 disk tier (0–1) */
|
|
129
|
-
diskHitRate: number;
|
|
130
|
-
l2Hits: number;
|
|
131
|
-
/** Fraction of gets served from L2 Redis (0–1) */
|
|
132
|
-
l2HitRate: number;
|
|
133
|
-
/** fetchFn calls (cache misses that fell through to the DB) */
|
|
134
|
-
fetches: number;
|
|
135
|
-
/** Fraction of gets that called fetchFn (0–1) */
|
|
136
|
-
fetchRate: number;
|
|
137
|
-
/** Concurrent get() calls deduplicated by the stampede guard */
|
|
138
|
-
stampedePrevented: number;
|
|
139
|
-
};
|
|
140
|
-
sets: {
|
|
141
|
-
total: number;
|
|
142
|
-
};
|
|
143
|
-
deletes: {
|
|
144
|
-
total: number;
|
|
145
|
-
};
|
|
146
|
-
revalidations: {
|
|
147
|
-
total: number;
|
|
148
|
-
};
|
|
149
|
-
bloom: {
|
|
150
|
-
/** Total bloom-filter checks (get() calls that passed prefix filter) */
|
|
151
|
-
checksTotal: number;
|
|
152
|
-
/**
|
|
153
|
-
* Times the filter said "might contain" but the key was absent in L1.
|
|
154
|
-
* A high rate suggests the bloom filter capacity needs increasing.
|
|
155
|
-
*/
|
|
156
|
-
falsePositives: number;
|
|
157
|
-
/** falsePositives / checksTotal (0–1; ideal < 0.01) */
|
|
158
|
-
falsePositiveRate: number;
|
|
159
|
-
};
|
|
160
|
-
compression: {
|
|
161
|
-
entriesCompressed: number;
|
|
162
|
-
entriesUncompressed: number;
|
|
163
|
-
/** Approximate bytes saved by msgpackr vs raw JSON */
|
|
164
|
-
bytesSaved: number;
|
|
165
|
-
};
|
|
166
|
-
/** Pub/Sub invalidation backplane statistics */
|
|
167
|
-
backplane: {
|
|
168
|
-
enabled: boolean;
|
|
169
|
-
/** Invalidation messages published to other instances */
|
|
170
|
-
sent: number;
|
|
171
|
-
/** Invalidation messages received from other instances */
|
|
172
|
-
received: number;
|
|
173
|
-
/** Own messages silently skipped (prevents double-eviction) */
|
|
174
|
-
skipped: number;
|
|
175
|
-
};
|
|
176
|
-
/** L2 Redis circuit breaker state */
|
|
177
|
-
l2CircuitBreaker: {
|
|
178
|
-
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
179
|
-
state: 'closed' | 'open' | 'half_open';
|
|
180
|
-
};
|
|
181
|
-
/** OOM guard statistics */
|
|
182
|
-
oom: {
|
|
183
|
-
enabled: boolean;
|
|
184
|
-
/** Number of emergency L1 eviction rounds triggered */
|
|
185
|
-
evictions: number;
|
|
186
|
-
/** Timestamp of the most recent OOM eviction, or null */
|
|
187
|
-
lastTriggeredAt: number | null;
|
|
188
|
-
};
|
|
189
|
-
l1: {
|
|
190
|
-
entries: number;
|
|
191
|
-
sizeBytes: number;
|
|
192
|
-
maxBytes: number;
|
|
193
|
-
};
|
|
194
|
-
disk: {
|
|
195
|
-
files: number;
|
|
196
|
-
sizeKB: number;
|
|
197
|
-
maxKB: number;
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
/** Per-category memory limits for L1 */
|
|
201
|
-
interface CategoryLimit {
|
|
202
|
-
maxEntries: number;
|
|
203
|
-
maxSizeBytes: number;
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Options accepted by CacheService.create()
|
|
207
|
-
*
|
|
208
|
-
* All fields are optional — sensible defaults are used when omitted.
|
|
209
|
-
*/
|
|
210
|
-
interface CacheOptions {
|
|
211
|
-
/**
|
|
212
|
-
* Plug in your own logger (pino, winston, bunyan, …).
|
|
213
|
-
* Defaults to a minimal console logger that only prints warn/error.
|
|
214
|
-
*/
|
|
215
|
-
logger?: ILogger;
|
|
216
|
-
/** Max total bytes held in L1 RAM cache. Default: 200 MB */
|
|
217
|
-
l1MaxBytes?: number;
|
|
218
|
-
/** Max total entries in L1. Default: 2000 */
|
|
219
|
-
l1MaxEntries?: number;
|
|
220
|
-
/**
|
|
221
|
-
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
222
|
-
* Merged over the built-in defaults.
|
|
223
|
-
*/
|
|
224
|
-
categoryLimits?: Record<string, CategoryLimit>;
|
|
225
|
-
/**
|
|
226
|
-
* Key prefixes that are never written to disk snapshots or the disk tier.
|
|
227
|
-
* Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
|
|
228
|
-
*/
|
|
229
|
-
forbiddenSnapshotPrefixes?: string[];
|
|
230
|
-
/** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
|
|
231
|
-
diskCacheDir?: string;
|
|
232
|
-
/** Max total bytes for the disk tier. Default: 500 MB */
|
|
233
|
-
diskMaxBytes?: number;
|
|
234
|
-
/** Max bytes for a single disk entry. Default: 10 MB */
|
|
235
|
-
diskEntryMaxBytes?: number;
|
|
236
|
-
/**
|
|
237
|
-
* Redis/Valkey hostname (no `redis://` prefix).
|
|
238
|
-
* Falls back to the `REDIS_HOST` environment variable.
|
|
239
|
-
* When neither is provided, L2 is disabled.
|
|
240
|
-
*/
|
|
241
|
-
redisHost?: string;
|
|
242
|
-
/** Redis port. Default: 6379 */
|
|
243
|
-
redisPort?: number;
|
|
244
|
-
/**
|
|
245
|
-
* Whether to enable TLS for the Redis connection. Default: true in production,
|
|
246
|
-
* false otherwise.
|
|
247
|
-
*/
|
|
248
|
-
redisTls?: boolean;
|
|
249
|
-
/**
|
|
250
|
-
* Set to `true` to disable L2 Redis entirely (e.g. when running single-process
|
|
251
|
-
* services that don't need distributed caching). Default: false in production,
|
|
252
|
-
* true in development.
|
|
253
|
-
*/
|
|
254
|
-
disableRedis?: boolean;
|
|
255
|
-
/**
|
|
256
|
-
* Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
|
|
257
|
-
* disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
|
|
258
|
-
* If not provided in production, a warning is logged and data is stored plaintext.
|
|
259
|
-
*/
|
|
260
|
-
encryptionKey?: string;
|
|
261
|
-
/**
|
|
262
|
-
* Encryption algorithm used for L2 (Redis) values and disk-tier files.
|
|
263
|
-
* - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
|
|
264
|
-
* - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
|
|
265
|
-
* - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
|
|
266
|
-
* Any key length (minimum 16 bytes recommended).
|
|
267
|
-
* Use for dev environments or non-sensitive data only.
|
|
268
|
-
* Default: `'aes-256-gcm'`
|
|
269
|
-
*/
|
|
270
|
-
encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
271
|
-
/**
|
|
272
|
-
* Fallback encryption key for zero-downtime key rotation.
|
|
273
|
-
* On every read, tricache tries the current `encryptionKey` first.
|
|
274
|
-
* If decryption fails (wrong key), it retries with `previousEncryptionKey`.
|
|
275
|
-
* All writes always use the current `encryptionKey`.
|
|
276
|
-
* Remove this field once you are confident all data has been re-encrypted.
|
|
277
|
-
*/
|
|
278
|
-
previousEncryptionKey?: string;
|
|
279
|
-
/** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
|
|
280
|
-
previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
281
|
-
/**
|
|
282
|
-
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
283
|
-
* on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
|
|
284
|
-
*/
|
|
285
|
-
snapshotPath?: string;
|
|
286
|
-
/**
|
|
287
|
-
* Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
|
|
288
|
-
*/
|
|
289
|
-
snapshotMaxAgeMs?: number;
|
|
290
|
-
/**
|
|
291
|
-
* Optional namespace prefix for all cache keys.
|
|
292
|
-
*
|
|
293
|
-
* When set, every key is transparently stored as `${namespace}:${key}` in
|
|
294
|
-
* L1, L1.5 (disk), and L2 (Redis). This enables:
|
|
295
|
-
* - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
|
|
296
|
-
* — tenants sharing the same Redis instance or disk dir are fully isolated.
|
|
297
|
-
* - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
|
|
298
|
-
* - **Service-level scoping**: microservices sharing one Redis without key collisions.
|
|
299
|
-
*
|
|
300
|
-
* Consumers never see the prefix — `get('user:1')` behaves identically
|
|
301
|
-
* whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
|
|
302
|
-
* scope to the namespace.
|
|
303
|
-
*
|
|
304
|
-
* The process-level singleton, disk cache directory, and cold-start snapshot
|
|
305
|
-
* path are all scoped per namespace, so two `CacheService.create()` calls
|
|
306
|
-
* with different namespaces return completely independent instances.
|
|
307
|
-
*
|
|
308
|
-
* Default: `''` (no prefix)
|
|
309
|
-
*/
|
|
310
|
-
namespace?: string;
|
|
311
|
-
/**
|
|
312
|
-
* Seconds to extend a stale SWR entry's life when background revalidation fails.
|
|
313
|
-
* Without this, a failed revalidation leaves the entry stale until its hard TTL
|
|
314
|
-
* expires, after which the next caller blocks. With `staleIfError`, tricache bumps
|
|
315
|
-
* the expiry by this many seconds on every failed revalidation, keeping the stale
|
|
316
|
-
* value available while the underlying service is degraded.
|
|
317
|
-
* Default: `0` (disabled — entry expires normally on revalidation failure).
|
|
318
|
-
*/
|
|
319
|
-
staleIfError?: number;
|
|
320
|
-
/**
|
|
321
|
-
* Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
|
|
322
|
-
* Useful for diagnosing cache pressure and tuning `categoryLimits`.
|
|
323
|
-
*/
|
|
324
|
-
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
325
|
-
/**
|
|
326
|
-
* Human-readable name for this CacheService instance. Added as an `instance` label
|
|
327
|
-
* to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
|
|
328
|
-
* Required when multiple CacheService instances share a process — without it,
|
|
329
|
-
* metric names from different instances collide.
|
|
330
|
-
* Default: `''` (no label).
|
|
331
|
-
*/
|
|
332
|
-
instanceName?: string;
|
|
333
|
-
/**
|
|
334
|
-
* Controls whether writes are propagated to L2 (Redis).
|
|
335
|
-
* - `'read-write'` (default): read from and write to L2.
|
|
336
|
-
* - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
|
|
337
|
-
* Use for shared read replicas or external Redis clusters you do not own.
|
|
338
|
-
*/
|
|
339
|
-
l2WriteMode?: 'read-write' | 'read-only';
|
|
340
|
-
/**
|
|
341
|
-
* Enable Redis Pub/Sub invalidation backplane so every running instance
|
|
342
|
-
* evicts a key from its L1 when any peer calls `set()` or `delete()`.
|
|
343
|
-
*
|
|
344
|
-
* Gives you sub-microsecond in-process cache speed with cluster-wide
|
|
345
|
-
* consistency across all your app servers.
|
|
346
|
-
*
|
|
347
|
-
* Default: `true` (auto-activates when Redis is available).
|
|
348
|
-
* Set to `false` for single-process services or eventual-consistency scenarios.
|
|
349
|
-
*/
|
|
350
|
-
invalidationBackplane?: boolean;
|
|
351
|
-
/**
|
|
352
|
-
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
353
|
-
* `oomHeapThreshold`, a fraction of the coldest L1 entries are
|
|
354
|
-
* emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
|
|
355
|
-
* Docker/Kubernetes containers with tight memory limits.
|
|
356
|
-
*
|
|
357
|
-
* Default: `true`
|
|
358
|
-
*/
|
|
359
|
-
oomProtection?: boolean;
|
|
360
|
-
/**
|
|
361
|
-
* Heap-used / heap-total ratio that triggers emergency eviction.
|
|
362
|
-
* Default: `0.85` (85 %)
|
|
363
|
-
*/
|
|
364
|
-
oomHeapThreshold?: number;
|
|
365
|
-
/** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
|
|
366
|
-
oomCheckIntervalMs?: number;
|
|
367
|
-
/** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
|
|
368
|
-
oomEvictPercent?: number;
|
|
369
|
-
/**
|
|
370
|
-
* Callback invoked periodically with a `CacheMetrics` snapshot.
|
|
371
|
-
* Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
|
|
372
|
-
*
|
|
373
|
-
* @example
|
|
374
|
-
* onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
|
|
375
|
-
*/
|
|
376
|
-
onMetrics?: (metrics: CacheMetrics) => void;
|
|
377
|
-
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
378
|
-
metricsIntervalMs?: number;
|
|
379
|
-
/**
|
|
380
|
-
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
381
|
-
* `delete()` are each wrapped in a span with attributes:
|
|
382
|
-
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
383
|
-
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
384
|
-
*
|
|
385
|
-
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
386
|
-
* dependency required; the interface is structurally compatible.
|
|
387
|
-
*
|
|
388
|
-
* @example
|
|
389
|
-
* import { trace } from '@opentelemetry/api';
|
|
390
|
-
* tracer: trace.getTracer('tricache')
|
|
391
|
-
*/
|
|
392
|
-
tracer?: ICacheTracer;
|
|
393
|
-
/**
|
|
394
|
-
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
395
|
-
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
396
|
-
* the same TTL and expire simultaneously.
|
|
397
|
-
*
|
|
398
|
-
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
399
|
-
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
400
|
-
*/
|
|
401
|
-
ttlJitterFactor?: number;
|
|
402
|
-
/**
|
|
403
|
-
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
404
|
-
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
405
|
-
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
406
|
-
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
407
|
-
*/
|
|
408
|
-
notFoundTtl?: number;
|
|
409
|
-
/**
|
|
410
|
-
* Number of consecutive Redis errors before the circuit opens (stops
|
|
411
|
-
* attempting Redis until the cooldown elapses).
|
|
412
|
-
* Default: `5`.
|
|
413
|
-
*/
|
|
414
|
-
l2CircuitBreakerThreshold?: number;
|
|
415
|
-
/**
|
|
416
|
-
* Milliseconds the circuit stays open before transitioning to half-open
|
|
417
|
-
* (allows a single probe request to test recovery).
|
|
418
|
-
* Default: `30 000` ms (30 s).
|
|
419
|
-
*/
|
|
420
|
-
l2CircuitBreakerCooldownMs?: number;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/**
|
|
424
|
-
* CacheService — three-tier cache with stampede prevention and SWR.
|
|
2
|
+
* tricache — three-tier cache for Node.js
|
|
425
3
|
*
|
|
426
|
-
*
|
|
427
|
-
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
428
|
-
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
429
|
-
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
430
|
-
* DB → your fetchFunction (cache miss path)
|
|
4
|
+
* L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
|
|
431
5
|
*
|
|
432
|
-
*
|
|
433
|
-
*
|
|
434
|
-
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
435
|
-
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
436
|
-
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
437
|
-
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
438
|
-
* - Periodic cleanup of expired entries every 5 minutes
|
|
439
|
-
*/
|
|
440
|
-
|
|
441
|
-
declare class CacheService {
|
|
442
|
-
private readonly logger;
|
|
443
|
-
private readonly enc;
|
|
444
|
-
private readonly l1;
|
|
445
|
-
private readonly disk;
|
|
446
|
-
private readonly opts;
|
|
447
|
-
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
448
|
-
private readonly _namespace;
|
|
449
|
-
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
450
|
-
private readonly _redisDisabled;
|
|
451
|
-
private readonly inflight;
|
|
452
|
-
private readonly revalidating;
|
|
453
|
-
private readonly _l1Counters;
|
|
454
|
-
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
455
|
-
private readonly tagIndex;
|
|
456
|
-
/**
|
|
457
|
-
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
458
|
-
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
459
|
-
*/
|
|
460
|
-
private readonly dependencyIndex;
|
|
461
|
-
private redis;
|
|
462
|
-
private redisConnecting;
|
|
463
|
-
private readonly cb;
|
|
464
|
-
private snapshotLoaded;
|
|
465
|
-
private cleanupInterval;
|
|
466
|
-
private oomInterval;
|
|
467
|
-
private metricsInterval;
|
|
468
|
-
private _shutdownHandler;
|
|
469
|
-
private readonly instanceId;
|
|
470
|
-
private readonly backplaneChannel;
|
|
471
|
-
private subClient;
|
|
472
|
-
private readonly counters;
|
|
473
|
-
constructor(options?: CacheOptions);
|
|
474
|
-
/**
|
|
475
|
-
* Get (or create) the process-level singleton CacheService instance.
|
|
476
|
-
*
|
|
477
|
-
* Options are only applied on first call — subsequent calls return the
|
|
478
|
-
* existing instance regardless of options passed.
|
|
479
|
-
*
|
|
480
|
-
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
481
|
-
* with different namespaces return independent instances.
|
|
482
|
-
*/
|
|
483
|
-
static create(options?: CacheOptions): CacheService;
|
|
484
|
-
/**
|
|
485
|
-
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
486
|
-
* Useful when config is fetched from a secret store at startup.
|
|
487
|
-
*
|
|
488
|
-
* @example
|
|
489
|
-
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
490
|
-
*/
|
|
491
|
-
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
492
|
-
/** Replace the singleton (useful in tests). */
|
|
493
|
-
static reset(options?: CacheOptions): CacheService;
|
|
494
|
-
/** Derive the globalThis key for a given set of options. */
|
|
495
|
-
private static globalKey;
|
|
496
|
-
/**
|
|
497
|
-
* Prepend the configured namespace to a raw cache key.
|
|
498
|
-
* Returns the key unchanged when namespace is empty.
|
|
499
|
-
*
|
|
500
|
-
* This is the only place the namespace prefix is applied — callers always
|
|
501
|
-
* receive and provide un-prefixed keys in the public API.
|
|
502
|
-
*/
|
|
503
|
-
private nk;
|
|
504
|
-
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
505
|
-
private _jitterTtl;
|
|
506
|
-
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
507
|
-
private _startSpan;
|
|
508
|
-
private initBackplane;
|
|
509
|
-
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
510
|
-
_handleBackplaneMessage(message: string): void;
|
|
511
|
-
private publishInvalidation;
|
|
512
|
-
private getRedis;
|
|
513
|
-
writeSnapshot(altPath?: string): void;
|
|
514
|
-
loadSnapshot(): void;
|
|
515
|
-
/**
|
|
516
|
-
* Get a value from cache, or fetch and cache it.
|
|
517
|
-
*
|
|
518
|
-
* @param cacheKey - Unique key identifying this value
|
|
519
|
-
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
520
|
-
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
521
|
-
* @param opts.priority - Override the auto-inferred eviction priority
|
|
522
|
-
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
523
|
-
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
524
|
-
* is triggered proactively while the caller still receives the
|
|
525
|
-
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
526
|
-
* Requires `fetchFn` to be stable across calls.
|
|
527
|
-
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
528
|
-
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
529
|
-
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
530
|
-
* decide probabilistically rather than at a fixed threshold.
|
|
531
|
-
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
532
|
-
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
533
|
-
*/
|
|
534
|
-
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
535
|
-
priority?: CachePriority;
|
|
536
|
-
swr?: number;
|
|
537
|
-
refreshAhead?: number;
|
|
538
|
-
xfetchBeta?: number;
|
|
539
|
-
notFoundTtl?: number;
|
|
540
|
-
}): Promise<T>;
|
|
541
|
-
private _revalidate;
|
|
542
|
-
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
543
|
-
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
544
|
-
tags?: string[];
|
|
545
|
-
dependsOn?: string[];
|
|
546
|
-
}): Promise<void>;
|
|
547
|
-
/**
|
|
548
|
-
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
549
|
-
*
|
|
550
|
-
* @example
|
|
551
|
-
* await cache.delete('user:abc:profile'); // exact key
|
|
552
|
-
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
553
|
-
*/
|
|
554
|
-
delete(cacheKey: string): Promise<void>;
|
|
555
|
-
/**
|
|
556
|
-
* Atomically increment a counter in Redis. Returns the new value.
|
|
557
|
-
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
558
|
-
*/
|
|
559
|
-
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
560
|
-
/**
|
|
561
|
-
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
562
|
-
*
|
|
563
|
-
* @example
|
|
564
|
-
* await cache.clear(); // flush everything
|
|
565
|
-
* await cache.clear('user:abc'); // flush all keys for one user
|
|
566
|
-
*/
|
|
567
|
-
clear(prefix?: string): Promise<void>;
|
|
568
|
-
/**
|
|
569
|
-
* Evict L1 entries that violate the current category or global capacity limits.
|
|
570
|
-
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
571
|
-
* Returns the number of entries evicted.
|
|
572
|
-
*/
|
|
573
|
-
rebalance(): number;
|
|
574
|
-
/**
|
|
575
|
-
* Return the remaining TTL in seconds for a key currently in L1.
|
|
576
|
-
* Returns null if the key is absent from L1 or has already expired.
|
|
577
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
578
|
-
*/
|
|
579
|
-
ttl(cacheKey: string): number | null;
|
|
580
|
-
/**
|
|
581
|
-
* Return true if the key exists in L1 and has not expired.
|
|
582
|
-
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
583
|
-
*/
|
|
584
|
-
has(cacheKey: string): boolean;
|
|
585
|
-
/**
|
|
586
|
-
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
587
|
-
*
|
|
588
|
-
* @example
|
|
589
|
-
* for (const key of cache.keys()) console.log(key);
|
|
590
|
-
*/
|
|
591
|
-
keys(): Generator<string>;
|
|
592
|
-
/**
|
|
593
|
-
* Lazily yield every non-expired L1 value.
|
|
594
|
-
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
595
|
-
*
|
|
596
|
-
* @example
|
|
597
|
-
* for (const val of cache.values<User>()) console.log(val.id);
|
|
598
|
-
*/
|
|
599
|
-
values<T = unknown>(): Generator<T>;
|
|
600
|
-
/**
|
|
601
|
-
* Lazily yield every non-expired L1 [key, value] pair.
|
|
602
|
-
* Keys are stripped of their namespace prefix.
|
|
603
|
-
*
|
|
604
|
-
* @example
|
|
605
|
-
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
606
|
-
*/
|
|
607
|
-
entries<T = unknown>(): Generator<[string, T]>;
|
|
608
|
-
/**
|
|
609
|
-
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
610
|
-
* Returns `false` if the key is absent or already expired.
|
|
611
|
-
*
|
|
612
|
-
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
613
|
-
*/
|
|
614
|
-
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
615
|
-
/**
|
|
616
|
-
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
617
|
-
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
618
|
-
*
|
|
619
|
-
* @example
|
|
620
|
-
* const fresh = cache.getIfFresh('user:123');
|
|
621
|
-
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
622
|
-
*/
|
|
623
|
-
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
624
|
-
/**
|
|
625
|
-
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
626
|
-
* Preserves input ordering. Uses inflight coalescing per key.
|
|
627
|
-
*
|
|
628
|
-
* @param keys - Array of cache keys.
|
|
629
|
-
* @param fetchFn - Called with only the keys that missed L1.
|
|
630
|
-
* @param ttl - TTL in seconds for newly fetched values.
|
|
631
|
-
*/
|
|
632
|
-
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
633
|
-
/**
|
|
634
|
-
* Batch write — set multiple entries in a single call.
|
|
635
|
-
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
636
|
-
*
|
|
637
|
-
* @example
|
|
638
|
-
* await cache.mset({
|
|
639
|
-
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
640
|
-
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
641
|
-
* });
|
|
642
|
-
*/
|
|
643
|
-
mset<T = unknown>(entries: Record<string, {
|
|
644
|
-
value: T;
|
|
645
|
-
ttl?: number;
|
|
646
|
-
priority?: CachePriority;
|
|
647
|
-
tags?: string[];
|
|
648
|
-
dependsOn?: string[];
|
|
649
|
-
}>): Promise<void>;
|
|
650
|
-
/**
|
|
651
|
-
* Batch delete — delete multiple exact keys in a single call.
|
|
652
|
-
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
653
|
-
*
|
|
654
|
-
* @example
|
|
655
|
-
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
656
|
-
*/
|
|
657
|
-
mdel(keys: string[]): Promise<void>;
|
|
658
|
-
/**
|
|
659
|
-
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
660
|
-
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
661
|
-
* the local snapshot is unavailable or too stale.
|
|
662
|
-
*
|
|
663
|
-
* Returns the number of keys loaded into L1.
|
|
664
|
-
*
|
|
665
|
-
* @example
|
|
666
|
-
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
667
|
-
* const loaded = await cache.warmFromL2('org:*');
|
|
668
|
-
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
669
|
-
*/
|
|
670
|
-
warmFromL2(pattern: string): Promise<number>;
|
|
671
|
-
/**
|
|
672
|
-
* Invalidate all keys associated with a tag.
|
|
673
|
-
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
674
|
-
*
|
|
675
|
-
* @example
|
|
676
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
677
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
678
|
-
*/
|
|
679
|
-
invalidateTag(tag: string): Promise<void>;
|
|
680
|
-
/**
|
|
681
|
-
* Measure L1 / disk / Redis latency.
|
|
682
|
-
* Useful for health checks and dashboards.
|
|
683
|
-
*
|
|
684
|
-
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
685
|
-
* `l2` is `null` when Redis is disabled.
|
|
686
|
-
*/
|
|
687
|
-
ping(): Promise<CachePingResult>;
|
|
688
|
-
/**
|
|
689
|
-
* Export all live L1 entries to Redis via a single pipeline.
|
|
690
|
-
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
691
|
-
* Returns the number of keys written.
|
|
692
|
-
*/
|
|
693
|
-
drainToL2(): Promise<number>;
|
|
694
|
-
stats(): {
|
|
695
|
-
l1: {
|
|
696
|
-
entries: number;
|
|
697
|
-
sizeBytes: number;
|
|
698
|
-
sizeKB: number;
|
|
699
|
-
categories: Record<string, {
|
|
700
|
-
entries: number;
|
|
701
|
-
hits: number;
|
|
702
|
-
}>;
|
|
703
|
-
bloom: {
|
|
704
|
-
checks: number;
|
|
705
|
-
falsePositives: number;
|
|
706
|
-
};
|
|
707
|
-
compression: {
|
|
708
|
-
compressed: number;
|
|
709
|
-
uncompressed: number;
|
|
710
|
-
bytesSaved: number;
|
|
711
|
-
};
|
|
712
|
-
};
|
|
713
|
-
disk: {
|
|
714
|
-
files: number;
|
|
715
|
-
sizeKB: number;
|
|
716
|
-
maxKB: number;
|
|
717
|
-
};
|
|
718
|
-
};
|
|
719
|
-
/**
|
|
720
|
-
* Write `value` only if the key is not already cached.
|
|
721
|
-
* Returns `true` if the write happened, `false` if the key already existed.
|
|
722
|
-
*
|
|
723
|
-
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
724
|
-
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
725
|
-
* multiple instances. L1 is populated on success.
|
|
726
|
-
*
|
|
727
|
-
* @example
|
|
728
|
-
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
729
|
-
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
730
|
-
*/
|
|
731
|
-
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
732
|
-
/**
|
|
733
|
-
* Return the top-N live L1 keys by historical access frequency.
|
|
734
|
-
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
735
|
-
* whose historical frequency exceeds their current in-memory hit count.
|
|
736
|
-
*
|
|
737
|
-
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
738
|
-
* collection overhead.
|
|
739
|
-
*
|
|
740
|
-
* @param n - Maximum number of keys to return. Default: 10.
|
|
741
|
-
*
|
|
742
|
-
* @example
|
|
743
|
-
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
744
|
-
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
745
|
-
*/
|
|
746
|
-
hotKeys(n?: number): Array<{
|
|
747
|
-
key: string;
|
|
748
|
-
hits: number;
|
|
749
|
-
sizeBytes: number;
|
|
750
|
-
}>;
|
|
751
|
-
/**
|
|
752
|
-
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
753
|
-
* pattern that may contain `*` wildcards).
|
|
754
|
-
*/
|
|
755
|
-
private _matchesGlob;
|
|
756
|
-
/**
|
|
757
|
-
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
758
|
-
* that was registered via `dependsOn` and whose source pattern matches.
|
|
759
|
-
*/
|
|
760
|
-
private _cascadeDependencies;
|
|
761
|
-
/** Return a full metrics snapshot. */
|
|
762
|
-
metrics(): CacheMetrics;
|
|
763
|
-
/**
|
|
764
|
-
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
765
|
-
* Paste the result into your `/metrics` endpoint.
|
|
766
|
-
*
|
|
767
|
-
* @param m - Snapshot returned by `cache.metrics()`
|
|
768
|
-
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
769
|
-
*/
|
|
770
|
-
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
771
|
-
/** Close Redis connections and stop all background timers. */
|
|
772
|
-
destroy(): Promise<void>;
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
/**
|
|
776
|
-
* Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
|
|
777
|
-
*
|
|
778
|
-
* Four modes are supported via the `encryptionMode` CacheOption:
|
|
779
|
-
*
|
|
780
|
-
* ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
|
|
781
|
-
* │ Mode │ Key bytes │ Notes │
|
|
782
|
-
* ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
|
|
783
|
-
* │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
|
|
784
|
-
* │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
|
|
785
|
-
* │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
|
|
786
|
-
* │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
|
|
787
|
-
* │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
|
|
788
|
-
* │ │ │ Use only for dev or non-sensitive data. │
|
|
789
|
-
* └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
|
|
790
|
-
*
|
|
791
|
-
* Key generation:
|
|
792
|
-
* AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
793
|
-
* AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
794
|
-
* CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
795
|
-
* XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
796
|
-
*
|
|
797
|
-
* Redis envelope formats:
|
|
798
|
-
* enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
|
|
799
|
-
* a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
|
|
800
|
-
* ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
|
|
801
|
-
* xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
|
|
802
|
-
*
|
|
803
|
-
* Disk envelope formats:
|
|
804
|
-
* TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
|
|
805
|
-
* TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
|
|
806
|
-
* TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
|
|
807
|
-
* TRIC1XOR | key⊕data[N] ← XOR
|
|
808
|
-
*/
|
|
809
|
-
|
|
810
|
-
/** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
|
|
811
|
-
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
812
|
-
declare class CacheEncryption {
|
|
813
|
-
private _key;
|
|
814
|
-
private readonly _mode;
|
|
815
|
-
private _prevKey;
|
|
816
|
-
private _prevMode;
|
|
817
|
-
private readonly _ivPool;
|
|
818
|
-
private _ivOffset;
|
|
819
|
-
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
820
|
-
private _nextIV;
|
|
821
|
-
private readonly _ctrIvPool;
|
|
822
|
-
private _ctrIvOffset;
|
|
823
|
-
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
824
|
-
private _nextCtrIV;
|
|
825
|
-
/**
|
|
826
|
-
* XOR `data` with the key, cycling through key bytes.
|
|
827
|
-
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
828
|
-
*
|
|
829
|
-
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
830
|
-
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
831
|
-
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
832
|
-
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
833
|
-
*
|
|
834
|
-
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
835
|
-
*/
|
|
836
|
-
private _xorBuffer;
|
|
837
|
-
constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
|
|
838
|
-
get isEnabled(): boolean;
|
|
839
|
-
/**
|
|
840
|
-
* Encrypt a string for Redis storage.
|
|
841
|
-
* Returns a mode-prefixed base64 string when a key is configured;
|
|
842
|
-
* otherwise returns the original string unchanged (backward-compatible).
|
|
843
|
-
*/
|
|
844
|
-
encrypt(plaintext: string): string;
|
|
845
|
-
/**
|
|
846
|
-
* Decrypt a Redis value.
|
|
847
|
-
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
848
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
849
|
-
*/
|
|
850
|
-
decrypt(value: string): string;
|
|
851
|
-
private _decryptWithKey;
|
|
852
|
-
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
853
|
-
encryptBuffer(data: Buffer): Buffer;
|
|
854
|
-
/**
|
|
855
|
-
* Decrypt a raw Buffer from disk/snapshot.
|
|
856
|
-
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
857
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
858
|
-
*/
|
|
859
|
-
decryptBuffer(data: Buffer): Buffer;
|
|
860
|
-
private _decryptBufferWithKey;
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
/**
|
|
864
|
-
* SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
|
|
865
|
-
*
|
|
866
|
-
* Features:
|
|
867
|
-
* - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
|
|
868
|
-
* - msgpackr compression for entries ≥ 512 bytes
|
|
869
|
-
* - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
|
|
870
|
-
* - Priority-weighted adaptive eviction (LFU × LRU × priority score)
|
|
871
|
-
* - Stale-While-Revalidate soft-expiry support (isStale flag on get())
|
|
872
|
-
* - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
|
|
873
|
-
* - Periodic cleanup of hard-expired entries + bloom filter rebuild
|
|
874
|
-
* - Process-level singleton via globalThis (survives Next.js hot reloads)
|
|
875
|
-
*/
|
|
876
|
-
|
|
877
|
-
interface SmartMemoryCacheOptions {
|
|
878
|
-
maxBytes: number;
|
|
879
|
-
maxEntries: number;
|
|
880
|
-
categories: Record<string, CategoryLimit>;
|
|
881
|
-
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
882
|
-
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
883
|
-
logger: ILogger;
|
|
884
|
-
}
|
|
885
|
-
declare class SmartMemoryCache {
|
|
886
|
-
private readonly cache;
|
|
887
|
-
private readonly opts;
|
|
888
|
-
private bloom;
|
|
889
|
-
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
890
|
-
private readonly categoryPrefixes;
|
|
891
|
-
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
892
|
-
private readonly sketch;
|
|
893
|
-
private totalSize;
|
|
894
|
-
private categoryCount;
|
|
895
|
-
private categorySize;
|
|
896
|
-
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
897
|
-
private categoryKeys;
|
|
898
|
-
private bloomChecks;
|
|
899
|
-
private bloomFalsePos;
|
|
900
|
-
private compressions;
|
|
901
|
-
private categoryHits;
|
|
902
|
-
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
903
|
-
private _bloomDirtyCount;
|
|
904
|
-
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
905
|
-
private recalculateStats;
|
|
906
|
-
private getCategory;
|
|
907
|
-
private getCategoryLimit;
|
|
908
|
-
private _delete;
|
|
909
|
-
private ensureCapacity;
|
|
910
|
-
private score;
|
|
911
|
-
/**
|
|
912
|
-
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
913
|
-
* saturated the filter past its ~1 % FP capacity.
|
|
914
|
-
*
|
|
915
|
-
* Trigger: (insertions − live entries) > maxCapacity
|
|
916
|
-
*
|
|
917
|
-
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
918
|
-
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
919
|
-
* cache holds more entries than the filter's rated capacity — which would
|
|
920
|
-
* stall the write path entirely.
|
|
921
|
-
*
|
|
922
|
-
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
923
|
-
*/
|
|
924
|
-
private maybeRebuildBloom;
|
|
925
|
-
private smartEvict;
|
|
926
|
-
get(key: string): CacheHit | null;
|
|
927
|
-
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
|
|
928
|
-
delete(key: string): boolean;
|
|
929
|
-
private keysMatchingPattern;
|
|
930
|
-
deletePattern(pattern: string): number;
|
|
931
|
-
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
932
|
-
clear(prefix?: string): number;
|
|
933
|
-
/**
|
|
934
|
-
* Evict entries that violate current category or global limits.
|
|
935
|
-
* Returns the number of entries evicted.
|
|
936
|
-
*/
|
|
937
|
-
rebalance(): number;
|
|
938
|
-
/**
|
|
939
|
-
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
940
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
941
|
-
*/
|
|
942
|
-
ttl(key: string): number | null;
|
|
943
|
-
/**
|
|
944
|
-
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
945
|
-
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
946
|
-
* exceeds the configured threshold.
|
|
947
|
-
*
|
|
948
|
-
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
949
|
-
* @returns Number of entries evicted
|
|
950
|
-
*/
|
|
951
|
-
evictPercentage(pct: number): number;
|
|
952
|
-
cleanup(): number;
|
|
953
|
-
exportEntries(forbiddenPrefixes: readonly string[]): Array<{
|
|
954
|
-
key: string;
|
|
955
|
-
entry: SmartCacheEntry;
|
|
956
|
-
}>;
|
|
957
|
-
importEntries(entries: Array<{
|
|
958
|
-
key: string;
|
|
959
|
-
entry: SmartCacheEntry;
|
|
960
|
-
}>, forbiddenPrefixes: readonly string[]): number;
|
|
961
|
-
/**
|
|
962
|
-
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
963
|
-
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
964
|
-
* are silently skipped.
|
|
965
|
-
*/
|
|
966
|
-
liveEntries(): Generator<[string, SmartCacheEntry]>;
|
|
967
|
-
/**
|
|
968
|
-
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
969
|
-
* Use this instead of liveEntries() when you only need keys.
|
|
970
|
-
*/
|
|
971
|
-
liveKeys(): Generator<string>;
|
|
972
|
-
/**
|
|
973
|
-
* Yields only the resolved values of live entries.
|
|
974
|
-
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
975
|
-
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
976
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
977
|
-
*/
|
|
978
|
-
liveValues(): Generator<unknown>;
|
|
979
|
-
get size(): number;
|
|
980
|
-
get memoryUsage(): number;
|
|
981
|
-
getStats(): {
|
|
982
|
-
entries: number;
|
|
983
|
-
sizeBytes: number;
|
|
984
|
-
sizeKB: number;
|
|
985
|
-
categories: Record<string, {
|
|
986
|
-
entries: number;
|
|
987
|
-
hits: number;
|
|
988
|
-
}>;
|
|
989
|
-
bloom: {
|
|
990
|
-
checks: number;
|
|
991
|
-
falsePositives: number;
|
|
992
|
-
};
|
|
993
|
-
compression: {
|
|
994
|
-
compressed: number;
|
|
995
|
-
uncompressed: number;
|
|
996
|
-
bytesSaved: number;
|
|
997
|
-
};
|
|
998
|
-
};
|
|
999
|
-
/**
|
|
1000
|
-
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
1001
|
-
* Does NOT count as a hit or perform SWR logic.
|
|
1002
|
-
*/
|
|
1003
|
-
getEntry(key: string): SmartCacheEntry | undefined;
|
|
1004
|
-
/**
|
|
1005
|
-
* Return true if the key exists in L1 and has not expired.
|
|
1006
|
-
* Uses the bloom filter as a fast negative check.
|
|
1007
|
-
*/
|
|
1008
|
-
has(key: string): boolean;
|
|
1009
|
-
/**
|
|
1010
|
-
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1011
|
-
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1012
|
-
*/
|
|
1013
|
-
touch(key: string, newTtlMs: number): boolean;
|
|
1014
|
-
/**
|
|
1015
|
-
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1016
|
-
* Returns `false` if the key is absent or already expired.
|
|
1017
|
-
*/
|
|
1018
|
-
bumpExpiry(key: string, additionalMs: number): boolean;
|
|
1019
|
-
bloomMightContain(key: string): boolean;
|
|
1020
|
-
bloomStats(): {
|
|
1021
|
-
bitsSet: number;
|
|
1022
|
-
fillFactor: number;
|
|
1023
|
-
} | {
|
|
1024
|
-
bitsSet: number;
|
|
1025
|
-
fillFactor: number;
|
|
1026
|
-
};
|
|
1027
|
-
/**
|
|
1028
|
-
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1029
|
-
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1030
|
-
* Useful for diagnosing which keys are driving cache pressure.
|
|
1031
|
-
*
|
|
1032
|
-
* @param n - Maximum number of entries to return. Default: 10.
|
|
1033
|
-
*/
|
|
1034
|
-
hotKeys(n: number): Array<{
|
|
1035
|
-
key: string;
|
|
1036
|
-
hits: number;
|
|
1037
|
-
sizeBytes: number;
|
|
1038
|
-
}>;
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
/**
|
|
1042
|
-
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
6
|
+
* Quick start:
|
|
7
|
+
* import { CacheService, CachePriority } from 'tricache';
|
|
1043
8
|
*
|
|
1044
|
-
*
|
|
1045
|
-
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
1046
|
-
* vs 10–100 ms DB round-trip).
|
|
9
|
+
* const cache = CacheService.create({ redisHost: 'localhost' });
|
|
1047
10
|
*
|
|
1048
|
-
*
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1051
|
-
*
|
|
1052
|
-
*
|
|
11
|
+
* const user = await cache.get(
|
|
12
|
+
* `user:${userId}`,
|
|
13
|
+
* () => db.users.findById(userId),
|
|
14
|
+
* 300, // 5-minute TTL
|
|
15
|
+
* );
|
|
1053
16
|
*
|
|
1054
|
-
*
|
|
17
|
+
* await cache.delete(`user:${userId}`);
|
|
1055
18
|
*/
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
logger: ILogger;
|
|
1064
|
-
}
|
|
1065
|
-
declare class DiskTier {
|
|
1066
|
-
private readonly opts;
|
|
1067
|
-
private dirReady;
|
|
1068
|
-
private diskUsageBytes;
|
|
1069
|
-
private usageCounted;
|
|
1070
|
-
private fileCount;
|
|
1071
|
-
constructor(opts: DiskTierOptions);
|
|
1072
|
-
private ensureDir;
|
|
1073
|
-
private ensureUsageCounted;
|
|
1074
|
-
/**
|
|
1075
|
-
* Map a cache key to its on-disk path.
|
|
1076
|
-
*
|
|
1077
|
-
* Files are sharded into two-character hex prefix subdirectories to avoid
|
|
1078
|
-
* putting thousands of flat files into a single directory node — which
|
|
1079
|
-
* degrades EXT4/NTFS performance at scale.
|
|
1080
|
-
*
|
|
1081
|
-
* key → SHA-256 hex e3b0c442...
|
|
1082
|
-
* path → {dir}/e3/e3b0c442...
|
|
1083
|
-
*/
|
|
1084
|
-
private keyToPath;
|
|
1085
|
-
/**
|
|
1086
|
-
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
1087
|
-
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
1088
|
-
* files written by older versions).
|
|
1089
|
-
*/
|
|
1090
|
-
private walkCacheFiles;
|
|
1091
|
-
private isForbidden;
|
|
1092
|
-
private encrypt;
|
|
1093
|
-
private decrypt;
|
|
1094
|
-
/**
|
|
1095
|
-
* Spill an evicted L1 entry to disk.
|
|
1096
|
-
*
|
|
1097
|
-
* Returns a Promise that resolves when the file is durably written. Callers
|
|
1098
|
-
* that treat the spill as fire-and-forget should do:
|
|
1099
|
-
* `void disk.save(key, entry)`
|
|
1100
|
-
*
|
|
1101
|
-
* Implementation notes:
|
|
1102
|
-
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
1103
|
-
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
1104
|
-
* on any external resource.
|
|
1105
|
-
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
1106
|
-
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
1107
|
-
*/
|
|
1108
|
-
save(key: string, entry: DiskCacheEntry): Promise<void>;
|
|
1109
|
-
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
1110
|
-
load(key: string): DiskCacheEntry | null;
|
|
1111
|
-
/** Explicitly delete a key from disk (cache invalidation). */
|
|
1112
|
-
delete(key: string): void;
|
|
1113
|
-
/** Purge all expired entries. Returns number deleted. */
|
|
1114
|
-
purgeExpired(): number;
|
|
1115
|
-
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1116
|
-
clear(): number;
|
|
1117
|
-
get stats(): {
|
|
1118
|
-
files: number;
|
|
1119
|
-
sizeKB: number;
|
|
1120
|
-
maxKB: number;
|
|
1121
|
-
};
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
declare class WasmBloomFilter {
|
|
1125
|
-
private readonly exports;
|
|
1126
|
-
private readonly mem;
|
|
1127
|
-
private readonly encoder;
|
|
1128
|
-
private readonly numBits;
|
|
1129
|
-
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
1130
|
-
private readonly _maxCapacity;
|
|
1131
|
-
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
1132
|
-
private _insertionCount;
|
|
1133
|
-
constructor();
|
|
1134
|
-
private writeKey;
|
|
1135
|
-
add(key: string): void;
|
|
1136
|
-
mightContain(key: string): boolean;
|
|
1137
|
-
reset(): void;
|
|
1138
|
-
rebuild(keys: Iterable<string>): void;
|
|
1139
|
-
get stats(): {
|
|
1140
|
-
bitsSet: number;
|
|
1141
|
-
fillFactor: number;
|
|
1142
|
-
};
|
|
1143
|
-
/** Number of add() calls since last reset/rebuild. */
|
|
1144
|
-
get insertions(): number;
|
|
1145
|
-
/**
|
|
1146
|
-
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
1147
|
-
* Exact formula for k=7 hash rounds, m=100 000 bits:
|
|
1148
|
-
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
|
|
1149
|
-
*/
|
|
1150
|
-
get maxCapacity(): number;
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
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 };
|
|
19
|
+
export { CacheService } from './cache-service';
|
|
20
|
+
export { CacheEncryption, type EncryptionMode } from './encryption';
|
|
21
|
+
export { SmartMemoryCache } from './smart-memory-cache';
|
|
22
|
+
export { DiskTier } from './disk-tier';
|
|
23
|
+
export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
24
|
+
export { CachePriority, consoleLogger, type ILogger, type CacheOptions, type CacheMetrics, type CategoryLimit, type SmartCacheEntry, type DiskCacheEntry, type CacheHit, type EvictionReason, type CachePingResult, type ICacheTracer, type ICacheSpan, } from './types';
|
|
25
|
+
//# sourceMappingURL=index.d.ts.map
|