tricache 0.6.0 → 0.6.2

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.
Files changed (42) hide show
  1. package/README.md +119 -0
  2. package/dist/chunk-F24NEZGQ.js +342 -0
  3. package/dist/index.cjs +494 -164
  4. package/dist/index.d.cts +125 -0
  5. package/dist/index.d.ts +1552 -18
  6. package/dist/index.js +3524 -25
  7. package/dist/serialize-worker.cjs +366 -0
  8. package/dist/serialize-worker.d.cts +2 -0
  9. package/dist/serialize-worker.d.ts +2 -0
  10. package/dist/serialize-worker.js +35 -0
  11. package/package.json +5 -5
  12. package/src/cache-service.ts +310 -93
  13. package/src/serialize-worker.ts +56 -0
  14. package/src/smart-memory-cache.ts +42 -1
  15. package/src/types.ts +99 -1
  16. package/src/worker-pool.ts +190 -0
  17. package/dist/cache-service.d.ts +0 -419
  18. package/dist/cache-service.d.ts.map +0 -1
  19. package/dist/cache-service.js +0 -1788
  20. package/dist/cache-service.js.map +0 -1
  21. package/dist/disk-tier.d.ts +0 -150
  22. package/dist/disk-tier.d.ts.map +0 -1
  23. package/dist/disk-tier.js +0 -808
  24. package/dist/disk-tier.js.map +0 -1
  25. package/dist/encryption.d.ts +0 -90
  26. package/dist/encryption.d.ts.map +0 -1
  27. package/dist/encryption.js +0 -393
  28. package/dist/encryption.js.map +0 -1
  29. package/dist/index.d.ts.map +0 -1
  30. package/dist/index.js.map +0 -1
  31. package/dist/smart-memory-cache.d.ts +0 -208
  32. package/dist/smart-memory-cache.d.ts.map +0 -1
  33. package/dist/smart-memory-cache.js +0 -933
  34. package/dist/smart-memory-cache.js.map +0 -1
  35. package/dist/types.d.ts +0 -537
  36. package/dist/types.d.ts.map +0 -1
  37. package/dist/types.js +0 -20
  38. package/dist/types.js.map +0 -1
  39. package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
  40. package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
  41. package/dist/wasm/bloom-filter-wasm.js +0 -83
  42. package/dist/wasm/bloom-filter-wasm.js.map +0 -1
@@ -16,10 +16,11 @@
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';
23
24
  import v8 from 'node:v8';
24
25
  import fs from 'fs';
25
26
  import path from 'path';
