tricache 0.5.1 → 0.6.1
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 +133 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +938 -217
- package/dist/index.d.cts +248 -6
- package/dist/index.d.ts +248 -6
- package/dist/index.js +845 -452
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +6 -6
- package/src/cache-service.ts +510 -109
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +105 -31
- package/src/types.ts +179 -1
- package/src/worker-pool.ts +190 -0
package/src/cache-service.ts
CHANGED
|
@@ -16,10 +16,12 @@
|
|
|
16
16
|
* - Periodic cleanup of expired entries every 5 minutes
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
import { Redis as RedisClient } from 'ioredis';
|
|
19
|
+
import { Redis as RedisClient, Cluster as RedisCluster } from 'ioredis';
|
|
20
20
|
import { pack, unpack } from 'msgpackr';
|
|
21
21
|
import crypto from 'crypto';
|
|
22
22
|
import os from 'os';
|
|
23
|
+
import { WorkerPool } from './worker-pool.js';
|
|
24
|
+
import v8 from 'node:v8';
|
|
23
25
|
import fs from 'fs';
|
|
24
26
|
import path from 'path';
|
|
25
27
|
|
|
@@ -124,6 +126,125 @@ function deepFreeze<T>(obj: T): T {
|
|
|
124
126
|
return obj;
|
|
125
127
|
}
|
|
126
128
|
|
|
129
|
+
// ─── Adaptive TTL latency tracker ────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Lightweight per-key fetch-latency ring buffer.
|
|
133
|
+
*
|
|
134
|
+
* Each key gets a `Float64Array` of `samples` slots written in round-robin
|
|
135
|
+
* order. A separate `{ head, count }` object tracks the write pointer and
|
|
136
|
+
* how many slots have been filled so far. Once a key has ≥ 5 samples the
|
|
137
|
+
* p95 percentile can be read back with `.p95(key)`.
|
|
138
|
+
*
|
|
139
|
+
* Total memory per key: 8 × samples bytes (Float64Array) + one small object.
|
|
140
|
+
* With defaults (32 samples, 5 000 keys): ~1.3 MB worst-case.
|
|
141
|
+
*
|
|
142
|
+
* Key eviction: the internal Map preserves insertion order. When `maxKeys`
|
|
143
|
+
* is reached the oldest-inserted key is removed before the new one is added —
|
|
144
|
+
* no extra LRU bookkeeping required.
|
|
145
|
+
*/
|
|
146
|
+
/** Per-key metadata stored alongside each ring buffer. */
|
|
147
|
+
interface LatencyMeta {
|
|
148
|
+
head: number; // ring-buffer write pointer
|
|
149
|
+
count: number; // filled slots (≤ samples)
|
|
150
|
+
p95: number; // cached p95 value (valid when !dirty && count ≥ 5)
|
|
151
|
+
dirty: boolean; // true when a new sample was written since last p95 computation
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
class LatencyTracker {
|
|
155
|
+
private readonly samples: number;
|
|
156
|
+
private readonly maxKeys: number;
|
|
157
|
+
private readonly bufs = new Map<string, Float64Array>();
|
|
158
|
+
private readonly meta = new Map<string, LatencyMeta>();
|
|
159
|
+
/** Shared sort buffer — safe to reuse because JS is single-threaded. */
|
|
160
|
+
private readonly scratch: Float64Array;
|
|
161
|
+
|
|
162
|
+
constructor(samples: number, maxKeys: number) {
|
|
163
|
+
this.samples = samples;
|
|
164
|
+
this.maxKeys = maxKeys;
|
|
165
|
+
this.scratch = new Float64Array(samples);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
record(key: string, deltaMs: number): void {
|
|
169
|
+
let buf = this.bufs.get(key);
|
|
170
|
+
let m = this.meta.get(key);
|
|
171
|
+
if (buf === undefined) {
|
|
172
|
+
if (this.bufs.size >= this.maxKeys) {
|
|
173
|
+
// Evict oldest key (Map insertion order)
|
|
174
|
+
const oldest = this.bufs.keys().next().value as string;
|
|
175
|
+
this.bufs.delete(oldest);
|
|
176
|
+
this.meta.delete(oldest);
|
|
177
|
+
}
|
|
178
|
+
buf = new Float64Array(this.samples);
|
|
179
|
+
m = { head: 0, count: 0, p95: 0, dirty: false };
|
|
180
|
+
this.bufs.set(key, buf);
|
|
181
|
+
this.meta.set(key, m);
|
|
182
|
+
}
|
|
183
|
+
buf[m!.head] = deltaMs;
|
|
184
|
+
m!.head = (m!.head + 1) % this.samples;
|
|
185
|
+
if (m!.count < this.samples) m!.count++;
|
|
186
|
+
m!.dirty = true; // new sample → cached p95 is stale
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
|
|
191
|
+
* Uses the shared scratch buffer — no heap allocation.
|
|
192
|
+
*/
|
|
193
|
+
private _computeP95(buf: Float64Array, m: LatencyMeta): void {
|
|
194
|
+
const n = m.count;
|
|
195
|
+
this.scratch.set(buf.subarray(0, n));
|
|
196
|
+
const view = this.scratch.subarray(0, n);
|
|
197
|
+
view.sort(); // TypedArray numeric sort — no comparator needed
|
|
198
|
+
m.p95 = view[Math.ceil(n * 0.95) - 1];
|
|
199
|
+
m.dirty = false;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Returns the p95 fetch latency for `key` in milliseconds, or `null` when
|
|
204
|
+
* fewer than 5 samples have been collected (not enough data yet).
|
|
205
|
+
* Uses a dirty-flag cache — sort only runs when a new sample was recorded.
|
|
206
|
+
*/
|
|
207
|
+
p95(key: string): number | null {
|
|
208
|
+
const buf = this.bufs.get(key);
|
|
209
|
+
const m = this.meta.get(key);
|
|
210
|
+
if (!buf || !m || m.count < 5) return null;
|
|
211
|
+
if (m.dirty) this._computeP95(buf, m);
|
|
212
|
+
return m.p95;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
get trackedKeys(): number { return this.bufs.size; }
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Top-20 slowest keys by p95, sorted descending.
|
|
219
|
+
* Keys with < 5 samples are excluded (not enough data for a reliable p95).
|
|
220
|
+
*
|
|
221
|
+
* Only dirty keys (those with new samples since the last call) pay the sort
|
|
222
|
+
* cost. Keys whose p95 is already cached are O(1) reads — so repeated
|
|
223
|
+
* metrics() calls with no intervening fetches are essentially free.
|
|
224
|
+
*/
|
|
225
|
+
snapshot(
|
|
226
|
+
prefixLen: number,
|
|
227
|
+
multiplierSec: number,
|
|
228
|
+
minMs: number,
|
|
229
|
+
maxMs: number,
|
|
230
|
+
): Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> {
|
|
231
|
+
const out: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> = [];
|
|
232
|
+
for (const [key, buf] of this.bufs) {
|
|
233
|
+
const m = this.meta.get(key)!;
|
|
234
|
+
if (m.count < 5) continue;
|
|
235
|
+
if (m.dirty) this._computeP95(buf, m); // sort only when new sample arrived
|
|
236
|
+
const p95 = m.p95;
|
|
237
|
+
const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1_000)));
|
|
238
|
+
out.push({
|
|
239
|
+
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
240
|
+
p95Ms: Math.round(p95),
|
|
241
|
+
adaptedTtlSec: Math.round(adaptedMs / 1_000),
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
127
248
|
function inferPriority(cacheKey: string): CachePriority {
|
|
128
249
|
if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
|
|
129
250
|
if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
|
|
@@ -138,11 +259,36 @@ function inferPriority(cacheKey: string): CachePriority {
|
|
|
138
259
|
// globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
|
|
139
260
|
const GLOBAL_KEY = '__tricache_instance__';
|
|
140
261
|
|
|
262
|
+
// ── Union type for single-node, Cluster, and Sentinel Redis clients ───────────
|
|
263
|
+
type AnyRedisClient = RedisClient | RedisCluster;
|
|
264
|
+
|
|
265
|
+
// ── Serverless environment detection ─────────────────────────────────────────
|
|
266
|
+
/**
|
|
267
|
+
* Returns the name of the detected serverless/ephemeral-filesystem runtime,
|
|
268
|
+
* or `null` when running in a regular persistent-disk environment.
|
|
269
|
+
*
|
|
270
|
+
* Detection is entirely env-var based — zero I/O, zero network, sub-microsecond.
|
|
271
|
+
*/
|
|
272
|
+
function detectServerlessRuntime(): string | null {
|
|
273
|
+
if (process.env['AWS_LAMBDA_FUNCTION_NAME']) return 'AWS Lambda';
|
|
274
|
+
if (process.env['K_SERVICE']) return 'Google Cloud Run';
|
|
275
|
+
if (process.env['FUNCTION_TARGET']) return 'Google Cloud Functions';
|
|
276
|
+
if (process.env['WEBSITE_INSTANCE_ID']) return 'Azure Functions';
|
|
277
|
+
if (process.env['FLY_APP_NAME']) return 'Fly.io';
|
|
278
|
+
if (process.env['RAILWAY_ENVIRONMENT']) return 'Railway';
|
|
279
|
+
if (process.env['VERCEL']) return 'Vercel';
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
141
283
|
export class CacheService {
|
|
142
284
|
private readonly logger: ILogger;
|
|
143
285
|
private readonly enc: CacheEncryption;
|
|
144
286
|
private readonly l1: SmartMemoryCache;
|
|
145
287
|
private readonly disk: DiskTier;
|
|
288
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
289
|
+
private _diskDisabled = false;
|
|
290
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
291
|
+
private _workerPool: WorkerPool | null = null;
|
|
146
292
|
private readonly opts: {
|
|
147
293
|
namespace: string;
|
|
148
294
|
logger: ILogger; l1MaxBytes: number; l1MaxEntries: number;
|
|
@@ -159,6 +305,7 @@ export class CacheService {
|
|
|
159
305
|
staleIfError: number;
|
|
160
306
|
l2WriteMode: 'read-write' | 'read-only';
|
|
161
307
|
instanceName: string;
|
|
308
|
+
l1EvictionWatermark: number;
|
|
162
309
|
ttlJitterFactor: number;
|
|
163
310
|
tracer: ICacheTracer | undefined;
|
|
164
311
|
notFoundTtl: number;
|
|
@@ -166,6 +313,17 @@ export class CacheService {
|
|
|
166
313
|
onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
|
|
167
314
|
onMiss: ((key: string) => void) | undefined;
|
|
168
315
|
frozen: boolean;
|
|
316
|
+
adaptiveTtl: boolean;
|
|
317
|
+
adaptiveTtlMinMs: number;
|
|
318
|
+
adaptiveTtlMaxMs: number;
|
|
319
|
+
adaptiveTtlMultiplier: number;
|
|
320
|
+
workerThreads: boolean;
|
|
321
|
+
workerThresholdBytes: number;
|
|
322
|
+
workerPoolSize: number;
|
|
323
|
+
backplaneMaxStalenessMs: number;
|
|
324
|
+
disableDisk: boolean;
|
|
325
|
+
redisClusterNodes: Array<{ host: string; port: number }> | undefined;
|
|
326
|
+
redisSentinel: { name: string; sentinels: Array<{ host: string; port: number }> } | undefined;
|
|
169
327
|
};
|
|
170
328
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
171
329
|
private readonly _namespace: string;
|
|
@@ -181,8 +339,8 @@ export class CacheService {
|
|
|
181
339
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
182
340
|
*/
|
|
183
341
|
private readonly dependencyIndex = new Map<string, Set<string>>();
|
|
184
|
-
private redis:
|
|
185
|
-
private redisConnecting: Promise<
|
|
342
|
+
private redis: AnyRedisClient | null = null;
|
|
343
|
+
private redisConnecting: Promise<AnyRedisClient> | null = null;
|
|
186
344
|
private readonly cb: L2CircuitBreaker;
|
|
187
345
|
private snapshotLoaded = false;
|
|
188
346
|
private _readyPromise: Promise<void> = Promise.resolve();
|
|
@@ -191,9 +349,12 @@ export class CacheService {
|
|
|
191
349
|
private oomInterval: ReturnType<typeof setInterval> | null = null;
|
|
192
350
|
private metricsInterval: ReturnType<typeof setInterval> | null = null;
|
|
193
351
|
private _shutdownHandler: (() => void) | null = null;
|
|
352
|
+
private latencyTracker: LatencyTracker | null = null;
|
|
194
353
|
private readonly instanceId: string;
|
|
195
354
|
private readonly backplaneChannel: string;
|
|
196
|
-
private subClient:
|
|
355
|
+
private subClient: AnyRedisClient | null = null;
|
|
356
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
357
|
+
private _subDisconnectedAt: number | null = null;
|
|
197
358
|
private readonly counters = {
|
|
198
359
|
gets: 0,
|
|
199
360
|
l1Hits: 0,
|
|
@@ -270,6 +431,7 @@ export class CacheService {
|
|
|
270
431
|
staleIfError: options.staleIfError ?? 0,
|
|
271
432
|
l2WriteMode: options.l2WriteMode ?? 'read-write',
|
|
272
433
|
instanceName: options.instanceName ?? '',
|
|
434
|
+
l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
|
|
273
435
|
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
274
436
|
tracer: options.tracer,
|
|
275
437
|
notFoundTtl: options.notFoundTtl ?? 0,
|
|
@@ -277,6 +439,17 @@ export class CacheService {
|
|
|
277
439
|
onHit: options.onHit,
|
|
278
440
|
onMiss: options.onMiss,
|
|
279
441
|
frozen: options.frozen ?? false,
|
|
442
|
+
adaptiveTtl: options.adaptiveTtl ?? false,
|
|
443
|
+
adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1_000,
|
|
444
|
+
adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86_400) * 1_000,
|
|
445
|
+
adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
|
|
446
|
+
workerThreads: options.workerThreads ?? false,
|
|
447
|
+
workerThresholdBytes: options.workerThresholdBytes ?? 131_072, // 128 KB
|
|
448
|
+
workerPoolSize: options.workerPoolSize ?? 0, // 0 = auto (min(4, cpus))
|
|
449
|
+
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5_000,
|
|
450
|
+
disableDisk: options.disableDisk ?? false,
|
|
451
|
+
redisClusterNodes: options.redisClusterNodes,
|
|
452
|
+
redisSentinel: options.redisSentinel,
|
|
280
453
|
};
|
|
281
454
|
|
|
282
455
|
// Circuit breaker for L2 Redis
|
|
@@ -284,7 +457,31 @@ export class CacheService {
|
|
|
284
457
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
|
|
285
458
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
286
459
|
|
|
287
|
-
//
|
|
460
|
+
// Adaptive TTL latency tracker (only allocated when the feature is enabled)
|
|
461
|
+
if (this.opts.adaptiveTtl) {
|
|
462
|
+
const samples = options.adaptiveTtlSamples ?? 32;
|
|
463
|
+
const maxKeys = options.adaptiveTtlMaxKeys ?? 5_000;
|
|
464
|
+
this.latencyTracker = new LatencyTracker(samples, maxKeys);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ── Fix 3: Serverless / ephemeral-disk detection ──────────────────────────
|
|
468
|
+
// Resolve disk-disabled flag: explicit option wins; else auto-detect runtime.
|
|
469
|
+
let diskDisabled = this.opts.disableDisk;
|
|
470
|
+
if (options.disableDisk === undefined) {
|
|
471
|
+
const serverless = detectServerlessRuntime();
|
|
472
|
+
if (serverless !== null) {
|
|
473
|
+
diskDisabled = true;
|
|
474
|
+
logger.warn('tricache: disk tier auto-disabled (ephemeral filesystem detected)', {
|
|
475
|
+
runtime: serverless,
|
|
476
|
+
hint: 'Set disableDisk: false to override, or disableDisk: true to silence this warning',
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
} else if (diskDisabled) {
|
|
480
|
+
logger.info('tricache: disk tier explicitly disabled (disableDisk: true)');
|
|
481
|
+
}
|
|
482
|
+
this._diskDisabled = diskDisabled;
|
|
483
|
+
|
|
484
|
+
// L1.5 disk tier (always constructed for metrics shape; ops are no-ops when disabled)
|
|
288
485
|
this.disk = new DiskTier({
|
|
289
486
|
dir: this.opts.diskCacheDir,
|
|
290
487
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -295,14 +492,19 @@ export class CacheService {
|
|
|
295
492
|
});
|
|
296
493
|
|
|
297
494
|
this._namespace = ns;
|
|
298
|
-
|
|
495
|
+
// disableRedis takes unconditional precedence; otherwise, L2 is active when
|
|
496
|
+
// at least one of host / cluster nodes / sentinel is configured.
|
|
497
|
+
this._redisDisabled = this.opts.disableRedis
|
|
498
|
+
|| (!this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel);
|
|
299
499
|
|
|
300
500
|
// L1 in-memory cache
|
|
301
501
|
this.l1 = new SmartMemoryCache({
|
|
302
502
|
maxBytes: this.opts.l1MaxBytes,
|
|
303
503
|
maxEntries: this.opts.l1MaxEntries,
|
|
304
504
|
categories: this.opts.categoryLimits,
|
|
505
|
+
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
305
506
|
diskSpill: (key: string, entry: SmartCacheEntry) => {
|
|
507
|
+
if (this._diskDisabled) return; // Fix 3: skip spill in serverless environments
|
|
306
508
|
// Defer disk.save() entirely to the next event-loop tick so the synchronous
|
|
307
509
|
// preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
|
|
308
510
|
// the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
|
|
@@ -316,14 +518,44 @@ export class CacheService {
|
|
|
316
518
|
// Load snapshot once per process
|
|
317
519
|
if (!this.snapshotLoaded) {
|
|
318
520
|
this.snapshotLoaded = true;
|
|
319
|
-
this.loadSnapshot();
|
|
521
|
+
if (!this._diskDisabled) this.loadSnapshot(); // Fix 3: skip in ephemeral environments
|
|
320
522
|
}
|
|
321
523
|
|
|
322
524
|
// Graceful shutdown: persist L1 to disk
|
|
323
|
-
this._shutdownHandler = () => { this.writeSnapshot(); process.exit(0); };
|
|
525
|
+
this._shutdownHandler = () => { if (!this._diskDisabled) this.writeSnapshot(); process.exit(0); };
|
|
324
526
|
process.once('SIGTERM', this._shutdownHandler);
|
|
325
527
|
process.once('SIGINT', this._shutdownHandler);
|
|
326
528
|
|
|
529
|
+
// ── Fix 1: Worker thread pool for off-main-thread AES-GCM ────────────────
|
|
530
|
+
if (this.opts.workerThreads && this.enc.isEnabled) {
|
|
531
|
+
try {
|
|
532
|
+
const encRef = this.enc as unknown as {
|
|
533
|
+
_key: Buffer | null;
|
|
534
|
+
_mode: string;
|
|
535
|
+
_prevKey: Buffer | null;
|
|
536
|
+
_prevMode: string;
|
|
537
|
+
};
|
|
538
|
+
this._workerPool = new WorkerPool({
|
|
539
|
+
keyBase64: encRef._key ? encRef._key.toString('base64') : '',
|
|
540
|
+
mode: encRef._mode as never,
|
|
541
|
+
prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString('base64') : undefined,
|
|
542
|
+
prevMode: encRef._prevMode as never,
|
|
543
|
+
size: this.opts.workerPoolSize || undefined,
|
|
544
|
+
});
|
|
545
|
+
if (this._workerPool.isAvailable) {
|
|
546
|
+
logger.info('tricache: worker-thread encryption pool active', {
|
|
547
|
+
threshold: `${this.opts.workerThresholdBytes / 1024} KB`,
|
|
548
|
+
});
|
|
549
|
+
} else {
|
|
550
|
+
this._workerPool = null;
|
|
551
|
+
logger.warn('tricache: worker-thread pool requested but unavailable; using main-thread crypto');
|
|
552
|
+
}
|
|
553
|
+
} catch {
|
|
554
|
+
this._workerPool = null;
|
|
555
|
+
logger.warn('tricache: worker-thread pool init failed; using main-thread crypto');
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
327
559
|
// Periodic L1 cleanup (5 min): expires stale entries and rebalances frequency counters.
|
|
328
560
|
// Disk cleanup is handled entirely by the janitor below — purgeExpired() is NOT called
|
|
329
561
|
// here to avoid a synchronous O(fileCount) event-loop stall at scale.
|
|
@@ -333,20 +565,20 @@ export class CacheService {
|
|
|
333
565
|
}, 5 * 60 * 1000);
|
|
334
566
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
|
|
335
567
|
|
|
336
|
-
// Disk janitor:
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
568
|
+
// Disk janitor (Fix 3: skip when disk is disabled)
|
|
569
|
+
if (!this._diskDisabled) {
|
|
570
|
+
this.diskJanitorInterval = setInterval(() => {
|
|
571
|
+
const purged = this.disk.purgeNextBucket();
|
|
572
|
+
if (purged > 0) this.logger.debug('Disk janitor tick', { purged });
|
|
573
|
+
}, 30_000);
|
|
574
|
+
if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
|
|
575
|
+
}
|
|
344
576
|
|
|
345
577
|
// OOM protection: evict coldest L1 entries when heap pressure rises
|
|
346
578
|
if (this.opts.oomProtection) {
|
|
347
579
|
this.oomInterval = setInterval(() => {
|
|
348
|
-
const
|
|
349
|
-
const used =
|
|
580
|
+
const heap = v8.getHeapStatistics();
|
|
581
|
+
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
350
582
|
if (used >= this.opts.oomHeapThreshold) {
|
|
351
583
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
352
584
|
this.counters.oomEvictions++;
|
|
@@ -464,21 +696,69 @@ export class CacheService {
|
|
|
464
696
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
465
697
|
if (this.subClient) return;
|
|
466
698
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
})
|
|
699
|
+
// ── Fix 4: Cluster/Sentinel subscriber ─────────────────────────────────
|
|
700
|
+
let sub: AnyRedisClient;
|
|
701
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
702
|
+
sub = new RedisCluster(this.opts.redisClusterNodes, {
|
|
703
|
+
redisOptions: {
|
|
704
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
705
|
+
connectTimeout: 10_000,
|
|
706
|
+
maxRetriesPerRequest: null as unknown as number,
|
|
707
|
+
},
|
|
708
|
+
});
|
|
709
|
+
} else if (this.opts.redisSentinel) {
|
|
710
|
+
sub = new RedisClient({
|
|
711
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
712
|
+
name: this.opts.redisSentinel.name,
|
|
713
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
714
|
+
connectTimeout: 10_000,
|
|
715
|
+
lazyConnect: true,
|
|
716
|
+
maxRetriesPerRequest: null as unknown as number,
|
|
717
|
+
enableAutoPipelining: false,
|
|
718
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
719
|
+
});
|
|
720
|
+
} else {
|
|
721
|
+
sub = new RedisClient({
|
|
722
|
+
host: this.opts.redisHost,
|
|
723
|
+
port: this.opts.redisPort,
|
|
724
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
725
|
+
connectTimeout: 10_000,
|
|
726
|
+
lazyConnect: true,
|
|
727
|
+
maxRetriesPerRequest: null as unknown as number,
|
|
728
|
+
enableAutoPipelining: false,
|
|
729
|
+
family: 4,
|
|
730
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
731
|
+
});
|
|
732
|
+
}
|
|
478
733
|
|
|
479
734
|
sub.on('error', (e: Error) =>
|
|
480
735
|
this.logger.debug('Backplane subscriber error', { error: e.message }));
|
|
481
736
|
|
|
737
|
+
// ── Fix 2: Staleness fence — track disconnect time ──────────────────────
|
|
738
|
+
sub.on('close', () => {
|
|
739
|
+
if (this._subDisconnectedAt === null) {
|
|
740
|
+
this._subDisconnectedAt = Date.now();
|
|
741
|
+
this.logger.debug('Backplane: subscriber disconnected', { at: this._subDisconnectedAt });
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
sub.on('ready', () => {
|
|
746
|
+
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
747
|
+
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
748
|
+
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
749
|
+
// We were disconnected long enough that peer invalidations were
|
|
750
|
+
// almost certainly missed. Evict every L1 entry written before
|
|
751
|
+
// the disconnect started so stale data cannot be served.
|
|
752
|
+
const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
|
|
753
|
+
this.logger.warn('Backplane: reconnect after gap — flushed potentially stale L1 entries', {
|
|
754
|
+
gapMs, evicted,
|
|
755
|
+
hint: 'Increase backplaneMaxStalenessMs or set to 0 to disable the fence',
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
this._subDisconnectedAt = null;
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
|
|
482
762
|
sub.on('message', (_channel: string, message: string) => {
|
|
483
763
|
this._handleBackplaneMessage(message);
|
|
484
764
|
});
|
|
@@ -508,7 +788,7 @@ export class CacheService {
|
|
|
508
788
|
// setImmediate so the event-loop tick that processes this pub/sub
|
|
509
789
|
// message returns immediately without blocking hot get() calls.
|
|
510
790
|
this.l1.delete(msg.key);
|
|
511
|
-
setImmediate(() => this.disk.delete(msg.key));
|
|
791
|
+
setImmediate(() => { if (!this._diskDisabled) this.disk.delete(msg.key); });
|
|
512
792
|
// Cascade: evict dependents registered on this instance for the
|
|
513
793
|
// deleted key — same logic the local delete() path runs, now also
|
|
514
794
|
// applied to peer-originated invalidations so fleet-wide deletes
|
|
@@ -537,28 +817,92 @@ export class CacheService {
|
|
|
537
817
|
} catch { /* non-critical — never block the caller */ }
|
|
538
818
|
}
|
|
539
819
|
|
|
540
|
-
|
|
820
|
+
/**
|
|
821
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
822
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
823
|
+
*/
|
|
824
|
+
private async _scanKeys(client: AnyRedisClient, pattern: string): Promise<string[]> {
|
|
825
|
+
const keys: string[] = [];
|
|
826
|
+
if (client instanceof RedisCluster) {
|
|
827
|
+
const masters = client.nodes('master');
|
|
828
|
+
await Promise.all(masters.map((node: RedisClient) =>
|
|
829
|
+
new Promise<void>((resolve, reject) => {
|
|
830
|
+
const stream = node.scanStream({ match: pattern, count: 100 });
|
|
831
|
+
stream.on('data', (chunk: string[]) => keys.push(...chunk));
|
|
832
|
+
stream.on('end', resolve);
|
|
833
|
+
stream.on('error', reject);
|
|
834
|
+
}),
|
|
835
|
+
));
|
|
836
|
+
} else {
|
|
837
|
+
await new Promise<void>((resolve, reject) => {
|
|
838
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
839
|
+
stream.on('data', (chunk: string[]) => keys.push(...chunk));
|
|
840
|
+
stream.on('end', resolve);
|
|
841
|
+
stream.on('error', reject);
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
return keys;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
private async getRedis(): Promise<AnyRedisClient> {
|
|
541
848
|
if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
|
|
542
849
|
if (this.redisConnecting) return this.redisConnecting;
|
|
543
850
|
|
|
544
851
|
this.redisConnecting = (async () => {
|
|
545
852
|
try {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
853
|
+
// ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
|
|
854
|
+
let client: AnyRedisClient;
|
|
855
|
+
|
|
856
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
857
|
+
// Redis Cluster — ioredis handles slot routing and multi-node pooling.
|
|
858
|
+
client = new RedisCluster(this.opts.redisClusterNodes, {
|
|
859
|
+
redisOptions: {
|
|
860
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
861
|
+
connectTimeout: 10_000,
|
|
862
|
+
maxRetriesPerRequest: 3,
|
|
863
|
+
keepAlive: 30_000,
|
|
864
|
+
},
|
|
865
|
+
enableAutoPipelining: true,
|
|
866
|
+
retryDelayOnClusterDown: 200,
|
|
867
|
+
retryDelayOnFailover: 1_000,
|
|
868
|
+
});
|
|
869
|
+
client.on('connect', () => this.logger.info('Redis Cluster connected'));
|
|
870
|
+
client.on('error', (e: Error) => this.logger.error('Redis Cluster error', {}, e));
|
|
871
|
+
client.on('reconnecting', () => this.logger.debug('Redis Cluster reconnecting'));
|
|
872
|
+
} else if (this.opts.redisSentinel) {
|
|
873
|
+
// Redis Sentinel — ioredis monitors master via sentinel topology.
|
|
874
|
+
client = new RedisClient({
|
|
875
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
876
|
+
name: this.opts.redisSentinel.name,
|
|
877
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
878
|
+
connectTimeout: 10_000,
|
|
879
|
+
lazyConnect: false,
|
|
880
|
+
maxRetriesPerRequest: 3,
|
|
881
|
+
enableAutoPipelining: true,
|
|
882
|
+
keepAlive: 30_000,
|
|
883
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
884
|
+
});
|
|
885
|
+
client.on('connect', () => this.logger.info('Redis Sentinel connected', { name: this.opts.redisSentinel!.name }));
|
|
886
|
+
client.on('error', (e: Error) => this.logger.error('Redis Sentinel error', { name: this.opts.redisSentinel!.name }, e));
|
|
887
|
+
client.on('reconnecting', () => this.logger.debug('Redis Sentinel reconnecting'));
|
|
888
|
+
} else {
|
|
889
|
+
// Single-node (original path)
|
|
890
|
+
client = new RedisClient({
|
|
891
|
+
host: this.opts.redisHost,
|
|
892
|
+
port: this.opts.redisPort,
|
|
893
|
+
tls: this.opts.redisTls ? {} : undefined,
|
|
894
|
+
connectTimeout: 10_000,
|
|
895
|
+
lazyConnect: false,
|
|
896
|
+
maxRetriesPerRequest: 3,
|
|
897
|
+
enableAutoPipelining: true,
|
|
898
|
+
keepAlive: 30_000,
|
|
899
|
+
family: 4,
|
|
900
|
+
retryStrategy: (times: number) => Math.min(times * 50, 2_000),
|
|
901
|
+
});
|
|
902
|
+
client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
|
|
903
|
+
client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
|
|
904
|
+
client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
|
|
905
|
+
}
|
|
562
906
|
|
|
563
907
|
await new Promise<void>((resolve, reject) => {
|
|
564
908
|
client.once('ready', resolve);
|
|
@@ -700,13 +1044,25 @@ export class CacheService {
|
|
|
700
1044
|
const k = this.nk(cacheKey); // namespaced key used for all storage
|
|
701
1045
|
this.counters.gets++;
|
|
702
1046
|
|
|
1047
|
+
// Normalize all opts fields to plain locals once. Every opts.XXX read
|
|
1048
|
+
// elsewhere in this function would hit a polymorphic IC when callers pass
|
|
1049
|
+
// different option shapes: {}, { swr }, { refreshAhead }, { tags }, etc.
|
|
1050
|
+
// Reading everything here collapses all downstream accesses to fast
|
|
1051
|
+
// monomorphic local-variable reads regardless of call-site variety.
|
|
1052
|
+
const optSwr = opts.swr ?? 0;
|
|
1053
|
+
const optPriority = opts.priority;
|
|
1054
|
+
const optRefreshAhead = opts.refreshAhead;
|
|
1055
|
+
const optXfetchBeta = opts.xfetchBeta;
|
|
1056
|
+
const optNotFoundTtl = opts.notFoundTtl;
|
|
1057
|
+
const optTags = opts.tags;
|
|
1058
|
+
|
|
703
1059
|
// L1: in-memory (fastest path)
|
|
704
1060
|
const l1Hit = this.l1.get(k);
|
|
705
1061
|
if (l1Hit !== null) {
|
|
706
1062
|
if (l1Hit.isStale) {
|
|
707
|
-
const swrGraceMs =
|
|
1063
|
+
const swrGraceMs = optSwr * 1_000;
|
|
708
1064
|
if (swrGraceMs > 0 && !this.revalidating.has(k)) {
|
|
709
|
-
const priority =
|
|
1065
|
+
const priority = optPriority ?? inferPriority(cacheKey);
|
|
710
1066
|
this.revalidating.add(k);
|
|
711
1067
|
void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
|
|
712
1068
|
this.counters.swrRevalidations++;
|
|
@@ -719,20 +1075,21 @@ export class CacheService {
|
|
|
719
1075
|
// Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
|
|
720
1076
|
// l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
|
|
721
1077
|
// Check opts first — pointless work when neither feature is configured.
|
|
722
|
-
|
|
1078
|
+
// Local aliases for the opts fields already normalised at function entry.
|
|
1079
|
+
const ra = optRefreshAhead;
|
|
1080
|
+
const xb = optXfetchBeta;
|
|
1081
|
+
if (ra || xb) {
|
|
723
1082
|
// Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
|
|
724
1083
|
const now = l1Hit.fetchedAt ?? Date.now();
|
|
725
1084
|
const remaining = l1Hit.expiresAt - now;
|
|
726
1085
|
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
|
|
727
1086
|
|
|
728
|
-
const shouldRefreshAhead =
|
|
729
|
-
? remaining <= entryTtl * (1 - opts.refreshAhead)
|
|
730
|
-
: false;
|
|
1087
|
+
const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
|
|
731
1088
|
|
|
732
1089
|
// XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
|
|
733
1090
|
// Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
|
|
734
|
-
const shouldXFetch =
|
|
735
|
-
? remaining <= l1Hit.delta *
|
|
1091
|
+
const shouldXFetch = xb && l1Hit.delta != null
|
|
1092
|
+
? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
|
|
736
1093
|
: false;
|
|
737
1094
|
|
|
738
1095
|
// Set.has() deferred to here — the common case (fresh key, threshold not crossed)
|
|
@@ -740,9 +1097,9 @@ export class CacheService {
|
|
|
740
1097
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
741
1098
|
// Defer inferPriority until we actually need it — avoids 3× string.includes()
|
|
742
1099
|
// scans on every warm hit when the threshold check is false (the common case).
|
|
743
|
-
const priority =
|
|
1100
|
+
const priority = optPriority ?? inferPriority(cacheKey);
|
|
744
1101
|
this.revalidating.add(k);
|
|
745
|
-
void this._revalidate(k, fetchFn, entryTtl,
|
|
1102
|
+
void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
|
|
746
1103
|
this.counters.swrRevalidations++;
|
|
747
1104
|
this.logger.debug(
|
|
748
1105
|
shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
|
|
@@ -759,8 +1116,8 @@ export class CacheService {
|
|
|
759
1116
|
}
|
|
760
1117
|
|
|
761
1118
|
const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
|
|
762
|
-
const swrGraceMs =
|
|
763
|
-
const priority =
|
|
1119
|
+
const swrGraceMs = optSwr * 1_000;
|
|
1120
|
+
const priority = optPriority ?? inferPriority(cacheKey);
|
|
764
1121
|
|
|
765
1122
|
// L2: Redis (distributed, production-only by default)
|
|
766
1123
|
if (!this._redisDisabled) {
|
|
@@ -769,8 +1126,14 @@ export class CacheService {
|
|
|
769
1126
|
const raw = await client.get(k);
|
|
770
1127
|
this.cb.onSuccess();
|
|
771
1128
|
if (raw) {
|
|
772
|
-
|
|
773
|
-
|
|
1129
|
+
// ── Fix 1: offload decryption to worker thread for large payloads ──
|
|
1130
|
+
let decrypted: string;
|
|
1131
|
+
if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
|
|
1132
|
+
decrypted = await this._workerPool.decrypt(raw);
|
|
1133
|
+
} else {
|
|
1134
|
+
decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
1135
|
+
}
|
|
1136
|
+
const parsed = JSON.parse(decrypted) as T;
|
|
774
1137
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
775
1138
|
this.counters.l2Hits++;
|
|
776
1139
|
this.opts.onHit?.(cacheKey, 'l2');
|
|
@@ -784,21 +1147,23 @@ export class CacheService {
|
|
|
784
1147
|
}
|
|
785
1148
|
}
|
|
786
1149
|
|
|
787
|
-
// L1.5: disk tier (evicted L1 entries)
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1150
|
+
// L1.5: disk tier (evicted L1 entries) — skipped when disk is disabled
|
|
1151
|
+
if (!this._diskDisabled) {
|
|
1152
|
+
const diskHit = this.disk.load(k);
|
|
1153
|
+
if (diskHit !== null) {
|
|
1154
|
+
const promoted = this.l1.importEntries(
|
|
1155
|
+
[{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
|
|
1156
|
+
this.opts.forbiddenSnapshotPrefixes,
|
|
1157
|
+
);
|
|
1158
|
+
if (promoted > 0) {
|
|
1159
|
+
const l1Check = this.l1.get(k);
|
|
1160
|
+
if (l1Check !== null) {
|
|
1161
|
+
this.counters.diskHits++;
|
|
1162
|
+
this.opts.onHit?.(cacheKey, 'disk');
|
|
1163
|
+
this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
|
|
1164
|
+
span.setAttribute('cache.hit', 'disk').end();
|
|
1165
|
+
return l1Check.value as T;
|
|
1166
|
+
}
|
|
802
1167
|
}
|
|
803
1168
|
}
|
|
804
1169
|
}
|
|
@@ -823,20 +1188,41 @@ export class CacheService {
|
|
|
823
1188
|
const delta = Date.now() - fetchStart;
|
|
824
1189
|
|
|
825
1190
|
// Negative caching: null/undefined results get their own (shorter) TTL
|
|
826
|
-
const notFoundTtlMs = (
|
|
827
|
-
|
|
1191
|
+
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
|
|
1192
|
+
let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
|
|
1193
|
+
|
|
1194
|
+
// Adaptive TTL: record this fetch duration and override the caller-supplied
|
|
1195
|
+
// TTL once ≥ 5 samples are available for the key.
|
|
1196
|
+
// Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
|
|
1197
|
+
if (this.latencyTracker && data != null) {
|
|
1198
|
+
this.latencyTracker.record(k, delta);
|
|
1199
|
+
const p95 = this.latencyTracker.p95(k);
|
|
1200
|
+
if (p95 !== null) {
|
|
1201
|
+
const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1_000);
|
|
1202
|
+
effectiveTtl = Math.max(
|
|
1203
|
+
this.opts.adaptiveTtlMinMs,
|
|
1204
|
+
Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs),
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
828
1208
|
|
|
829
1209
|
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
|
|
830
1210
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
831
1211
|
|
|
832
1212
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta);
|
|
833
|
-
if (
|
|
1213
|
+
if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
|
|
834
1214
|
|
|
835
1215
|
if (!this._redisDisabled) {
|
|
836
1216
|
try {
|
|
837
1217
|
const client = await this.getRedis();
|
|
838
1218
|
const serialized = JSON.stringify(data);
|
|
839
|
-
|
|
1219
|
+
// ── Fix 1: offload encryption to worker thread for large payloads ──
|
|
1220
|
+
let toStore: string;
|
|
1221
|
+
if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
|
|
1222
|
+
toStore = await this._workerPool.encrypt(serialized);
|
|
1223
|
+
} else {
|
|
1224
|
+
toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1225
|
+
}
|
|
840
1226
|
await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
|
|
841
1227
|
this.cb.onSuccess();
|
|
842
1228
|
this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
@@ -871,13 +1257,23 @@ export class CacheService {
|
|
|
871
1257
|
const data = await fetchFn();
|
|
872
1258
|
const delta = Date.now() - fetchStart;
|
|
873
1259
|
const staleAt = Date.now() + ttlMs;
|
|
1260
|
+
|
|
1261
|
+
// Keep the latency tracker current during SWR background revalidations too
|
|
1262
|
+
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
1263
|
+
|
|
874
1264
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
|
|
875
1265
|
|
|
876
1266
|
if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
|
|
877
1267
|
try {
|
|
878
1268
|
const client = await this.getRedis();
|
|
879
1269
|
const s = JSON.stringify(data);
|
|
880
|
-
|
|
1270
|
+
// ── Fix 1: offload encryption to worker thread for large payloads ──
|
|
1271
|
+
let stored: string;
|
|
1272
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
1273
|
+
stored = await this._workerPool.encrypt(s);
|
|
1274
|
+
} else {
|
|
1275
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1276
|
+
}
|
|
881
1277
|
await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
|
|
882
1278
|
} catch { /* ok */ }
|
|
883
1279
|
}
|
|
@@ -926,7 +1322,13 @@ export class CacheService {
|
|
|
926
1322
|
try {
|
|
927
1323
|
const client = await this.getRedis();
|
|
928
1324
|
const s = JSON.stringify(data);
|
|
929
|
-
|
|
1325
|
+
// ── Fix 1: offload encryption to worker thread for large payloads ──
|
|
1326
|
+
let stored: string;
|
|
1327
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
1328
|
+
stored = await this._workerPool.encrypt(s);
|
|
1329
|
+
} else {
|
|
1330
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1331
|
+
}
|
|
930
1332
|
await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
|
|
931
1333
|
this.cb.onSuccess();
|
|
932
1334
|
} catch (err) {
|
|
@@ -989,7 +1391,7 @@ export class CacheService {
|
|
|
989
1391
|
// A re-get in the narrow window before the deferred call fires would get an L1 miss
|
|
990
1392
|
// and promote the disk entry back — acceptable for a cache (same trade-off the backplane
|
|
991
1393
|
// path already accepts).
|
|
992
|
-
setImmediate(() => this.disk.delete(k));
|
|
1394
|
+
setImmediate(() => { if (!this._diskDisabled) this.disk.delete(k); });
|
|
993
1395
|
// Cascade: invalidate any key that declared it depends on this exact key's pattern
|
|
994
1396
|
this._cascadeDependencies(k);
|
|
995
1397
|
// Clean up: remove k from all dependency registrations (it is gone)
|
|
@@ -1000,13 +1402,7 @@ export class CacheService {
|
|
|
1000
1402
|
try {
|
|
1001
1403
|
const client = await this.getRedis();
|
|
1002
1404
|
if (isPattern) {
|
|
1003
|
-
const
|
|
1004
|
-
const keys: string[] = [];
|
|
1005
|
-
await new Promise<void>((resolve, reject) => {
|
|
1006
|
-
stream.on('data', (chunk: string[]) => keys.push(...chunk));
|
|
1007
|
-
stream.on('end', resolve);
|
|
1008
|
-
stream.on('error', reject);
|
|
1009
|
-
});
|
|
1405
|
+
const keys = await this._scanKeys(client, k);
|
|
1010
1406
|
if (keys.length > 0) await client.del(...keys);
|
|
1011
1407
|
} else {
|
|
1012
1408
|
await client.del(k);
|
|
@@ -1075,7 +1471,7 @@ export class CacheService {
|
|
|
1075
1471
|
// prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
|
|
1076
1472
|
} else {
|
|
1077
1473
|
this.l1.clear();
|
|
1078
|
-
this.disk.clear();
|
|
1474
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
1079
1475
|
this._l1Counters.clear();
|
|
1080
1476
|
this.tagIndex.clear();
|
|
1081
1477
|
}
|
|
@@ -1084,13 +1480,7 @@ export class CacheService {
|
|
|
1084
1480
|
try {
|
|
1085
1481
|
const client = await this.getRedis();
|
|
1086
1482
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
|
|
1087
|
-
const
|
|
1088
|
-
const keys: string[] = [];
|
|
1089
|
-
await new Promise<void>((resolve, reject) => {
|
|
1090
|
-
stream.on('data', (chunk: string[]) => keys.push(...chunk));
|
|
1091
|
-
stream.on('end', resolve);
|
|
1092
|
-
stream.on('error', reject);
|
|
1093
|
-
});
|
|
1483
|
+
const keys = await this._scanKeys(client, pattern);
|
|
1094
1484
|
if (keys.length > 0) await client.del(...keys);
|
|
1095
1485
|
} catch (err) {
|
|
1096
1486
|
this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
|
|
@@ -1343,14 +1733,8 @@ export class CacheService {
|
|
|
1343
1733
|
const client = await this.getRedis();
|
|
1344
1734
|
const nsPattern = this.nk(pattern);
|
|
1345
1735
|
|
|
1346
|
-
// Collect all matching keys via SCAN
|
|
1347
|
-
const matchedKeys
|
|
1348
|
-
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
1349
|
-
await new Promise<void>((resolve, reject) => {
|
|
1350
|
-
stream.on('data', (chunk: string[]) => matchedKeys.push(...chunk));
|
|
1351
|
-
stream.on('end', resolve);
|
|
1352
|
-
stream.on('error', reject);
|
|
1353
|
-
});
|
|
1736
|
+
// Collect all matching keys via SCAN (handles single-node and Cluster)
|
|
1737
|
+
const matchedKeys = await this._scanKeys(client, nsPattern);
|
|
1354
1738
|
|
|
1355
1739
|
if (matchedKeys.length === 0) {
|
|
1356
1740
|
this.cb.onSuccess();
|
|
@@ -1406,7 +1790,7 @@ export class CacheService {
|
|
|
1406
1790
|
// Remove from L1 + disk
|
|
1407
1791
|
for (const k of members) {
|
|
1408
1792
|
this.l1.delete(k);
|
|
1409
|
-
this.disk.delete(k);
|
|
1793
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
1410
1794
|
}
|
|
1411
1795
|
this.tagIndex.delete(tagKey);
|
|
1412
1796
|
|
|
@@ -1643,7 +2027,7 @@ export class CacheService {
|
|
|
1643
2027
|
for (const dep of dependents) {
|
|
1644
2028
|
if (dep === deletedKey) continue; // no self-cascade
|
|
1645
2029
|
this.l1.delete(dep);
|
|
1646
|
-
this.disk.delete(dep);
|
|
2030
|
+
if (!this._diskDisabled) this.disk.delete(dep);
|
|
1647
2031
|
void this.publishInvalidation('del', dep);
|
|
1648
2032
|
this.logger.debug('Dependency cascade: invalidated dependent key', {
|
|
1649
2033
|
trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
|
|
@@ -1716,7 +2100,19 @@ export class CacheService {
|
|
|
1716
2100
|
sizeBytes: this.l1.memoryUsage,
|
|
1717
2101
|
maxBytes: this.opts.l1MaxBytes,
|
|
1718
2102
|
},
|
|
1719
|
-
disk: this.disk.stats,
|
|
2103
|
+
disk: { ...this.disk.stats, disabled: this._diskDisabled },
|
|
2104
|
+
...(this.latencyTracker && {
|
|
2105
|
+
adaptiveTtl: {
|
|
2106
|
+
enabled: true as const,
|
|
2107
|
+
trackedKeys: this.latencyTracker.trackedKeys,
|
|
2108
|
+
slowestKeys: this.latencyTracker.snapshot(
|
|
2109
|
+
this._namespace ? this._namespace.length + 1 : 0, // strip "namespace:" prefix
|
|
2110
|
+
this.opts.adaptiveTtlMultiplier,
|
|
2111
|
+
this.opts.adaptiveTtlMinMs,
|
|
2112
|
+
this.opts.adaptiveTtlMaxMs,
|
|
2113
|
+
),
|
|
2114
|
+
},
|
|
2115
|
+
}),
|
|
1720
2116
|
};
|
|
1721
2117
|
}
|
|
1722
2118
|
|
|
@@ -1794,6 +2190,10 @@ export class CacheService {
|
|
|
1794
2190
|
process.off('SIGINT', this._shutdownHandler);
|
|
1795
2191
|
this._shutdownHandler = null;
|
|
1796
2192
|
}
|
|
2193
|
+
if (this._workerPool) {
|
|
2194
|
+
await this._workerPool.destroy();
|
|
2195
|
+
this._workerPool = null;
|
|
2196
|
+
}
|
|
1797
2197
|
if (this.subClient) {
|
|
1798
2198
|
try { await this.subClient.quit(); } catch { /* ok */ }
|
|
1799
2199
|
this.subClient = null;
|
|
@@ -1802,6 +2202,7 @@ export class CacheService {
|
|
|
1802
2202
|
try { await this.redis.disconnect(); } catch { /* ok */ }
|
|
1803
2203
|
this.redis = null;
|
|
1804
2204
|
}
|
|
2205
|
+
if (!this._diskDisabled) this.disk.close();
|
|
1805
2206
|
}
|
|
1806
2207
|
|
|
1807
2208
|
}
|