tricache 0.1.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/LICENSE +21 -0
- package/README.md +438 -0
- package/dist/index.cjs +1784 -0
- package/dist/index.d.cts +718 -0
- package/dist/index.d.ts +718 -0
- package/dist/index.js +1741 -0
- package/package.json +64 -0
- package/src/cache-service.ts +866 -0
- package/src/disk-tier.ts +300 -0
- package/src/encryption.ts +340 -0
- package/src/index.ts +36 -0
- package/src/smart-memory-cache.ts +472 -0
- package/src/types.ts +317 -0
- package/src/wasm/bloom-filter-wasm.ts +117 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache — shared types and interfaces
|
|
3
|
+
*/
|
|
4
|
+
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
5
|
+
interface ILogger {
|
|
6
|
+
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
7
|
+
info(msg: string, meta?: Record<string, unknown>): void;
|
|
8
|
+
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
9
|
+
error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
|
|
10
|
+
}
|
|
11
|
+
/** Default no-op logger — swap out via CacheService options */
|
|
12
|
+
declare const consoleLogger: ILogger;
|
|
13
|
+
/** Priority levels for L1 eviction — higher = less likely to be evicted */
|
|
14
|
+
declare enum CachePriority {
|
|
15
|
+
LOW = 1,// Easily regenerated (analytics, reports)
|
|
16
|
+
NORMAL = 2,// General data
|
|
17
|
+
HIGH = 3,// Frequently accessed (profiles, config)
|
|
18
|
+
CRITICAL = 4
|
|
19
|
+
}
|
|
20
|
+
/** Internal representation of a single cache entry in the L1 Map */
|
|
21
|
+
interface SmartCacheEntry {
|
|
22
|
+
/** msgpackr-packed binary payload */
|
|
23
|
+
data: Buffer;
|
|
24
|
+
/** always true for entries written by the current code;
|
|
25
|
+
* may be false in legacy snapshots/disk files — handled transparently on import */
|
|
26
|
+
isCompressed: boolean;
|
|
27
|
+
/** Hard expiry — entry is deleted after this timestamp */
|
|
28
|
+
expiresAt: number;
|
|
29
|
+
/** SWR soft expiry — serve stale + revalidate in background when past this */
|
|
30
|
+
staleAt?: number;
|
|
31
|
+
/** Exact byte size of the stored value */
|
|
32
|
+
size: number;
|
|
33
|
+
/** Access count (LFU numerator) */
|
|
34
|
+
hits: number;
|
|
35
|
+
/** Last access timestamp (LRU comparator) */
|
|
36
|
+
lastAccess: number;
|
|
37
|
+
/** Eviction priority */
|
|
38
|
+
priority: CachePriority;
|
|
39
|
+
}
|
|
40
|
+
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
41
|
+
interface CacheHit {
|
|
42
|
+
value: unknown;
|
|
43
|
+
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
44
|
+
isStale: boolean;
|
|
45
|
+
}
|
|
46
|
+
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
47
|
+
* legacy disk files written by older versions may have a JSON string in data) */
|
|
48
|
+
interface DiskCacheEntry {
|
|
49
|
+
data: string | Buffer | Uint8Array;
|
|
50
|
+
isCompressed: boolean;
|
|
51
|
+
expiresAt: number;
|
|
52
|
+
staleAt?: number;
|
|
53
|
+
size: number;
|
|
54
|
+
hits: number;
|
|
55
|
+
lastAccess: number;
|
|
56
|
+
priority: number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Snapshot of runtime metrics for a CacheService instance.
|
|
60
|
+
* Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
|
|
61
|
+
* Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
|
|
62
|
+
*/
|
|
63
|
+
interface CacheMetrics {
|
|
64
|
+
/** Configured namespace (empty string = no namespace) */
|
|
65
|
+
namespace: string;
|
|
66
|
+
/** Milliseconds since the CacheService instance was constructed */
|
|
67
|
+
uptimeMs: number;
|
|
68
|
+
gets: {
|
|
69
|
+
total: number;
|
|
70
|
+
l1Hits: number;
|
|
71
|
+
/** Fraction of gets served from L1 RAM cache (0–1) */
|
|
72
|
+
l1HitRate: number;
|
|
73
|
+
diskHits: number;
|
|
74
|
+
/** Fraction of gets served from L1.5 disk tier (0–1) */
|
|
75
|
+
diskHitRate: number;
|
|
76
|
+
l2Hits: number;
|
|
77
|
+
/** Fraction of gets served from L2 Redis (0–1) */
|
|
78
|
+
l2HitRate: number;
|
|
79
|
+
/** fetchFn calls (cache misses that fell through to the DB) */
|
|
80
|
+
fetches: number;
|
|
81
|
+
/** Fraction of gets that called fetchFn (0–1) */
|
|
82
|
+
fetchRate: number;
|
|
83
|
+
/** Concurrent get() calls deduplicated by the stampede guard */
|
|
84
|
+
stampedePrevented: number;
|
|
85
|
+
};
|
|
86
|
+
sets: {
|
|
87
|
+
total: number;
|
|
88
|
+
};
|
|
89
|
+
deletes: {
|
|
90
|
+
total: number;
|
|
91
|
+
};
|
|
92
|
+
revalidations: {
|
|
93
|
+
total: number;
|
|
94
|
+
};
|
|
95
|
+
bloom: {
|
|
96
|
+
/** Total bloom-filter checks (get() calls that passed prefix filter) */
|
|
97
|
+
checksTotal: number;
|
|
98
|
+
/**
|
|
99
|
+
* Times the filter said "might contain" but the key was absent in L1.
|
|
100
|
+
* A high rate suggests the bloom filter capacity needs increasing.
|
|
101
|
+
*/
|
|
102
|
+
falsePositives: number;
|
|
103
|
+
/** falsePositives / checksTotal (0–1; ideal < 0.01) */
|
|
104
|
+
falsePositiveRate: number;
|
|
105
|
+
};
|
|
106
|
+
compression: {
|
|
107
|
+
entriesCompressed: number;
|
|
108
|
+
entriesUncompressed: number;
|
|
109
|
+
/** Approximate bytes saved by msgpackr vs raw JSON */
|
|
110
|
+
bytesSaved: number;
|
|
111
|
+
};
|
|
112
|
+
/** Pub/Sub invalidation backplane statistics */
|
|
113
|
+
backplane: {
|
|
114
|
+
enabled: boolean;
|
|
115
|
+
/** Invalidation messages published to other instances */
|
|
116
|
+
sent: number;
|
|
117
|
+
/** Invalidation messages received from other instances */
|
|
118
|
+
received: number;
|
|
119
|
+
/** Own messages silently skipped (prevents double-eviction) */
|
|
120
|
+
skipped: number;
|
|
121
|
+
};
|
|
122
|
+
/** OOM guard statistics */
|
|
123
|
+
oom: {
|
|
124
|
+
enabled: boolean;
|
|
125
|
+
/** Number of emergency L1 eviction rounds triggered */
|
|
126
|
+
evictions: number;
|
|
127
|
+
/** Timestamp of the most recent OOM eviction, or null */
|
|
128
|
+
lastTriggeredAt: number | null;
|
|
129
|
+
};
|
|
130
|
+
l1: {
|
|
131
|
+
entries: number;
|
|
132
|
+
sizeBytes: number;
|
|
133
|
+
maxBytes: number;
|
|
134
|
+
};
|
|
135
|
+
disk: {
|
|
136
|
+
files: number;
|
|
137
|
+
sizeKB: number;
|
|
138
|
+
maxKB: number;
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Per-category memory limits for L1 */
|
|
142
|
+
interface CategoryLimit {
|
|
143
|
+
maxEntries: number;
|
|
144
|
+
maxSizeBytes: number;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Options accepted by CacheService.create()
|
|
148
|
+
*
|
|
149
|
+
* All fields are optional — sensible defaults are used when omitted.
|
|
150
|
+
*/
|
|
151
|
+
interface CacheOptions {
|
|
152
|
+
/**
|
|
153
|
+
* Plug in your own logger (pino, winston, bunyan, …).
|
|
154
|
+
* Defaults to a minimal console logger that only prints warn/error.
|
|
155
|
+
*/
|
|
156
|
+
logger?: ILogger;
|
|
157
|
+
/** Max total bytes held in L1 RAM cache. Default: 200 MB */
|
|
158
|
+
l1MaxBytes?: number;
|
|
159
|
+
/** Max total entries in L1. Default: 2000 */
|
|
160
|
+
l1MaxEntries?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
163
|
+
* Merged over the built-in defaults.
|
|
164
|
+
*/
|
|
165
|
+
categoryLimits?: Record<string, CategoryLimit>;
|
|
166
|
+
/**
|
|
167
|
+
* Key prefixes that are never written to disk snapshots or the disk tier.
|
|
168
|
+
* Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
|
|
169
|
+
*/
|
|
170
|
+
forbiddenSnapshotPrefixes?: string[];
|
|
171
|
+
/** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
|
|
172
|
+
diskCacheDir?: string;
|
|
173
|
+
/** Max total bytes for the disk tier. Default: 500 MB */
|
|
174
|
+
diskMaxBytes?: number;
|
|
175
|
+
/** Max bytes for a single disk entry. Default: 10 MB */
|
|
176
|
+
diskEntryMaxBytes?: number;
|
|
177
|
+
/**
|
|
178
|
+
* Redis/Valkey hostname (no `redis://` prefix).
|
|
179
|
+
* Falls back to the `REDIS_HOST` environment variable.
|
|
180
|
+
* When neither is provided, L2 is disabled.
|
|
181
|
+
*/
|
|
182
|
+
redisHost?: string;
|
|
183
|
+
/** Redis port. Default: 6379 */
|
|
184
|
+
redisPort?: number;
|
|
185
|
+
/**
|
|
186
|
+
* Whether to enable TLS for the Redis connection. Default: true in production,
|
|
187
|
+
* false otherwise.
|
|
188
|
+
*/
|
|
189
|
+
redisTls?: boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Set to `true` to disable L2 Redis entirely (e.g. when running single-process
|
|
192
|
+
* services that don't need distributed caching). Default: false in production,
|
|
193
|
+
* true in development.
|
|
194
|
+
*/
|
|
195
|
+
disableRedis?: boolean;
|
|
196
|
+
/**
|
|
197
|
+
* Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
|
|
198
|
+
* disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
|
|
199
|
+
* If not provided in production, a warning is logged and data is stored plaintext.
|
|
200
|
+
*/
|
|
201
|
+
encryptionKey?: string;
|
|
202
|
+
/**
|
|
203
|
+
* Encryption algorithm used for L2 (Redis) values and disk-tier files.
|
|
204
|
+
* - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
|
|
205
|
+
* - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
|
|
206
|
+
* - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
|
|
207
|
+
* Any key length (minimum 16 bytes recommended).
|
|
208
|
+
* Use for dev environments or non-sensitive data only.
|
|
209
|
+
* Default: `'aes-256-gcm'`
|
|
210
|
+
*/
|
|
211
|
+
encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
212
|
+
/**
|
|
213
|
+
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
214
|
+
* on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
|
|
215
|
+
*/
|
|
216
|
+
snapshotPath?: string;
|
|
217
|
+
/**
|
|
218
|
+
* Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
|
|
219
|
+
*/
|
|
220
|
+
snapshotMaxAgeMs?: number;
|
|
221
|
+
/**
|
|
222
|
+
* Optional namespace prefix for all cache keys.
|
|
223
|
+
*
|
|
224
|
+
* When set, every key is transparently stored as `${namespace}:${key}` in
|
|
225
|
+
* L1, L1.5 (disk), and L2 (Redis). This enables:
|
|
226
|
+
* - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
|
|
227
|
+
* — tenants sharing the same Redis instance or disk dir are fully isolated.
|
|
228
|
+
* - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
|
|
229
|
+
* - **Service-level scoping**: microservices sharing one Redis without key collisions.
|
|
230
|
+
*
|
|
231
|
+
* Consumers never see the prefix — `get('user:1')` behaves identically
|
|
232
|
+
* whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
|
|
233
|
+
* scope to the namespace.
|
|
234
|
+
*
|
|
235
|
+
* The process-level singleton, disk cache directory, and cold-start snapshot
|
|
236
|
+
* path are all scoped per namespace, so two `CacheService.create()` calls
|
|
237
|
+
* with different namespaces return completely independent instances.
|
|
238
|
+
*
|
|
239
|
+
* Default: `''` (no prefix)
|
|
240
|
+
*/
|
|
241
|
+
namespace?: string;
|
|
242
|
+
/**
|
|
243
|
+
* Enable Redis Pub/Sub invalidation backplane so every running instance
|
|
244
|
+
* evicts a key from its L1 when any peer calls `set()` or `delete()`.
|
|
245
|
+
*
|
|
246
|
+
* Gives you sub-microsecond in-process cache speed with cluster-wide
|
|
247
|
+
* consistency across all your app servers.
|
|
248
|
+
*
|
|
249
|
+
* Default: `true` (auto-activates when Redis is available).
|
|
250
|
+
* Set to `false` for single-process services or eventual-consistency scenarios.
|
|
251
|
+
*/
|
|
252
|
+
invalidationBackplane?: boolean;
|
|
253
|
+
/**
|
|
254
|
+
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
255
|
+
* `oomHeapThreshold`, a fraction of the coldest L1 entries are
|
|
256
|
+
* emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
|
|
257
|
+
* Docker/Kubernetes containers with tight memory limits.
|
|
258
|
+
*
|
|
259
|
+
* Default: `true`
|
|
260
|
+
*/
|
|
261
|
+
oomProtection?: boolean;
|
|
262
|
+
/**
|
|
263
|
+
* Heap-used / heap-total ratio that triggers emergency eviction.
|
|
264
|
+
* Default: `0.85` (85 %)
|
|
265
|
+
*/
|
|
266
|
+
oomHeapThreshold?: number;
|
|
267
|
+
/** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
|
|
268
|
+
oomCheckIntervalMs?: number;
|
|
269
|
+
/** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
|
|
270
|
+
oomEvictPercent?: number;
|
|
271
|
+
/**
|
|
272
|
+
* Callback invoked periodically with a `CacheMetrics` snapshot.
|
|
273
|
+
* Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
|
|
277
|
+
*/
|
|
278
|
+
onMetrics?: (metrics: CacheMetrics) => void;
|
|
279
|
+
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
280
|
+
metricsIntervalMs?: number;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* CacheService — three-tier cache with stampede prevention and SWR.
|
|
285
|
+
*
|
|
286
|
+
* Architecture:
|
|
287
|
+
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
288
|
+
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
289
|
+
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
290
|
+
* DB → your fetchFunction (cache miss path)
|
|
291
|
+
*
|
|
292
|
+
* Key features:
|
|
293
|
+
* - Thundering-herd / cache-stampede prevention (inflight Promise registry)
|
|
294
|
+
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
295
|
+
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
296
|
+
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
297
|
+
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
298
|
+
* - Periodic cleanup of expired entries every 5 minutes
|
|
299
|
+
*/
|
|
300
|
+
|
|
301
|
+
declare class CacheService {
|
|
302
|
+
private readonly logger;
|
|
303
|
+
private readonly enc;
|
|
304
|
+
private readonly l1;
|
|
305
|
+
private readonly disk;
|
|
306
|
+
private readonly opts;
|
|
307
|
+
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
308
|
+
private readonly _namespace;
|
|
309
|
+
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
310
|
+
private readonly _redisDisabled;
|
|
311
|
+
private readonly inflight;
|
|
312
|
+
private readonly revalidating;
|
|
313
|
+
private redis;
|
|
314
|
+
private redisConnecting;
|
|
315
|
+
private snapshotLoaded;
|
|
316
|
+
private cleanupInterval;
|
|
317
|
+
private oomInterval;
|
|
318
|
+
private metricsInterval;
|
|
319
|
+
private _shutdownHandler;
|
|
320
|
+
private readonly instanceId;
|
|
321
|
+
private readonly backplaneChannel;
|
|
322
|
+
private subClient;
|
|
323
|
+
private readonly counters;
|
|
324
|
+
constructor(options?: CacheOptions);
|
|
325
|
+
/**
|
|
326
|
+
* Get (or create) the process-level singleton CacheService instance.
|
|
327
|
+
*
|
|
328
|
+
* Options are only applied on first call — subsequent calls return the
|
|
329
|
+
* existing instance regardless of options passed.
|
|
330
|
+
*
|
|
331
|
+
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
332
|
+
* with different namespaces return independent instances.
|
|
333
|
+
*/
|
|
334
|
+
static create(options?: CacheOptions): CacheService;
|
|
335
|
+
/** Replace the singleton (useful in tests). */
|
|
336
|
+
static reset(options?: CacheOptions): CacheService;
|
|
337
|
+
/** Derive the globalThis key for a given set of options. */
|
|
338
|
+
private static globalKey;
|
|
339
|
+
/**
|
|
340
|
+
* Prepend the configured namespace to a raw cache key.
|
|
341
|
+
* Returns the key unchanged when namespace is empty.
|
|
342
|
+
*
|
|
343
|
+
* This is the only place the namespace prefix is applied — callers always
|
|
344
|
+
* receive and provide un-prefixed keys in the public API.
|
|
345
|
+
*/
|
|
346
|
+
private nk;
|
|
347
|
+
private initBackplane;
|
|
348
|
+
private publishInvalidation;
|
|
349
|
+
private getRedis;
|
|
350
|
+
writeSnapshot(): void;
|
|
351
|
+
loadSnapshot(): void;
|
|
352
|
+
/**
|
|
353
|
+
* Get a value from cache, or fetch and cache it.
|
|
354
|
+
*
|
|
355
|
+
* @param cacheKey - Unique key identifying this value
|
|
356
|
+
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
357
|
+
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
358
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
359
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
|
|
360
|
+
* alive for this many extra seconds after TTL; callers get stale data
|
|
361
|
+
* instantly while a background refresh runs. Default: 0 (disabled).
|
|
362
|
+
*/
|
|
363
|
+
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
364
|
+
priority?: CachePriority;
|
|
365
|
+
swr?: number;
|
|
366
|
+
}): Promise<T>;
|
|
367
|
+
private _revalidate;
|
|
368
|
+
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
369
|
+
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority): Promise<void>;
|
|
370
|
+
/**
|
|
371
|
+
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
372
|
+
*
|
|
373
|
+
* @example
|
|
374
|
+
* await cache.delete('user:abc:profile'); // exact key
|
|
375
|
+
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
376
|
+
*/
|
|
377
|
+
delete(cacheKey: string): Promise<void>;
|
|
378
|
+
/**
|
|
379
|
+
* Atomically increment a counter in Redis. Returns the new value.
|
|
380
|
+
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
381
|
+
*/
|
|
382
|
+
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
383
|
+
stats(): {
|
|
384
|
+
l1: {
|
|
385
|
+
entries: number;
|
|
386
|
+
sizeKB: number;
|
|
387
|
+
categories: Record<string, number>;
|
|
388
|
+
bloom: {
|
|
389
|
+
checks: number;
|
|
390
|
+
falsePositives: number;
|
|
391
|
+
};
|
|
392
|
+
compression: {
|
|
393
|
+
compressed: number;
|
|
394
|
+
uncompressed: number;
|
|
395
|
+
bytesSaved: number;
|
|
396
|
+
};
|
|
397
|
+
};
|
|
398
|
+
disk: {
|
|
399
|
+
files: number;
|
|
400
|
+
sizeKB: number;
|
|
401
|
+
maxKB: number;
|
|
402
|
+
};
|
|
403
|
+
};
|
|
404
|
+
/** Return a full metrics snapshot. */
|
|
405
|
+
metrics(): CacheMetrics;
|
|
406
|
+
/**
|
|
407
|
+
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
408
|
+
* Paste the result into your `/metrics` endpoint.
|
|
409
|
+
*
|
|
410
|
+
* @param m - Snapshot returned by `cache.metrics()`
|
|
411
|
+
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
412
|
+
*/
|
|
413
|
+
static toPrometheusText(m: CacheMetrics, prefix?: string): string;
|
|
414
|
+
/** Close Redis connections and stop all background timers. */
|
|
415
|
+
destroy(): Promise<void>;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
|
|
420
|
+
*
|
|
421
|
+
* Four modes are supported via the `encryptionMode` CacheOption:
|
|
422
|
+
*
|
|
423
|
+
* ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
|
|
424
|
+
* │ Mode │ Key bytes │ Notes │
|
|
425
|
+
* ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
|
|
426
|
+
* │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
|
|
427
|
+
* │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
|
|
428
|
+
* │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
|
|
429
|
+
* │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
|
|
430
|
+
* │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
|
|
431
|
+
* │ │ │ Use only for dev or non-sensitive data. │
|
|
432
|
+
* └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
|
|
433
|
+
*
|
|
434
|
+
* Key generation:
|
|
435
|
+
* AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
436
|
+
* AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
437
|
+
* CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
438
|
+
* XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
439
|
+
*
|
|
440
|
+
* Redis envelope formats:
|
|
441
|
+
* enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
|
|
442
|
+
* a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
|
|
443
|
+
* ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
|
|
444
|
+
* xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
|
|
445
|
+
*
|
|
446
|
+
* Disk envelope formats:
|
|
447
|
+
* TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
|
|
448
|
+
* TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
|
|
449
|
+
* TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
|
|
450
|
+
* TRIC1XOR | key⊕data[N] ← XOR
|
|
451
|
+
*/
|
|
452
|
+
|
|
453
|
+
/** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
|
|
454
|
+
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
455
|
+
declare class CacheEncryption {
|
|
456
|
+
private _key;
|
|
457
|
+
private readonly _mode;
|
|
458
|
+
private readonly _ivPool;
|
|
459
|
+
private _ivOffset;
|
|
460
|
+
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
461
|
+
private _nextIV;
|
|
462
|
+
private readonly _ctrIvPool;
|
|
463
|
+
private _ctrIvOffset;
|
|
464
|
+
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
465
|
+
private _nextCtrIV;
|
|
466
|
+
/**
|
|
467
|
+
* XOR `data` with the key, cycling through key bytes.
|
|
468
|
+
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
469
|
+
*
|
|
470
|
+
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
471
|
+
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
472
|
+
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
473
|
+
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
474
|
+
*
|
|
475
|
+
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
476
|
+
*/
|
|
477
|
+
private _xorBuffer;
|
|
478
|
+
constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode);
|
|
479
|
+
get isEnabled(): boolean;
|
|
480
|
+
/**
|
|
481
|
+
* Encrypt a string for Redis storage.
|
|
482
|
+
* Returns a mode-prefixed base64 string when a key is configured;
|
|
483
|
+
* otherwise returns the original string unchanged (backward-compatible).
|
|
484
|
+
*/
|
|
485
|
+
encrypt(plaintext: string): string;
|
|
486
|
+
/**
|
|
487
|
+
* Decrypt a Redis value.
|
|
488
|
+
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
489
|
+
*/
|
|
490
|
+
decrypt(value: string): string;
|
|
491
|
+
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
492
|
+
encryptBuffer(data: Buffer): Buffer;
|
|
493
|
+
/**
|
|
494
|
+
* Decrypt a raw Buffer from disk/snapshot.
|
|
495
|
+
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
496
|
+
*/
|
|
497
|
+
decryptBuffer(data: Buffer): Buffer;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
|
|
502
|
+
*
|
|
503
|
+
* Features:
|
|
504
|
+
* - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
|
|
505
|
+
* - msgpackr compression for entries ≥ 512 bytes
|
|
506
|
+
* - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
|
|
507
|
+
* - Priority-weighted adaptive eviction (LFU × LRU × priority score)
|
|
508
|
+
* - Stale-While-Revalidate soft-expiry support (isStale flag on get())
|
|
509
|
+
* - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
|
|
510
|
+
* - Periodic cleanup of hard-expired entries + bloom filter rebuild
|
|
511
|
+
* - Process-level singleton via globalThis (survives Next.js hot reloads)
|
|
512
|
+
*/
|
|
513
|
+
|
|
514
|
+
interface SmartMemoryCacheOptions {
|
|
515
|
+
maxBytes: number;
|
|
516
|
+
maxEntries: number;
|
|
517
|
+
categories: Record<string, CategoryLimit>;
|
|
518
|
+
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
519
|
+
logger: ILogger;
|
|
520
|
+
}
|
|
521
|
+
declare class SmartMemoryCache {
|
|
522
|
+
private readonly cache;
|
|
523
|
+
private readonly opts;
|
|
524
|
+
private bloom;
|
|
525
|
+
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
526
|
+
private readonly categoryPrefixes;
|
|
527
|
+
private totalSize;
|
|
528
|
+
private categoryCount;
|
|
529
|
+
private categorySize;
|
|
530
|
+
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
531
|
+
private categoryKeys;
|
|
532
|
+
private bloomChecks;
|
|
533
|
+
private bloomFalsePos;
|
|
534
|
+
private compressions;
|
|
535
|
+
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
536
|
+
private _bloomDirtyCount;
|
|
537
|
+
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
538
|
+
private recalculateStats;
|
|
539
|
+
private getCategory;
|
|
540
|
+
private getCategoryLimit;
|
|
541
|
+
private _delete;
|
|
542
|
+
private ensureCapacity;
|
|
543
|
+
private score;
|
|
544
|
+
/**
|
|
545
|
+
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
546
|
+
* saturated the filter past its ~1 % FP capacity.
|
|
547
|
+
*
|
|
548
|
+
* Trigger: (insertions − live entries) > maxCapacity
|
|
549
|
+
*
|
|
550
|
+
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
551
|
+
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
552
|
+
* cache holds more entries than the filter's rated capacity — which would
|
|
553
|
+
* stall the write path entirely.
|
|
554
|
+
*
|
|
555
|
+
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
556
|
+
*/
|
|
557
|
+
private maybeRebuildBloom;
|
|
558
|
+
private smartEvict;
|
|
559
|
+
get(key: string): CacheHit | null;
|
|
560
|
+
set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
|
|
561
|
+
delete(key: string): boolean;
|
|
562
|
+
private keysMatchingPattern;
|
|
563
|
+
deletePattern(pattern: string): number;
|
|
564
|
+
/**
|
|
565
|
+
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
566
|
+
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
567
|
+
* exceeds the configured threshold.
|
|
568
|
+
*
|
|
569
|
+
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
570
|
+
* @returns Number of entries evicted
|
|
571
|
+
*/
|
|
572
|
+
evictPercentage(pct: number): number;
|
|
573
|
+
cleanup(): number;
|
|
574
|
+
exportEntries(forbiddenPrefixes: readonly string[]): Array<{
|
|
575
|
+
key: string;
|
|
576
|
+
entry: SmartCacheEntry;
|
|
577
|
+
}>;
|
|
578
|
+
importEntries(entries: Array<{
|
|
579
|
+
key: string;
|
|
580
|
+
entry: SmartCacheEntry;
|
|
581
|
+
}>, forbiddenPrefixes: readonly string[]): number;
|
|
582
|
+
get size(): number;
|
|
583
|
+
get memoryUsage(): number;
|
|
584
|
+
getStats(): {
|
|
585
|
+
entries: number;
|
|
586
|
+
sizeKB: number;
|
|
587
|
+
categories: Record<string, number>;
|
|
588
|
+
bloom: {
|
|
589
|
+
checks: number;
|
|
590
|
+
falsePositives: number;
|
|
591
|
+
};
|
|
592
|
+
compression: {
|
|
593
|
+
compressed: number;
|
|
594
|
+
uncompressed: number;
|
|
595
|
+
bytesSaved: number;
|
|
596
|
+
};
|
|
597
|
+
};
|
|
598
|
+
bloomMightContain(key: string): boolean;
|
|
599
|
+
bloomStats(): {
|
|
600
|
+
bitsSet: number;
|
|
601
|
+
fillFactor: number;
|
|
602
|
+
} | {
|
|
603
|
+
bitsSet: number;
|
|
604
|
+
fillFactor: number;
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
610
|
+
*
|
|
611
|
+
* When L1 evicts an entry it is spilled here instead of being discarded.
|
|
612
|
+
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
613
|
+
* vs 10–100 ms DB round-trip).
|
|
614
|
+
*
|
|
615
|
+
* Storage:
|
|
616
|
+
* - Directory: configurable (default os.tmpdir()/tricache-disk)
|
|
617
|
+
* - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
|
|
618
|
+
* - Format: msgpack({ version, key, entry, writtenAt })
|
|
619
|
+
* - Mode: 0o600 — owner read/write only
|
|
620
|
+
*
|
|
621
|
+
* Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
|
|
622
|
+
*/
|
|
623
|
+
|
|
624
|
+
interface DiskTierOptions {
|
|
625
|
+
dir: string;
|
|
626
|
+
maxBytes: number;
|
|
627
|
+
entryMaxBytes: number;
|
|
628
|
+
forbiddenPrefixes: readonly string[];
|
|
629
|
+
encryptionKey?: Buffer | null;
|
|
630
|
+
logger: ILogger;
|
|
631
|
+
}
|
|
632
|
+
declare class DiskTier {
|
|
633
|
+
private readonly opts;
|
|
634
|
+
private dirReady;
|
|
635
|
+
private diskUsageBytes;
|
|
636
|
+
private usageCounted;
|
|
637
|
+
private fileCount;
|
|
638
|
+
constructor(opts: DiskTierOptions);
|
|
639
|
+
private ensureDir;
|
|
640
|
+
private ensureUsageCounted;
|
|
641
|
+
/**
|
|
642
|
+
* Map a cache key to its on-disk path.
|
|
643
|
+
*
|
|
644
|
+
* Files are sharded into two-character hex prefix subdirectories to avoid
|
|
645
|
+
* putting thousands of flat files into a single directory node — which
|
|
646
|
+
* degrades EXT4/NTFS performance at scale.
|
|
647
|
+
*
|
|
648
|
+
* key → SHA-256 hex e3b0c442...
|
|
649
|
+
* path → {dir}/e3/e3b0c442...
|
|
650
|
+
*/
|
|
651
|
+
private keyToPath;
|
|
652
|
+
/**
|
|
653
|
+
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
654
|
+
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
655
|
+
* files written by older versions).
|
|
656
|
+
*/
|
|
657
|
+
private walkCacheFiles;
|
|
658
|
+
private isForbidden;
|
|
659
|
+
private encrypt;
|
|
660
|
+
private decrypt;
|
|
661
|
+
/**
|
|
662
|
+
* Spill an evicted L1 entry to disk.
|
|
663
|
+
*
|
|
664
|
+
* Returns a Promise that resolves when the file is durably written. Callers
|
|
665
|
+
* that treat the spill as fire-and-forget should do:
|
|
666
|
+
* `void disk.save(key, entry)`
|
|
667
|
+
*
|
|
668
|
+
* Implementation notes:
|
|
669
|
+
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
670
|
+
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
671
|
+
* on any external resource.
|
|
672
|
+
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
673
|
+
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
674
|
+
*/
|
|
675
|
+
save(key: string, entry: DiskCacheEntry): Promise<void>;
|
|
676
|
+
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
677
|
+
load(key: string): DiskCacheEntry | null;
|
|
678
|
+
/** Explicitly delete a key from disk (cache invalidation). */
|
|
679
|
+
delete(key: string): void;
|
|
680
|
+
/** Purge all expired entries. Returns number deleted. */
|
|
681
|
+
purgeExpired(): number;
|
|
682
|
+
get stats(): {
|
|
683
|
+
files: number;
|
|
684
|
+
sizeKB: number;
|
|
685
|
+
maxKB: number;
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
declare class WasmBloomFilter {
|
|
690
|
+
private readonly exports;
|
|
691
|
+
private readonly mem;
|
|
692
|
+
private readonly encoder;
|
|
693
|
+
private readonly numBits;
|
|
694
|
+
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
695
|
+
private readonly _maxCapacity;
|
|
696
|
+
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
697
|
+
private _insertionCount;
|
|
698
|
+
constructor();
|
|
699
|
+
private writeKey;
|
|
700
|
+
add(key: string): void;
|
|
701
|
+
mightContain(key: string): boolean;
|
|
702
|
+
reset(): void;
|
|
703
|
+
rebuild(keys: Iterable<string>): void;
|
|
704
|
+
get stats(): {
|
|
705
|
+
bitsSet: number;
|
|
706
|
+
fillFactor: number;
|
|
707
|
+
};
|
|
708
|
+
/** Number of add() calls since last reset/rebuild. */
|
|
709
|
+
get insertions(): number;
|
|
710
|
+
/**
|
|
711
|
+
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
712
|
+
* Exact formula for k=7 hash rounds, m=100 000 bits:
|
|
713
|
+
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
|
|
714
|
+
*/
|
|
715
|
+
get maxCapacity(): number;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
|