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
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CacheService — three-tier cache with stampede prevention and SWR.
|
|
3
|
+
*
|
|
4
|
+
* Architecture:
|
|
5
|
+
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
6
|
+
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
7
|
+
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
8
|
+
* DB → your fetchFunction (cache miss path)
|
|
9
|
+
*
|
|
10
|
+
* Key features:
|
|
11
|
+
* - Thundering-herd / cache-stampede prevention (inflight Promise registry)
|
|
12
|
+
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
13
|
+
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
14
|
+
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
15
|
+
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
16
|
+
* - Periodic cleanup of expired entries every 5 minutes
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { Redis as RedisClient } from 'ioredis';
|
|
20
|
+
import crypto from 'crypto';
|
|
21
|
+
import os from 'os';
|
|
22
|
+
import fs from 'fs';
|
|
23
|
+
import path from 'path';
|
|
24
|
+
import { pack, unpack } from 'msgpackr';
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
CachePriority,
|
|
28
|
+
CategoryLimit,
|
|
29
|
+
SmartCacheEntry,
|
|
30
|
+
DiskCacheEntry,
|
|
31
|
+
CacheOptions,
|
|
32
|
+
CacheMetrics,
|
|
33
|
+
ILogger,
|
|
34
|
+
consoleLogger,
|
|
35
|
+
} from './types';
|
|
36
|
+
import { CacheEncryption } from './encryption';
|
|
37
|
+
import { SmartMemoryCache } from './smart-memory-cache';
|
|
38
|
+
import { DiskTier } from './disk-tier';
|
|
39
|
+
|
|
40
|
+
// ─── Snapshot constants ───────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
const SNAPSHOT_VERSION = 1;
|
|
43
|
+
const DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1000; // 2 hours
|
|
44
|
+
const SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024; // 220 MB guard
|
|
45
|
+
|
|
46
|
+
// ─── Default category limits ──────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
const DEFAULT_CATEGORY_LIMITS: Record<string, CategoryLimit> = {
|
|
49
|
+
'default': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// ─── Default forbidden prefixes ───────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
const DEFAULT_FORBIDDEN_PREFIXES = ['auth:', 'session:', 'mfa:', 'rate_limit:'] as const;
|
|
55
|
+
|
|
56
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
57
|
+
// Priority inference — override by passing priority explicitly to get()
|
|
58
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
function inferPriority(cacheKey: string): CachePriority {
|
|
61
|
+
if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
|
|
62
|
+
if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
|
|
63
|
+
if (cacheKey.includes('analytics:') || cacheKey.includes('report:') || cacheKey.includes('stats:')) return CachePriority.LOW;
|
|
64
|
+
return CachePriority.NORMAL;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
68
|
+
// CacheService
|
|
69
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
// globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
|
|
72
|
+
const GLOBAL_KEY = '__tricache_instance__';
|
|
73
|
+
|
|
74
|
+
export class CacheService {
|
|
75
|
+
private readonly logger: ILogger;
|
|
76
|
+
private readonly enc: CacheEncryption;
|
|
77
|
+
private readonly l1: SmartMemoryCache;
|
|
78
|
+
private readonly disk: DiskTier;
|
|
79
|
+
private readonly opts: {
|
|
80
|
+
namespace: string;
|
|
81
|
+
logger: ILogger; l1MaxBytes: number; l1MaxEntries: number;
|
|
82
|
+
categoryLimits: Record<string, CategoryLimit>;
|
|
83
|
+
forbiddenSnapshotPrefixes: readonly string[];
|
|
84
|
+
diskCacheDir: string; diskMaxBytes: number; diskEntryMaxBytes: number;
|
|
85
|
+
redisHost: string; redisPort: number; redisTls: boolean; disableRedis: boolean;
|
|
86
|
+
encryptionKey: string | undefined; snapshotPath: string; snapshotMaxAgeMs: number;
|
|
87
|
+
invalidationBackplane: boolean;
|
|
88
|
+
oomProtection: boolean; oomHeapThreshold: number;
|
|
89
|
+
oomCheckIntervalMs: number; oomEvictPercent: number;
|
|
90
|
+
onMetrics: ((m: CacheMetrics) => void) | undefined;
|
|
91
|
+
metricsIntervalMs: number;
|
|
92
|
+
};
|
|
93
|
+
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
94
|
+
private readonly _namespace: string;
|
|
95
|
+
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
96
|
+
private readonly _redisDisabled: boolean;
|
|
97
|
+
private readonly inflight = new Map<string, Promise<unknown>>();
|
|
98
|
+
private readonly revalidating = new Set<string>();
|
|
99
|
+
private redis: RedisClient | null = null;
|
|
100
|
+
private redisConnecting: Promise<RedisClient> | null = null;
|
|
101
|
+
private snapshotLoaded = false;
|
|
102
|
+
private cleanupInterval: ReturnType<typeof setInterval> | null = null;
|
|
103
|
+
private oomInterval: ReturnType<typeof setInterval> | null = null;
|
|
104
|
+
private metricsInterval: ReturnType<typeof setInterval> | null = null;
|
|
105
|
+
private _shutdownHandler: (() => void) | null = null;
|
|
106
|
+
private readonly instanceId: string;
|
|
107
|
+
private readonly backplaneChannel: string;
|
|
108
|
+
private subClient: RedisClient | null = null;
|
|
109
|
+
private readonly counters = {
|
|
110
|
+
gets: 0,
|
|
111
|
+
l1Hits: 0,
|
|
112
|
+
diskHits: 0,
|
|
113
|
+
l2Hits: 0,
|
|
114
|
+
fetches: 0,
|
|
115
|
+
stampedes: 0,
|
|
116
|
+
sets: 0,
|
|
117
|
+
deletes: 0,
|
|
118
|
+
swrRevalidations: 0,
|
|
119
|
+
invSent: 0,
|
|
120
|
+
invReceived: 0,
|
|
121
|
+
invSkipped: 0,
|
|
122
|
+
oomEvictions: 0,
|
|
123
|
+
oomLastAt: null as number | null,
|
|
124
|
+
startedAt: Date.now(),
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// ── Constructor (use CacheService.create() for the recommended singleton) ──
|
|
128
|
+
|
|
129
|
+
constructor(options: CacheOptions = {}) {
|
|
130
|
+
const logger = options.logger ?? consoleLogger;
|
|
131
|
+
this.logger = logger;
|
|
132
|
+
|
|
133
|
+
// Resolve namespace: trim whitespace, default to empty string
|
|
134
|
+
const ns = options.namespace?.trim() ?? '';
|
|
135
|
+
|
|
136
|
+
// Resolve encryption key: option > env var
|
|
137
|
+
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
138
|
+
this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode);
|
|
139
|
+
|
|
140
|
+
// When a namespace is active, scope the forbidden prefixes so that
|
|
141
|
+
// auth/session keys like `org_abc:auth:token` are still protected.
|
|
142
|
+
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
143
|
+
const forbiddenPrefixes = ns
|
|
144
|
+
? rawForbidden.map(p => `${ns}:${p}`)
|
|
145
|
+
: rawForbidden;
|
|
146
|
+
|
|
147
|
+
// Normalised options with defaults
|
|
148
|
+
this.opts = {
|
|
149
|
+
namespace: ns,
|
|
150
|
+
logger,
|
|
151
|
+
l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
|
|
152
|
+
l1MaxEntries: options.l1MaxEntries ?? 2_000,
|
|
153
|
+
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...(options.categoryLimits ?? {}) },
|
|
154
|
+
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
155
|
+
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
156
|
+
// two instances with different namespaces never share cache files.
|
|
157
|
+
diskCacheDir: options.diskCacheDir ?? path.join(
|
|
158
|
+
os.tmpdir(), ns ? `tricache-disk-${ns}` : 'tricache-disk'),
|
|
159
|
+
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
160
|
+
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
161
|
+
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? '',
|
|
162
|
+
redisPort: options.redisPort ?? 6379,
|
|
163
|
+
redisTls: options.redisTls ?? (process.env.NODE_ENV === 'production'),
|
|
164
|
+
disableRedis: options.disableRedis ?? (process.env.NODE_ENV !== 'production'),
|
|
165
|
+
encryptionKey: encKeyRaw,
|
|
166
|
+
snapshotPath: options.snapshotPath ?? path.join(
|
|
167
|
+
os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
|
|
168
|
+
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
169
|
+
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
170
|
+
oomProtection: options.oomProtection ?? true,
|
|
171
|
+
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
172
|
+
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 10_000,
|
|
173
|
+
oomEvictPercent: options.oomEvictPercent ?? 0.20,
|
|
174
|
+
onMetrics: options.onMetrics,
|
|
175
|
+
metricsIntervalMs: options.metricsIntervalMs ?? 60_000,
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// L1.5 disk tier
|
|
179
|
+
this.disk = new DiskTier({
|
|
180
|
+
dir: this.opts.diskCacheDir,
|
|
181
|
+
maxBytes: this.opts.diskMaxBytes,
|
|
182
|
+
entryMaxBytes: this.opts.diskEntryMaxBytes,
|
|
183
|
+
forbiddenPrefixes: forbiddenPrefixes,
|
|
184
|
+
encryptionKey: this.enc.isEnabled ? (this.enc as unknown as { _key: Buffer })['_key'] : null,
|
|
185
|
+
logger,
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
this._namespace = ns;
|
|
189
|
+
this._redisDisabled = (this.opts.disableRedis || !this.opts.redisHost);
|
|
190
|
+
|
|
191
|
+
// L1 in-memory cache
|
|
192
|
+
this.l1 = new SmartMemoryCache({
|
|
193
|
+
maxBytes: this.opts.l1MaxBytes,
|
|
194
|
+
maxEntries: this.opts.l1MaxEntries,
|
|
195
|
+
categories: this.opts.categoryLimits,
|
|
196
|
+
diskSpill: (key: string, entry: SmartCacheEntry) => { void this.disk.save(key, entry as unknown as DiskCacheEntry); },
|
|
197
|
+
logger,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// Load snapshot once per process
|
|
201
|
+
if (!this.snapshotLoaded) {
|
|
202
|
+
this.snapshotLoaded = true;
|
|
203
|
+
this.loadSnapshot();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Graceful shutdown: persist L1 to disk
|
|
207
|
+
this._shutdownHandler = () => { this.writeSnapshot(); process.exit(0); };
|
|
208
|
+
process.once('SIGTERM', this._shutdownHandler);
|
|
209
|
+
process.once('SIGINT', this._shutdownHandler);
|
|
210
|
+
|
|
211
|
+
// Periodic cleanup (5 min)
|
|
212
|
+
this.cleanupInterval = setInterval(() => {
|
|
213
|
+
const cleaned = this.l1.cleanup();
|
|
214
|
+
const diskPurged = this.disk.purgeExpired();
|
|
215
|
+
if (cleaned > 0 || diskPurged > 0) {
|
|
216
|
+
this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
|
|
217
|
+
}
|
|
218
|
+
}, 5 * 60 * 1000);
|
|
219
|
+
if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
|
|
220
|
+
|
|
221
|
+
// OOM protection: evict coldest L1 entries when heap pressure rises
|
|
222
|
+
if (this.opts.oomProtection) {
|
|
223
|
+
this.oomInterval = setInterval(() => {
|
|
224
|
+
const mem = process.memoryUsage();
|
|
225
|
+
const used = mem.heapUsed / mem.heapTotal;
|
|
226
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
227
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
228
|
+
this.counters.oomEvictions++;
|
|
229
|
+
this.counters.oomLastAt = Date.now();
|
|
230
|
+
this.logger.warn('tricache OOM guard: emergency L1 eviction', {
|
|
231
|
+
heapUsedPct: Math.round(used * 100),
|
|
232
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
233
|
+
evicted,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}, this.opts.oomCheckIntervalMs);
|
|
237
|
+
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Metrics callback
|
|
241
|
+
if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
|
|
242
|
+
this.metricsInterval = setInterval(() => {
|
|
243
|
+
try { this.opts.onMetrics!(this.metrics()); } catch { /* never crash process */ }
|
|
244
|
+
}, this.opts.metricsIntervalMs);
|
|
245
|
+
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Backplane: assign instance ID + channel, then subscribe
|
|
249
|
+
this.instanceId = crypto.randomBytes(8).toString('hex');
|
|
250
|
+
this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
|
|
251
|
+
this.initBackplane();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Get (or create) the process-level singleton CacheService instance.
|
|
258
|
+
*
|
|
259
|
+
* Options are only applied on first call — subsequent calls return the
|
|
260
|
+
* existing instance regardless of options passed.
|
|
261
|
+
*
|
|
262
|
+
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
263
|
+
* with different namespaces return independent instances.
|
|
264
|
+
*/
|
|
265
|
+
static create(options?: CacheOptions): CacheService {
|
|
266
|
+
const g = globalThis as Record<string, unknown>;
|
|
267
|
+
const key = CacheService.globalKey(options);
|
|
268
|
+
if (!g[key]) g[key] = new CacheService(options);
|
|
269
|
+
return g[key] as CacheService;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Replace the singleton (useful in tests). */
|
|
273
|
+
static reset(options?: CacheOptions): CacheService {
|
|
274
|
+
const g = globalThis as Record<string, unknown>;
|
|
275
|
+
const key = CacheService.globalKey(options);
|
|
276
|
+
const existing = g[key] as CacheService | undefined;
|
|
277
|
+
if (existing) existing.destroy();
|
|
278
|
+
g[key] = new CacheService(options);
|
|
279
|
+
return g[key] as CacheService;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Derive the globalThis key for a given set of options. */
|
|
283
|
+
private static globalKey(options?: CacheOptions): string {
|
|
284
|
+
const ns = options?.namespace?.trim() ?? '';
|
|
285
|
+
return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── Redis connection ──────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Prepend the configured namespace to a raw cache key.
|
|
292
|
+
* Returns the key unchanged when namespace is empty.
|
|
293
|
+
*
|
|
294
|
+
* This is the only place the namespace prefix is applied — callers always
|
|
295
|
+
* receive and provide un-prefixed keys in the public API.
|
|
296
|
+
*/
|
|
297
|
+
private nk(key: string): string {
|
|
298
|
+
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private initBackplane(): void {
|
|
302
|
+
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
303
|
+
if (this.subClient) return;
|
|
304
|
+
|
|
305
|
+
const sub = new RedisClient({
|
|
306
|
+
host: this.opts.redisHost,
|
|
307
|
+
port: this.opts.redisPort,
|
|
308
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
309
|
+
connectTimeout: 10_000,
|
|
310
|
+
lazyConnect: true,
|
|
311
|
+
maxRetriesPerRequest: null as unknown as number,
|
|
312
|
+
enableAutoPipelining: false,
|
|
313
|
+
family: 4,
|
|
314
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
sub.on('error', (e: Error) =>
|
|
318
|
+
this.logger.debug('Backplane subscriber error', { error: e.message }));
|
|
319
|
+
|
|
320
|
+
sub.on('message', (_channel: string, message: string) => {
|
|
321
|
+
try {
|
|
322
|
+
const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
|
|
323
|
+
if (msg.src === this.instanceId) {
|
|
324
|
+
this.counters.invSkipped++;
|
|
325
|
+
return; // own message — our L1 is already current
|
|
326
|
+
}
|
|
327
|
+
this.counters.invReceived++;
|
|
328
|
+
if (msg.op === 'del') {
|
|
329
|
+
this.l1.delete(msg.key);
|
|
330
|
+
this.disk.delete(msg.key);
|
|
331
|
+
} else if (msg.op === 'del-glob') {
|
|
332
|
+
this.l1.deletePattern(msg.key);
|
|
333
|
+
}
|
|
334
|
+
this.logger.debug('Backplane: peer invalidation applied', {
|
|
335
|
+
op: msg.op, key: msg.key.slice(0, 60),
|
|
336
|
+
});
|
|
337
|
+
} catch { /* malformed message — ignore */ }
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
sub.subscribe(this.backplaneChannel)
|
|
341
|
+
.then(() => this.logger.info('Backplane: subscribed', {
|
|
342
|
+
channel: this.backplaneChannel, instanceId: this.instanceId,
|
|
343
|
+
}))
|
|
344
|
+
.catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
|
|
345
|
+
error: err.message,
|
|
346
|
+
}));
|
|
347
|
+
|
|
348
|
+
this.subClient = sub;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
|
|
352
|
+
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
353
|
+
try {
|
|
354
|
+
const client = await this.getRedis();
|
|
355
|
+
await client.publish(
|
|
356
|
+
this.backplaneChannel,
|
|
357
|
+
JSON.stringify({ op, key, src: this.instanceId }),
|
|
358
|
+
);
|
|
359
|
+
this.counters.invSent++;
|
|
360
|
+
} catch { /* non-critical — never block the caller */ }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private async getRedis(): Promise<RedisClient> {
|
|
364
|
+
if (this.redis?.status === 'ready') return this.redis as RedisClient;
|
|
365
|
+
if (this.redisConnecting) return this.redisConnecting;
|
|
366
|
+
|
|
367
|
+
this.redisConnecting = (async () => {
|
|
368
|
+
const client = new RedisClient({
|
|
369
|
+
host: this.opts.redisHost,
|
|
370
|
+
port: this.opts.redisPort,
|
|
371
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
372
|
+
connectTimeout: 10_000,
|
|
373
|
+
lazyConnect: false,
|
|
374
|
+
maxRetriesPerRequest: 3,
|
|
375
|
+
enableAutoPipelining: true,
|
|
376
|
+
keepAlive: 30_000,
|
|
377
|
+
family: 4,
|
|
378
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
|
|
382
|
+
client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
|
|
383
|
+
client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
|
|
384
|
+
|
|
385
|
+
await new Promise<void>((resolve, reject) => {
|
|
386
|
+
client.once('ready', resolve);
|
|
387
|
+
client.once('error', reject);
|
|
388
|
+
setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
this.redis = client;
|
|
392
|
+
this.redisConnecting = null;
|
|
393
|
+
return client;
|
|
394
|
+
})();
|
|
395
|
+
|
|
396
|
+
return this.redisConnecting;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
400
|
+
|
|
401
|
+
writeSnapshot(): void {
|
|
402
|
+
try {
|
|
403
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
404
|
+
if (entries.length === 0) return;
|
|
405
|
+
|
|
406
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
407
|
+
const packed = pack(payload);
|
|
408
|
+
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
409
|
+
|
|
410
|
+
fs.writeFileSync(this.opts.snapshotPath, final, { mode: 0o600 });
|
|
411
|
+
this.logger.info('Cache snapshot written', {
|
|
412
|
+
path: this.opts.snapshotPath, entries: entries.length,
|
|
413
|
+
sizeKB: Math.round(final.length / 1024), encrypted: this.enc.isEnabled,
|
|
414
|
+
});
|
|
415
|
+
} catch (err) {
|
|
416
|
+
this.logger.warn('Cache snapshot write failed', { error: (err as Error).message });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
loadSnapshot(): void {
|
|
421
|
+
const snapshotPath = this.opts.snapshotPath;
|
|
422
|
+
try {
|
|
423
|
+
if (!fs.existsSync(snapshotPath)) return;
|
|
424
|
+
|
|
425
|
+
const stat = fs.statSync(snapshotPath);
|
|
426
|
+
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
427
|
+
this.logger.warn('Snapshot rejected: exceeds size limit', { sizeBytes: stat.size });
|
|
428
|
+
fs.unlinkSync(snapshotPath);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const raw = fs.readFileSync(snapshotPath);
|
|
433
|
+
fs.unlinkSync(snapshotPath); // delete immediately — don't leave cache data on disk
|
|
434
|
+
|
|
435
|
+
let buf: Buffer;
|
|
436
|
+
try { buf = this.enc.decryptBuffer(raw); } catch (e) {
|
|
437
|
+
this.logger.warn('Snapshot rejected: decryption failed', { error: (e as Error).message });
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const snapshot = unpack(buf) as {
|
|
442
|
+
version?: number; writtenAt?: number;
|
|
443
|
+
entries?: Array<{ key: string; entry: SmartCacheEntry }>;
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
447
|
+
this.logger.warn('Snapshot rejected: version mismatch', { got: snapshot?.version });
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
|
|
452
|
+
if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
|
|
453
|
+
this.logger.warn('Snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
458
|
+
this.logger.warn('Snapshot rejected: entries is not an array');
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
463
|
+
this.logger.info('Cache snapshot loaded (L1 is warm)', {
|
|
464
|
+
loaded, total: snapshot.entries.length,
|
|
465
|
+
sizeKB: this.l1.getStats().sizeKB,
|
|
466
|
+
});
|
|
467
|
+
} catch (err) {
|
|
468
|
+
this.logger.warn('Snapshot load failed — starting cold', { error: (err as Error).message });
|
|
469
|
+
try { fs.unlinkSync(snapshotPath); } catch { /* ok */ }
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Get a value from cache, or fetch and cache it.
|
|
477
|
+
*
|
|
478
|
+
* @param cacheKey - Unique key identifying this value
|
|
479
|
+
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
480
|
+
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
481
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
482
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
|
|
483
|
+
* alive for this many extra seconds after TTL; callers get stale data
|
|
484
|
+
* instantly while a background refresh runs. Default: 0 (disabled).
|
|
485
|
+
*/
|
|
486
|
+
async get<T>(
|
|
487
|
+
cacheKey: string,
|
|
488
|
+
fetchFn: () => Promise<T>,
|
|
489
|
+
ttlSeconds: number = 300,
|
|
490
|
+
opts: {
|
|
491
|
+
priority?: CachePriority;
|
|
492
|
+
swr?: number; // Stale-While-Revalidate grace period in seconds
|
|
493
|
+
} = {},
|
|
494
|
+
): Promise<T> {
|
|
495
|
+
const k = this.nk(cacheKey); // namespaced key used for all storage
|
|
496
|
+
this.counters.gets++;
|
|
497
|
+
|
|
498
|
+
// L1: in-memory (fastest path — defer inferPriority / ttlMs until we confirm a miss;
|
|
499
|
+
// inferPriority runs 3 regex tests that are wasted work on every warm hit)
|
|
500
|
+
const l1Hit = this.l1.get(k);
|
|
501
|
+
if (l1Hit !== null) {
|
|
502
|
+
if (l1Hit.isStale) {
|
|
503
|
+
const swrGraceMs = (opts.swr ?? 0) * 1_000;
|
|
504
|
+
if (swrGraceMs > 0 && !this.revalidating.has(k)) {
|
|
505
|
+
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
506
|
+
this.revalidating.add(k);
|
|
507
|
+
void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
|
|
508
|
+
this.counters.swrRevalidations++;
|
|
509
|
+
this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
|
|
510
|
+
} else {
|
|
511
|
+
this.logger.debug('L1 hit');
|
|
512
|
+
}
|
|
513
|
+
} else {
|
|
514
|
+
this.logger.debug('L1 hit');
|
|
515
|
+
}
|
|
516
|
+
this.counters.l1Hits++;
|
|
517
|
+
return l1Hit.value as T;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const ttlMs = ttlSeconds * 1_000;
|
|
521
|
+
const swrGraceMs = (opts.swr ?? 0) * 1_000;
|
|
522
|
+
const priority = opts.priority ?? inferPriority(cacheKey); // original key for correct prefix inference
|
|
523
|
+
|
|
524
|
+
// L2: Redis (distributed, production-only by default)
|
|
525
|
+
if (!this._redisDisabled) {
|
|
526
|
+
try {
|
|
527
|
+
const client = await this.getRedis();
|
|
528
|
+
const raw = await client.get(k);
|
|
529
|
+
if (raw) {
|
|
530
|
+
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
531
|
+
const parsed = JSON.parse(decrypted) as T;
|
|
532
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
533
|
+
this.counters.l2Hits++;
|
|
534
|
+
this.logger.debug('L2 hit (Redis)', { cacheKey });
|
|
535
|
+
return parsed;
|
|
536
|
+
}
|
|
537
|
+
} catch (err) {
|
|
538
|
+
this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// L1.5: disk tier (evicted L1 entries)
|
|
543
|
+
const diskHit = this.disk.load(k);
|
|
544
|
+
if (diskHit !== null) {
|
|
545
|
+
const promoted = this.l1.importEntries(
|
|
546
|
+
[{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
|
|
547
|
+
this.opts.forbiddenSnapshotPrefixes,
|
|
548
|
+
);
|
|
549
|
+
if (promoted > 0) {
|
|
550
|
+
const l1Check = this.l1.get(k);
|
|
551
|
+
if (l1Check !== null) {
|
|
552
|
+
this.counters.diskHits++;
|
|
553
|
+
this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
|
|
554
|
+
return l1Check.value as T;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Cache MISS: thundering-herd prevention
|
|
560
|
+
const existing = this.inflight.get(k);
|
|
561
|
+
if (existing) {
|
|
562
|
+
this.counters.stampedes++;
|
|
563
|
+
this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
|
|
564
|
+
return existing as Promise<T>;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const fetchPromise: Promise<T> = (async () => {
|
|
568
|
+
try {
|
|
569
|
+
this.counters.fetches++;
|
|
570
|
+
const data = await fetchFn();
|
|
571
|
+
const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : undefined;
|
|
572
|
+
const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
|
|
573
|
+
|
|
574
|
+
this.l1.set(k, data, storeTtl, priority, staleAt);
|
|
575
|
+
|
|
576
|
+
if (!this._redisDisabled) {
|
|
577
|
+
try {
|
|
578
|
+
const client = await this.getRedis();
|
|
579
|
+
const serialized = JSON.stringify(data);
|
|
580
|
+
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
581
|
+
await client.setex(k, ttlSeconds, toStore);
|
|
582
|
+
this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
583
|
+
} catch {
|
|
584
|
+
this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
|
|
585
|
+
}
|
|
586
|
+
} else {
|
|
587
|
+
this.logger.debug('Cached L1', { cacheKey });
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
return data;
|
|
591
|
+
} finally {
|
|
592
|
+
this.inflight.delete(k);
|
|
593
|
+
}
|
|
594
|
+
})();
|
|
595
|
+
|
|
596
|
+
this.inflight.set(k, fetchPromise);
|
|
597
|
+
return fetchPromise;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
private async _revalidate<T>(
|
|
601
|
+
cacheKey: string,
|
|
602
|
+
fetchFn: () => Promise<T>,
|
|
603
|
+
ttlMs: number,
|
|
604
|
+
swrGraceMs: number,
|
|
605
|
+
priority: CachePriority,
|
|
606
|
+
): Promise<void> {
|
|
607
|
+
try {
|
|
608
|
+
const data = await fetchFn();
|
|
609
|
+
const staleAt = Date.now() + ttlMs;
|
|
610
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
|
|
611
|
+
|
|
612
|
+
if (!this._redisDisabled) {
|
|
613
|
+
try {
|
|
614
|
+
const client = await this.getRedis();
|
|
615
|
+
const s = JSON.stringify(data);
|
|
616
|
+
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
617
|
+
await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
|
|
618
|
+
} catch { /* ok */ }
|
|
619
|
+
}
|
|
620
|
+
this.logger.debug('SWR: revalidation complete', { cacheKey });
|
|
621
|
+
} catch (err) {
|
|
622
|
+
this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
|
|
623
|
+
} finally {
|
|
624
|
+
this.revalidating.delete(cacheKey);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
629
|
+
|
|
630
|
+
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
631
|
+
async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority): Promise<void> {
|
|
632
|
+
const ttlMs = ttlSeconds * 1_000;
|
|
633
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
634
|
+
const k = this.nk(cacheKey);
|
|
635
|
+
this.counters.sets++;
|
|
636
|
+
this.l1.set(k, data, ttlMs, p);
|
|
637
|
+
|
|
638
|
+
if (!this._redisDisabled) {
|
|
639
|
+
try {
|
|
640
|
+
const client = await this.getRedis();
|
|
641
|
+
const s = JSON.stringify(data);
|
|
642
|
+
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
643
|
+
await client.setex(k, ttlSeconds, stored);
|
|
644
|
+
} catch (err) {
|
|
645
|
+
this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
void this.publishInvalidation('del', k);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
654
|
+
*
|
|
655
|
+
* @example
|
|
656
|
+
* await cache.delete('user:abc:profile'); // exact key
|
|
657
|
+
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
658
|
+
*/
|
|
659
|
+
async delete(cacheKey: string): Promise<void> {
|
|
660
|
+
const isPattern = cacheKey.includes('*');
|
|
661
|
+
const k = this.nk(cacheKey); // namespace-scoped key / pattern
|
|
662
|
+
this.counters.deletes++;
|
|
663
|
+
|
|
664
|
+
if (isPattern) {
|
|
665
|
+
this.l1.deletePattern(k);
|
|
666
|
+
} else {
|
|
667
|
+
this.l1.delete(k);
|
|
668
|
+
this.disk.delete(k);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (!this._redisDisabled) {
|
|
672
|
+
try {
|
|
673
|
+
const client = await this.getRedis();
|
|
674
|
+
if (isPattern) {
|
|
675
|
+
const stream = client.scanStream({ match: k, count: 100 });
|
|
676
|
+
const keys: string[] = [];
|
|
677
|
+
await new Promise<void>((resolve, reject) => {
|
|
678
|
+
stream.on('data', (chunk: string[]) => keys.push(...chunk));
|
|
679
|
+
stream.on('end', resolve);
|
|
680
|
+
stream.on('error', reject);
|
|
681
|
+
});
|
|
682
|
+
if (keys.length > 0) await client.del(...keys);
|
|
683
|
+
} else {
|
|
684
|
+
await client.del(k);
|
|
685
|
+
}
|
|
686
|
+
} catch (err) {
|
|
687
|
+
this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Atomically increment a counter in Redis. Returns the new value.
|
|
698
|
+
* Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
|
|
699
|
+
*/
|
|
700
|
+
async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
|
|
701
|
+
if (this._redisDisabled) return 0;
|
|
702
|
+
const k = this.nk(cacheKey);
|
|
703
|
+
try {
|
|
704
|
+
const client = await this.getRedis();
|
|
705
|
+
const count = await client.incr(k);
|
|
706
|
+
if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
|
|
707
|
+
return count;
|
|
708
|
+
} catch (err) {
|
|
709
|
+
this.logger.error('increment: Redis error', { cacheKey }, err as Error);
|
|
710
|
+
return 0;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
715
|
+
|
|
716
|
+
stats() {
|
|
717
|
+
return {
|
|
718
|
+
l1: this.l1.getStats(),
|
|
719
|
+
disk: this.disk.stats,
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// ── Observability ──────────────────────────────────────────────────────────────────
|
|
724
|
+
|
|
725
|
+
/** Return a full metrics snapshot. */
|
|
726
|
+
metrics(): CacheMetrics {
|
|
727
|
+
const c = this.counters;
|
|
728
|
+
const l1s = this.l1.getStats();
|
|
729
|
+
const div = (n: number, d: number) => (d > 0 ? n / d : 0);
|
|
730
|
+
|
|
731
|
+
return {
|
|
732
|
+
namespace: this.opts.namespace,
|
|
733
|
+
uptimeMs: Date.now() - c.startedAt,
|
|
734
|
+
|
|
735
|
+
gets: {
|
|
736
|
+
total: c.gets,
|
|
737
|
+
l1Hits: c.l1Hits,
|
|
738
|
+
l1HitRate: div(c.l1Hits, c.gets),
|
|
739
|
+
diskHits: c.diskHits,
|
|
740
|
+
diskHitRate: div(c.diskHits, c.gets),
|
|
741
|
+
l2Hits: c.l2Hits,
|
|
742
|
+
l2HitRate: div(c.l2Hits, c.gets),
|
|
743
|
+
fetches: c.fetches,
|
|
744
|
+
fetchRate: div(c.fetches, c.gets),
|
|
745
|
+
stampedePrevented: c.stampedes,
|
|
746
|
+
},
|
|
747
|
+
|
|
748
|
+
sets: { total: c.sets },
|
|
749
|
+
deletes: { total: c.deletes },
|
|
750
|
+
revalidations: { total: c.swrRevalidations },
|
|
751
|
+
|
|
752
|
+
bloom: {
|
|
753
|
+
checksTotal: l1s.bloom.checks,
|
|
754
|
+
falsePositives: l1s.bloom.falsePositives,
|
|
755
|
+
falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks),
|
|
756
|
+
},
|
|
757
|
+
|
|
758
|
+
compression: {
|
|
759
|
+
entriesCompressed: l1s.compression.compressed,
|
|
760
|
+
entriesUncompressed: l1s.compression.uncompressed,
|
|
761
|
+
bytesSaved: l1s.compression.bytesSaved,
|
|
762
|
+
},
|
|
763
|
+
|
|
764
|
+
backplane: {
|
|
765
|
+
enabled: this.opts.invalidationBackplane && !this._redisDisabled,
|
|
766
|
+
sent: c.invSent,
|
|
767
|
+
received: c.invReceived,
|
|
768
|
+
skipped: c.invSkipped,
|
|
769
|
+
},
|
|
770
|
+
|
|
771
|
+
oom: {
|
|
772
|
+
enabled: this.opts.oomProtection,
|
|
773
|
+
evictions: c.oomEvictions,
|
|
774
|
+
lastTriggeredAt: c.oomLastAt,
|
|
775
|
+
},
|
|
776
|
+
|
|
777
|
+
l1: {
|
|
778
|
+
entries: l1s.entries,
|
|
779
|
+
sizeBytes: this.l1.memoryUsage,
|
|
780
|
+
maxBytes: this.opts.l1MaxBytes,
|
|
781
|
+
},
|
|
782
|
+
disk: this.disk.stats,
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
788
|
+
* Paste the result into your `/metrics` endpoint.
|
|
789
|
+
*
|
|
790
|
+
* @param m - Snapshot returned by `cache.metrics()`
|
|
791
|
+
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
792
|
+
*/
|
|
793
|
+
static toPrometheusText(m: CacheMetrics, prefix = 'tricache'): string {
|
|
794
|
+
const lbl = m.namespace ? `{namespace="${m.namespace}"}` : '';
|
|
795
|
+
const lines: string[] = [];
|
|
796
|
+
|
|
797
|
+
const counter = (name: string, val: number, help: string) => {
|
|
798
|
+
lines.push(`# HELP ${prefix}_${name}_total ${help}`);
|
|
799
|
+
lines.push(`# TYPE ${prefix}_${name}_total counter`);
|
|
800
|
+
lines.push(`${prefix}_${name}_total${lbl} ${val}`);
|
|
801
|
+
};
|
|
802
|
+
const gauge = (name: string, val: number, help: string) => {
|
|
803
|
+
lines.push(`# HELP ${prefix}_${name} ${help}`);
|
|
804
|
+
lines.push(`# TYPE ${prefix}_${name} gauge`);
|
|
805
|
+
lines.push(`${prefix}_${name}${lbl} ${val}`);
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
counter('gets', m.gets.total, 'Total get() calls');
|
|
809
|
+
counter('l1_hits', m.gets.l1Hits, 'L1 RAM cache hits');
|
|
810
|
+
counter('disk_hits', m.gets.diskHits, 'L1.5 disk tier hits');
|
|
811
|
+
counter('l2_hits', m.gets.l2Hits, 'L2 Redis hits');
|
|
812
|
+
counter('fetches', m.gets.fetches, 'fetchFn calls (cache misses)');
|
|
813
|
+
counter('stampedes_prevented', m.gets.stampedePrevented, 'Coalesced duplicate inflight requests');
|
|
814
|
+
counter('sets', m.sets.total, 'Total set() calls');
|
|
815
|
+
counter('deletes', m.deletes.total, 'Total delete() calls');
|
|
816
|
+
counter('swr_revalidations', m.revalidations.total, 'Stale-While-Revalidate background refreshes');
|
|
817
|
+
|
|
818
|
+
gauge('l1_hit_rate', m.gets.l1HitRate, 'Fraction of gets served from L1 RAM (0-1)');
|
|
819
|
+
gauge('disk_hit_rate', m.gets.diskHitRate, 'Fraction of gets served from disk (0-1)');
|
|
820
|
+
gauge('l2_hit_rate', m.gets.l2HitRate, 'Fraction of gets served from Redis (0-1)');
|
|
821
|
+
gauge('fetch_rate', m.gets.fetchRate, 'Fraction of gets calling fetchFn (0-1)');
|
|
822
|
+
|
|
823
|
+
gauge('l1_entries', m.l1.entries, 'Current L1 entry count');
|
|
824
|
+
gauge('l1_size_bytes', m.l1.sizeBytes, 'Current L1 used bytes');
|
|
825
|
+
gauge('disk_files', m.disk.files, 'Current L1.5 disk file count');
|
|
826
|
+
|
|
827
|
+
gauge('bloom_false_positive_rate', m.bloom.falsePositiveRate,
|
|
828
|
+
'Bloom filter false-positive rate; increase capacity if > 0.01');
|
|
829
|
+
gauge('compression_bytes_saved', m.compression.bytesSaved,
|
|
830
|
+
'Approximate bytes saved by msgpackr compression');
|
|
831
|
+
|
|
832
|
+
if (m.backplane.enabled) {
|
|
833
|
+
counter('backplane_sent', m.backplane.sent, 'Invalidation messages sent via Pub/Sub');
|
|
834
|
+
counter('backplane_received', m.backplane.received, 'Invalidation messages received from peers');
|
|
835
|
+
}
|
|
836
|
+
if (m.oom.enabled) {
|
|
837
|
+
counter('oom_evictions', m.oom.evictions,
|
|
838
|
+
'Emergency L1 eviction rounds triggered by heap pressure');
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
return lines.join('\n');
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
845
|
+
|
|
846
|
+
/** Close Redis connections and stop all background timers. */
|
|
847
|
+
async destroy(): Promise<void> {
|
|
848
|
+
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
849
|
+
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
850
|
+
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
851
|
+
if (this._shutdownHandler) {
|
|
852
|
+
process.off('SIGTERM', this._shutdownHandler);
|
|
853
|
+
process.off('SIGINT', this._shutdownHandler);
|
|
854
|
+
this._shutdownHandler = null;
|
|
855
|
+
}
|
|
856
|
+
if (this.subClient) {
|
|
857
|
+
try { await this.subClient.quit(); } catch { /* ok */ }
|
|
858
|
+
this.subClient = null;
|
|
859
|
+
}
|
|
860
|
+
if (this.redis) {
|
|
861
|
+
try { await this.redis.disconnect(); } catch { /* ok */ }
|
|
862
|
+
this.redis = null;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
}
|