@@ -258,11 +259,36 @@ function inferPriority(cacheKey: string): CachePriority {
258
259
  // globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
259
260
  const GLOBAL_KEY = '__tricache_instance__';
260
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
+
261
283
  export class CacheService {
262
284
  private readonly logger: ILogger;
263
285
  private readonly enc: CacheEncryption;
264
286
  private readonly l1: SmartMemoryCache;
265
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;
266
292
  private readonly opts: {
267
293
  namespace: string;
268
294
  logger: ILogger; l1MaxBytes: number; l1MaxEntries: number;
@@ -291,6 +317,13 @@ export class CacheService {
291
317
  adaptiveTtlMinMs: number;
292
318
  adaptiveTtlMaxMs: number;
293
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;
294
327
  };
295
328
  /** Pre-computed once — opts.namespace never changes after construction. */
296
329
  private readonly _namespace: string;
@@ -306,8 +339,8 @@ export class CacheService {
306
339
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
307
340
  */
308
341
  private readonly dependencyIndex = new Map<string, Set<string>>();
309
- private redis: RedisClient | null = null;
310
- private redisConnecting: Promise<RedisClient> | null = null;
342
+ private redis: AnyRedisClient | null = null;
343
+ private redisConnecting: Promise<AnyRedisClient> | null = null;
311
344
  private readonly cb: L2CircuitBreaker;
312
345
  private snapshotLoaded = false;
313
346
  private _readyPromise: Promise<void> = Promise.resolve();
@@ -319,7 +352,9 @@ export class CacheService {
319
352
  private latencyTracker: LatencyTracker | null = null;
320
353
  private readonly instanceId: string;
321
354
  private readonly backplaneChannel: string;
322
- private subClient: RedisClient | null = null;
355
+ private subClient: AnyRedisClient | null = null;
356
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
357
+ private _subDisconnectedAt: number | null = null;
323
358
  private readonly counters = {
324
359
  gets: 0,
325
360
  l1Hits: 0,
@@ -408,6 +443,13 @@ export class CacheService {
408
443
  adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1_000,
409
444
  adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86_400) * 1_000,
410
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,
411
453
  };
412
454
 
413
455
  // Circuit breaker for L2 Redis
@@ -422,7 +464,24 @@ export class CacheService {
422
464
  this.latencyTracker = new LatencyTracker(samples, maxKeys);
423
465
  }
424
466
 
425
- // L1.5 disk tier
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)
426
485
  this.disk = new DiskTier({
427
486
  dir: this.opts.diskCacheDir,
428
487
  maxBytes: this.opts.diskMaxBytes,
@@ -433,7 +492,10 @@ export class CacheService {
433
492
  });
434
493
 
435
494
  this._namespace = ns;
436
- this._redisDisabled = (this.opts.disableRedis || !this.opts.redisHost);
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);
437
499
 
438
500
  // L1 in-memory cache
439
501
  this.l1 = new SmartMemoryCache({
@@ -442,6 +504,7 @@ export class CacheService {
442
504
  categories: this.opts.categoryLimits,
443
505
  evictionWatermark: this.opts.l1EvictionWatermark,
444
506
  diskSpill: (key: string, entry: SmartCacheEntry) => {
507
+ if (this._diskDisabled) return; // Fix 3: skip spill in serverless environments
445
508
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
446
509
  // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
447
510
  // the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
@@ -455,14 +518,44 @@ export class CacheService {
455
518
  // Load snapshot once per process
456
519
  if (!this.snapshotLoaded) {
457
520
  this.snapshotLoaded = true;
458
- this.loadSnapshot();
521
+ if (!this._diskDisabled) this.loadSnapshot(); // Fix 3: skip in ephemeral environments
459
522
  }
460
523
 
461
524
  // Graceful shutdown: persist L1 to disk
462
- this._shutdownHandler = () => { this.writeSnapshot(); process.exit(0); };
525
+ this._shutdownHandler = () => { if (!this._diskDisabled) this.writeSnapshot(); process.exit(0); };
463
526
  process.once('SIGTERM', this._shutdownHandler);
464
527
  process.once('SIGINT', this._shutdownHandler);
465
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
+
466
559
  // Periodic L1 cleanup (5 min): expires stale entries and rebalances frequency counters.
467
560
  // Disk cleanup is handled entirely by the janitor below — purgeExpired() is NOT called
468
561
  // here to avoid a synchronous O(fileCount) event-loop stall at scale.
@@ -472,14 +565,14 @@ export class CacheService {
472
565
  }, 5 * 60 * 1000);
473
566
  if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
474
567
 
475
- // Disk janitor: sole owner of disk expiry. Scans one of 256 subdirectory buckets per tick
476
- // (30 s × 256 = 128-min full cycle). Each tick is bounded to one bucket's worth of
477
- // readFileSync + decrypt + unpack work, capping per-tick event-loop occupancy.
478
- this.diskJanitorInterval = setInterval(() => {
479
- const purged = this.disk.purgeNextBucket();
480
- if (purged > 0) this.logger.debug('Disk janitor tick', { purged });
481
- }, 30_000);
482
- if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
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
+ }
483
576
 
484
577
  // OOM protection: evict coldest L1 entries when heap pressure rises
485
578
  if (this.opts.oomProtection) {
@@ -603,21 +696,69 @@ export class CacheService {
603
696
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
604
697
  if (this.subClient) return;
605
698
 
606
- const sub = new RedisClient({
607
- host: this.opts.redisHost,
608
- port: this.opts.redisPort,
609
- tls: this.opts.redisTls ? {} : undefined,
610
- connectTimeout: 10_000,
611
- lazyConnect: true,
612
- maxRetriesPerRequest: null as unknown as number,
613
- enableAutoPipelining: false,
614
- family: 4,
615
- retryStrategy: (times: number) => Math.min(times * 50, 2_000),
616
- });
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
+ }
617
733
 
618
734
  sub.on('error', (e: Error) =>
619
735
  this.logger.debug('Backplane subscriber error', { error: e.message }));
620
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
+
621
762
  sub.on('message', (_channel: string, message: string) => {
622
763
  this._handleBackplaneMessage(message);
623
764
  });
@@ -647,7 +788,7 @@ export class CacheService {
647
788
  // setImmediate so the event-loop tick that processes this pub/sub
648
789
  // message returns immediately without blocking hot get() calls.
649
790
  this.l1.delete(msg.key);
650
- setImmediate(() => this.disk.delete(msg.key));
791
+ setImmediate(() => { if (!this._diskDisabled) this.disk.delete(msg.key); });
651
792
  // Cascade: evict dependents registered on this instance for the
652
793
  // deleted key — same logic the local delete() path runs, now also
653
794
  // applied to peer-originated invalidations so fleet-wide deletes
@@ -676,28 +817,92 @@ export class CacheService {
676
817
  } catch { /* non-critical — never block the caller */ }
677
818
  }
678
819
 
679
- private async getRedis(): Promise<RedisClient> {
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> {
680
848
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
681
849
  if (this.redisConnecting) return this.redisConnecting;
682
850
 
683
851
  this.redisConnecting = (async () => {
684
852
  try {
685
- const client = new RedisClient({
686
- host: this.opts.redisHost,
687
- port: this.opts.redisPort,
688
- tls: this.opts.redisTls ? {} : undefined,
689
- connectTimeout: 10_000,
690
- lazyConnect: false,
691
- maxRetriesPerRequest: 3,
692
- enableAutoPipelining: true,
693
- keepAlive: 30_000,
694
- family: 4,
695
- retryStrategy: (times: number) => Math.min(times * 50, 2_000),
696
- });
697
-
698
- client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
699
- client.on('error', (e: Error) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
700
- client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
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
+ }
701
906
 
702
907
  await new Promise<void>((resolve, reject) => {
703
908
  client.once('ready', resolve);
@@ -921,8 +1126,14 @@ export class CacheService {
921
1126
  const raw = await client.get(k);
922
1127
  this.cb.onSuccess();
923
1128
  if (raw) {
924
- const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
925
- const parsed = JSON.parse(decrypted) as T;
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;
926
1137
  this.l1.set(k, parsed, ttlMs, priority);
927
1138
  this.counters.l2Hits++;
928
1139
  this.opts.onHit?.(cacheKey, 'l2');
@@ -936,21 +1147,23 @@ export class CacheService {
936
1147
  }
937
1148
  }
938
1149
 
939
- // L1.5: disk tier (evicted L1 entries)
940
- const diskHit = this.disk.load(k);
941
- if (diskHit !== null) {
942
- const promoted = this.l1.importEntries(
943
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
944
- this.opts.forbiddenSnapshotPrefixes,
945
- );
946
- if (promoted > 0) {
947
- const l1Check = this.l1.get(k);
948
- if (l1Check !== null) {
949
- this.counters.diskHits++;
950
- this.opts.onHit?.(cacheKey, 'disk');
951
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
952
- span.setAttribute('cache.hit', 'disk').end();
953
- return l1Check.value as T;
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
+ }
954
1167
  }
955
1168
  }
956
1169
  }
@@ -1003,7 +1216,13 @@ export class CacheService {
1003
1216
  try {
1004
1217
  const client = await this.getRedis();
1005
1218
  const serialized = JSON.stringify(data);
1006
- const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
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
+ }
1007
1226
  await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
1008
1227
  this.cb.onSuccess();
1009
1228
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
@@ -1048,7 +1267,13 @@ export class CacheService {
1048
1267
  try {
1049
1268
  const client = await this.getRedis();
1050
1269
  const s = JSON.stringify(data);
1051
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
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
+ }
1052
1277
  await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
1053
1278
  } catch { /* ok */ }
1054
1279
  }
@@ -1097,7 +1322,13 @@ export class CacheService {
1097
1322
  try {
1098
1323
  const client = await this.getRedis();
1099
1324
  const s = JSON.stringify(data);
1100
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
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
+ }
1101
1332
  await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
1102
1333
  this.cb.onSuccess();
1103
1334
  } catch (err) {
@@ -1160,7 +1391,7 @@ export class CacheService {
1160
1391
  // A re-get in the narrow window before the deferred call fires would get an L1 miss
1161
1392
  // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
1162
1393
  // path already accepts).
1163
- setImmediate(() => this.disk.delete(k));
1394
+ setImmediate(() => { if (!this._diskDisabled) this.disk.delete(k); });
1164
1395
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
1165
1396
  this._cascadeDependencies(k);
1166
1397
  // Clean up: remove k from all dependency registrations (it is gone)
@@ -1171,13 +1402,7 @@ export class CacheService {
1171
1402
  try {
1172
1403
  const client = await this.getRedis();
1173
1404
  if (isPattern) {
1174
- const stream = client.scanStream({ match: k, count: 100 });
1175
- const keys: string[] = [];
1176
- await new Promise<void>((resolve, reject) => {
1177
- stream.on('data', (chunk: string[]) => keys.push(...chunk));
1178
- stream.on('end', resolve);
1179
- stream.on('error', reject);
1180
- });
1405
+ const keys = await this._scanKeys(client, k);
1181
1406
  if (keys.length > 0) await client.del(...keys);
1182
1407
  } else {
1183
1408
  await client.del(k);
@@ -1246,7 +1471,7 @@ export class CacheService {
1246
1471
  // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
1247
1472
  } else {
1248
1473
  this.l1.clear();
1249
- this.disk.clear();
1474
+ if (!this._diskDisabled) this.disk.clear();
1250
1475
  this._l1Counters.clear();
1251
1476
  this.tagIndex.clear();
1252
1477
  }
@@ -1255,13 +1480,7 @@ export class CacheService {
1255
1480
  try {
1256
1481
  const client = await this.getRedis();
1257
1482
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
1258
- const stream = client.scanStream({ match: pattern, count: 100 });
1259
- const keys: string[] = [];
1260
- await new Promise<void>((resolve, reject) => {
1261
- stream.on('data', (chunk: string[]) => keys.push(...chunk));
1262
- stream.on('end', resolve);
1263
- stream.on('error', reject);
1264
- });
1483
+ const keys = await this._scanKeys(client, pattern);
1265
1484
  if (keys.length > 0) await client.del(...keys);
1266
1485
  } catch (err) {
1267
1486
  this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
@@ -1514,14 +1733,8 @@ export class CacheService {
1514
1733
  const client = await this.getRedis();
1515
1734
  const nsPattern = this.nk(pattern);
1516
1735
 
1517
- // Collect all matching keys via SCAN
1518
- const matchedKeys: string[] = [];
1519
- const stream = client.scanStream({ match: nsPattern, count: 100 });
1520
- await new Promise<void>((resolve, reject) => {
1521
- stream.on('data', (chunk: string[]) => matchedKeys.push(...chunk));
1522
- stream.on('end', resolve);
1523
- stream.on('error', reject);
1524
- });
1736
+ // Collect all matching keys via SCAN (handles single-node and Cluster)
1737
+ const matchedKeys = await this._scanKeys(client, nsPattern);
1525
1738
 
1526
1739
  if (matchedKeys.length === 0) {
1527
1740
  this.cb.onSuccess();
@@ -1577,7 +1790,7 @@ export class CacheService {
1577
1790
  // Remove from L1 + disk
1578
1791
  for (const k of members) {
1579
1792
  this.l1.delete(k);
1580
- this.disk.delete(k);
1793
+ if (!this._diskDisabled) this.disk.delete(k);
1581
1794
  }
1582
1795
  this.tagIndex.delete(tagKey);
1583
1796
 
@@ -1814,7 +2027,7 @@ export class CacheService {
1814
2027
  for (const dep of dependents) {
1815
2028
  if (dep === deletedKey) continue; // no self-cascade
1816
2029
  this.l1.delete(dep);
1817
- this.disk.delete(dep);
2030
+ if (!this._diskDisabled) this.disk.delete(dep);
1818
2031
  void this.publishInvalidation('del', dep);
1819
2032
  this.logger.debug('Dependency cascade: invalidated dependent key', {
1820
2033
  trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
@@ -1887,7 +2100,7 @@ export class CacheService {
1887
2100
  sizeBytes: this.l1.memoryUsage,
1888
2101
  maxBytes: this.opts.l1MaxBytes,
1889
2102
  },
1890
- disk: this.disk.stats,
2103
+ disk: { ...this.disk.stats, disabled: this._diskDisabled },
1891
2104
  ...(this.latencyTracker && {
1892
2105
  adaptiveTtl: {
1893
2106
  enabled: true as const,
@@ -1977,6 +2190,10 @@ export class CacheService {
1977
2190
  process.off('SIGINT', this._shutdownHandler);
1978
2191
  this._shutdownHandler = null;
1979
2192
  }
2193
+ if (this._workerPool) {
2194
+ await this._workerPool.destroy();
2195
+ this._workerPool = null;
2196
+ }
1980
2197
  if (this.subClient) {
1981
2198
  try { await this.subClient.quit(); } catch { /* ok */ }
1982
2199
  this.subClient = null;
@@ -1985,7 +2202,7 @@ export class CacheService {
1985
2202
  try { await this.redis.disconnect(); } catch { /* ok */ }
1986
2203
  this.redis = null;
1987
2204
  }
1988
- this.disk.close();
2205
+ if (!this._diskDisabled) this.disk.close();
1989
2206
  }
1990
2207
 
1991
2208
  }