tricache 0.7.1 → 0.8.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.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
package/dist/index.d.ts CHANGED
@@ -1,5 +1,121 @@
1
- import { a as CategoryLimit, S as SmartCacheEntry, E as EvictionReason, I as ILogger, b as CacheHit, c as CachePriority, d as CacheEncryption, D as DiskCacheEntry } from './cache-service-D8tIXmzb.js';
2
- export { e as CacheMetrics, f as CacheOptions, g as CachePingResult, C as CacheService, h as EncryptionMode, i as ICacheBatchObservableCallback, j as ICacheCounter, k as ICacheMeter, l as ICacheObservableGauge, m as ICacheSpan, n as ICacheTracer, L as LockOptions, W as WrapOptions, o as consoleLogger } from './cache-service-D8tIXmzb.js';
1
+ export { C as CacheService, I as IIpcCacheProvider, a as IpcMetricsPayload, b as IpcTelemetryClient, c as IpcTelemetryServer, L as LatencyWatchdogOptions, d as LatencyWatchdogTelemetry, P as ProcessTerminationBus, T as TierLatencyWatchdog, e as deepMergeOptions, f as findActiveSockets, g as formatBytes, h as formatDuration, i as formatNumber, r as renderProgressBar, j as renderTopDashboard, k as resolveIpcSocketPath } from './cache-service-CyLdpo77.js';
2
+ import { i as IRemoteSnapshotAdapter, j as CategoryLimit, S as SmartCacheEntry, k as EvictionReason, h as ILogger, l as CacheHit, e as CachePriority, g as WTinyLfuStats$1, m as CacheEncryption, n as DiskCacheEntry, D as DiskBackpressureStats, o as IRedisDriver, p as IRedisPipeline } from './types-B6krw64X.js';
3
+ export { b as CacheHealthStatus, a as CacheMetrics, C as CacheOptions, f as CachePingResult, c as CachePresetType, d as CrossRegionInvalidationEvent, q as CrossRegionRelayOptions, E as EncryptionMode, r as EnvelopeEncryption, s as EnvelopeEncryptionOptions, H as HttpMeshRelayOptions, t as HttpSnapshotAdapterOptions, u as ICacheBatchObservableCallback, v as ICacheCounter, w as ICacheMeter, x as ICacheObservableGauge, y as ICacheSpan, z as ICacheSpanLink, I as ICacheTracer, A as ICrossRegionRelay, L as LockOptions, R as RemoteSnapshotOptions, B as WebhookRequestLike, F as WebhookResponseLike, W as WrapOptions, G as consoleLogger, J as createCrossRegionWebhookHandler, K as createCustomCrossRegionRelay, M as createCustomSnapshotAdapter, N as createHttpMeshRelay, O as createHttpSnapshotAdapter, P as createMemoryCrossRegionRelay, Q as createMemorySnapshotAdapter } from './types-B6krw64X.js';
4
+ export { B as BloomFilterStats, M as Murmur3BloomFilter, W as WasmBloomFilter, m as murmur3_32 } from './murmur3-CMGw9PbV.js';
5
+ import { EventEmitter } from 'node:events';
6
+ export { DashboardActionEvent, DashboardOptions, DashboardPeerInstance, StandaloneDashboardOptions, createNextDashboardHandlers, handleDashboardRequest, startDashboardServer, tricacheDashboard } from './dashboard/index.js';
7
+ import 'crypto';
8
+ import 'node:http';
9
+
10
+ /**
11
+ * tricache — Zero-Dependency AWS SigV4 Snapshot Adapter
12
+ *
13
+ * Provides a lightweight (~150 LOC) AWS SigV4 request signer built purely on the
14
+ * standard Web Crypto API (crypto.subtle) and global fetch.
15
+ *
16
+ * Allows stateless container pods (Kubernetes, AWS ECS, GCP Cloud Run) and Edge workers
17
+ * to persist and hydrate L1 snapshots directly to/from AWS S3, Cloudflare R2, MinIO,
18
+ * or custom S3-compatible object storage WITHOUT pulling in the 30MB @aws-sdk/client-s3.
19
+ */
20
+
21
+ interface SigV4SnapshotAdapterOptions {
22
+ /** S3 or Cloudflare R2 bucket name */
23
+ bucket: string;
24
+ /** Object key / filename for the snapshot (e.g. 'production-l1.snap') */
25
+ key: string;
26
+ /** AWS Region. Default: 'us-east-1' (use 'auto' for Cloudflare R2) */
27
+ region?: string;
28
+ /** Custom endpoint URL (e.g. 'https://<account_id>.r2.cloudflarestorage.com' or 'http://127.0.0.1:9000') */
29
+ endpoint?: string;
30
+ /** AWS Access Key ID. Defaults to process.env.AWS_ACCESS_KEY_ID */
31
+ accessKeyId?: string;
32
+ /** AWS Secret Access Key. Defaults to process.env.AWS_SECRET_ACCESS_KEY */
33
+ secretAccessKey?: string;
34
+ /** Optional AWS Session Token (for temporary IAM/STS credentials). Defaults to process.env.AWS_SESSION_TOKEN */
35
+ sessionToken?: string;
36
+ /** Force path-style URLs (e.g. https://endpoint/bucket/key). Default: true if endpoint is specified, false for AWS S3 */
37
+ forcePathStyle?: boolean;
38
+ /** Custom fetch implementation (defaults to globalThis.fetch) */
39
+ fetch?: typeof globalThis.fetch;
40
+ }
41
+ declare class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
42
+ private readonly bucket;
43
+ private readonly key;
44
+ private readonly region;
45
+ private readonly endpoint?;
46
+ private readonly accessKeyId;
47
+ private readonly secretAccessKey;
48
+ private readonly sessionToken?;
49
+ private readonly forcePathStyle;
50
+ private readonly fetchImpl;
51
+ constructor(options: SigV4SnapshotAdapterOptions);
52
+ private _resolveTarget;
53
+ private _buildHeaders;
54
+ get(): Promise<Buffer | null>;
55
+ put(data: Buffer): Promise<void>;
56
+ }
57
+ /**
58
+ * Creates a zero-dependency AWS SigV4 snapshot adapter for AWS S3, Cloudflare R2, MinIO, or custom gateways.
59
+ */
60
+ declare function createSigV4SnapshotAdapter(options: SigV4SnapshotAdapterOptions): IRemoteSnapshotAdapter;
61
+ /**
62
+ * Ergonomic alias for AWS S3 snapshot storage.
63
+ */
64
+ declare function createS3SnapshotAdapter(options: SigV4SnapshotAdapterOptions): IRemoteSnapshotAdapter;
65
+ /**
66
+ * Ergonomic alias for Cloudflare R2 snapshot storage using SigV4 REST credentials.
67
+ */
68
+ declare function createR2SnapshotAdapter(options: Omit<SigV4SnapshotAdapterOptions, 'region'> & {
69
+ region?: string;
70
+ accountId?: string;
71
+ }): IRemoteSnapshotAdapter;
72
+
73
+ /**
74
+ * Configuration options for the TriCache binary codec.
75
+ */
76
+ interface CacheCodecOptions {
77
+ /**
78
+ * When true (default), objects with a toJSON() method will have toJSON() invoked.
79
+ * When false (msgpackr 2.1.0+), the object's own internal properties are serialized directly,
80
+ * avoiding accidental HTTP response projections on durable cached state.
81
+ */
82
+ useToJSON?: boolean;
83
+ /**
84
+ * Enable msgpackr record structure extension (default: true).
85
+ * Generates compact record definitions that yield 30-50% smaller encodings for repeated object shapes.
86
+ */
87
+ useRecords?: boolean;
88
+ /**
89
+ * Enable serialization of additional built-in types (Map, Set, TypedArray, Error, RegExp).
90
+ * Default: true.
91
+ */
92
+ moreTypes?: boolean;
93
+ /**
94
+ * Decode MessagePack maps as plain JavaScript objects.
95
+ * Default: true (ensures plain JS objects and standard maps decode to plain objects).
96
+ */
97
+ mapsAsObjects?: boolean;
98
+ }
99
+ /**
100
+ * CacheCodec wraps msgpackr's Packr/Unpackr to provide unified, high-performance binary
101
+ * serialization across L1 in-memory buffers, L1.5 disk spill, and cold-start snapshots.
102
+ */
103
+ declare class CacheCodec {
104
+ private readonly packr;
105
+ constructor(options?: CacheCodecOptions);
106
+ /**
107
+ * Serializes a JavaScript value to a binary MessagePack Buffer.
108
+ */
109
+ encode(data: unknown): Buffer;
110
+ /**
111
+ * Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
112
+ */
113
+ decode<T = unknown>(data: Buffer | Uint8Array): T;
114
+ }
115
+ /**
116
+ * Default singleton codec configured for high-speed packing, record deduplication, and rich types.
117
+ */
118
+ declare const defaultCodec: CacheCodec;
3
119
 
4
120
  /**
5
121
  * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
@@ -24,15 +140,26 @@ interface SmartMemoryCacheOptions {
24
140
  logger: ILogger;
25
141
  /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
26
142
  evictionWatermark?: number;
143
+ /** Custom binary codec (defaults to defaultCodec with record structures and rich types enabled). */
144
+ codec?: CacheCodec;
145
+ /**
146
+ * Admission policy:
147
+ * - 'wtinylfu': Window TinyLFU segmented admission with mathematical scan resistance.
148
+ * - 'adaptive': Adaptive LFU x LRU x priority reservoir sampling.
149
+ * Default: 'adaptive' (unless explicitly set to 'wtinylfu')
150
+ */
151
+ admissionPolicy?: 'wtinylfu' | 'adaptive';
27
152
  }
28
153
  declare class SmartMemoryCache {
29
154
  private readonly cache;
30
155
  private readonly opts;
156
+ private readonly codec;
31
157
  private bloom;
32
158
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
33
159
  private readonly categoryPrefixes;
34
160
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
35
161
  private readonly sketch;
162
+ private readonly wtinyPolicy?;
36
163
  private totalSize;
37
164
  private categoryCount;
38
165
  private categorySize;
@@ -235,6 +362,198 @@ declare class SmartMemoryCache {
235
362
  hits: number;
236
363
  sizeBytes: number;
237
364
  }>;
365
+ /**
366
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
367
+ * Returns `undefined` when running under default adaptive eviction.
368
+ */
369
+ getWTinyLfuStats(): WTinyLfuStats$1 | undefined;
370
+ }
371
+
372
+ /**
373
+ * tricache — Native Window TinyLFU (W-TinyLFU) Admission Engine
374
+ *
375
+ * Implements the state-of-the-art W-TinyLFU cache architecture popularized by Caffeine:
376
+ *
377
+ * [Incoming Entry]
378
+ * │
379
+ * ▼
380
+ * ┌───────────────────────────┐
381
+ * │ Window Cache (LRU) │ ~1% of Total Capacity
382
+ * │ (Absorbs Burst Recency) │
383
+ * └─────────────┬─────────────┘
384
+ * │ Evicted from Window
385
+ * ▼
386
+ * [TinyLFU Admission]
387
+ * Freq(Candidate) > Freq(Victim)?
388
+ * │
389
+ * ┌───────────────┴───────────────┐
390
+ * │ YES │ NO
391
+ * ▼ ▼
392
+ * ┌──────────────────────┐ [Drop Candidate]
393
+ * │ Probationary SLRU │ ~20% of Main
394
+ * └──────────┬───────────┘
395
+ * │ On 2nd Hit
396
+ * ▼
397
+ * ┌──────────────────────┐
398
+ * │ Protected SLRU │ ~80% of Main
399
+ * └──────────────────────┘
400
+ *
401
+ * Characteristics:
402
+ * - Pure TypeScript with zero external dependencies
403
+ * - Mathematical scan resistance: large sequential scans never pollute the main cache
404
+ * - Burst recency absorption: short-lived temporal spikes hit in the Window without eviction churn
405
+ * - Near-optimal theoretical hit ratios on Zipfian distributions
406
+ */
407
+ interface WTinyLfuOptions {
408
+ /** Total maximum number of entries across all segments (Window + Probation + Protected). Default: 10,000 */
409
+ capacity: number;
410
+ /** Fraction of total capacity dedicated to Window Cache for burst recency absorption. Default: 0.01 (1%) */
411
+ windowPercent?: number;
412
+ /** Fraction of main SLRU space allocated to Protected segment. Default: 0.80 (80%) */
413
+ protectedPercent?: number;
414
+ /** Width of Count-Min Sketch rows (power of 2). Default: 1024 */
415
+ sketchWidth?: number;
416
+ }
417
+ interface WTinyLfuStats {
418
+ capacity: number;
419
+ size: number;
420
+ windowSize: number;
421
+ probationSize: number;
422
+ protectedSize: number;
423
+ hits: number;
424
+ misses: number;
425
+ hitRate: number;
426
+ admissions: number;
427
+ rejections: number;
428
+ demotions: number;
429
+ promotions: number;
430
+ }
431
+ interface EvictionResult<K, V> {
432
+ evicted?: {
433
+ key: K;
434
+ value: V;
435
+ segment: 'window' | 'probation' | 'protected';
436
+ };
437
+ rejected?: {
438
+ key: K;
439
+ value: V;
440
+ segment: 'window';
441
+ };
442
+ }
443
+ /**
444
+ * 4-row Count-Min Sketch for TinyLFU frequency estimation.
445
+ * Uses Murmur3-style bit-mixes of FNV-1a digests with periodic halving decay.
446
+ */
447
+ declare class TinyLfuSketch {
448
+ private readonly rows;
449
+ private readonly width;
450
+ private readonly mask;
451
+ private readonly table;
452
+ private insertions;
453
+ private readonly decayThreshold;
454
+ constructor(width?: number, decayThreshold?: number);
455
+ private hash;
456
+ increment(key: string): void;
457
+ estimate(key: string): number;
458
+ decay(): void;
459
+ clear(): void;
460
+ }
461
+ /**
462
+ * Window TinyLFU (W-TinyLFU) Segmented Cache.
463
+ */
464
+ declare class WTinyLfuCache<K = string, V = unknown> {
465
+ private readonly maxTotal;
466
+ private readonly maxWindow;
467
+ private readonly maxProtected;
468
+ private readonly maxProbation;
469
+ private readonly window;
470
+ private readonly probation;
471
+ private readonly protected_;
472
+ private readonly sketch;
473
+ private hitCount;
474
+ private missCount;
475
+ private admissionCount;
476
+ private rejectionCount;
477
+ private promotionCount;
478
+ private demotionCount;
479
+ constructor(options: WTinyLfuOptions);
480
+ get capacity(): number;
481
+ get size(): number;
482
+ private keyToString;
483
+ /**
484
+ * Retrieves an entry and performs W-TinyLFU access promotion.
485
+ */
486
+ get(key: K): V | undefined;
487
+ /**
488
+ * Returns true if key exists in any segment without updating access frequency.
489
+ */
490
+ has(key: K): boolean;
491
+ /**
492
+ * Puts an entry into the cache using W-TinyLFU admission policies.
493
+ */
494
+ set(key: K, value: V): EvictionResult<K, V>;
495
+ /**
496
+ * Removes a key from whichever segment it resides in.
497
+ */
498
+ delete(key: K): boolean;
499
+ /**
500
+ * Resets all segments, sketch, and metrics.
501
+ */
502
+ clear(): void;
503
+ /**
504
+ * Returns current telemetry and hit-ratio stats.
505
+ */
506
+ stats(): WTinyLfuStats;
507
+ getStats(): WTinyLfuStats;
508
+ /**
509
+ * Returns an iterator of all keys currently in the cache.
510
+ */
511
+ keys(): IterableIterator<K>;
512
+ /**
513
+ * Returns an iterator of all entries currently in the cache.
514
+ */
515
+ entries(): IterableIterator<[K, V]>;
516
+ /**
517
+ * Returns segment membership for a key ('window', 'probation', 'protected', or null).
518
+ */
519
+ getSegment(key: K): 'window' | 'probation' | 'protected' | null;
520
+ }
521
+ interface WTinyLfuAdmissionDecision {
522
+ admit: boolean;
523
+ evictKey?: string;
524
+ candidateKey?: string;
525
+ }
526
+ /**
527
+ * Lightweight W-TinyLFU policy controller for existing tiered caches like SmartMemoryCache.
528
+ */
529
+ declare class WTinyLfuPolicy {
530
+ private readonly sketch;
531
+ private readonly maxTotal;
532
+ private readonly maxWindow;
533
+ private readonly maxProtected;
534
+ private readonly maxProbation;
535
+ private readonly window;
536
+ private readonly probation;
537
+ private readonly protected_;
538
+ private hitCount;
539
+ private missCount;
540
+ private admissionCount;
541
+ private rejectionCount;
542
+ private promotionCount;
543
+ private demotionCount;
544
+ constructor(capacity: number, sketch: {
545
+ estimate(key: string): number;
546
+ increment(key: string): void;
547
+ }, windowPercent?: number, protectedPercent?: number);
548
+ get windowSize(): number;
549
+ get probationSize(): number;
550
+ get protectedSize(): number;
551
+ onAccess(key: string): void;
552
+ onSet(key: string, isUpdate: boolean): WTinyLfuAdmissionDecision;
553
+ onDelete(key: string): void;
554
+ clear(): void;
555
+ getStats(): WTinyLfuStats;
556
+ getSegment(key: string): 'window' | 'probation' | 'protected' | null;
238
557
  }
239
558
 
240
559
  type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
@@ -255,11 +574,50 @@ type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
255
574
  * Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
256
575
  */
257
576
 
577
+ /**
578
+ * BoundedDiskQueue — Concurrency-controlled write spooler with circuit breaking.
579
+ *
580
+ * Prevents libuv threadpool (UV_THREADPOOL_SIZE=4) starvation during cloud NVMe / EBS
581
+ * latency spikes (e.g. 450ms multi-tenant throttle) by limiting active async fs operations,
582
+ * bounding in-memory pending queues, and fast-shedding spills via a 3-state circuit breaker
583
+ * (CLOSED -> OPEN -> HALF-OPEN canary).
584
+ */
585
+ declare class BoundedDiskQueue {
586
+ private readonly maxConcurrent;
587
+ private readonly maxPending;
588
+ private readonly writeTimeoutMs;
589
+ private readonly failureThreshold;
590
+ private readonly cooldownMs;
591
+ private active;
592
+ private queue;
593
+ private spillsDropped;
594
+ private consecutiveFailures;
595
+ private circuitState;
596
+ private lastStateChangeMonotonic;
597
+ constructor(maxConcurrent?: number, maxPending?: number, writeTimeoutMs?: number, failureThreshold?: number, cooldownMs?: number);
598
+ schedule<T>(task: () => Promise<T>): Promise<T | null>;
599
+ getStats(): DiskBackpressureStats;
600
+ reset(): void;
601
+ }
602
+ /**
603
+ * Resolves the default directory for DiskTier storage.
604
+ *
605
+ * In Linux container environments, checks if `/dev/shm` (POSIX shared memory tmpfs)
606
+ * is writable and has adequate capacity (total >= 256MB AND free >= 128MB).
607
+ * When valid, targets `/dev/shm` to provide an off-heap, zero-GC RAM extension
608
+ * that runs at memory speeds (~20µs) and burns zero cloud/EBS IOPS.
609
+ * If capacity or free space is insufficient, or on non-Linux platforms,
610
+ * gracefully falls back to `os.tmpdir()`.
611
+ */
612
+ declare function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): {
613
+ dir: string;
614
+ isShm: boolean;
615
+ };
258
616
  interface DiskTierOptions {
259
617
  dir: string;
260
618
  maxBytes: number;
261
619
  entryMaxBytes: number;
262
- forbiddenPrefixes: readonly string[];
620
+ forbiddenPrefixes?: readonly string[];
263
621
  /** Mode-aware encryption instance. When set, disk files are encrypted with the
264
622
  * same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
265
623
  * When null, files are written unencrypted. Pass `cache.encryption` here. */
@@ -267,15 +625,30 @@ interface DiskTierOptions {
267
625
  compression?: CompressionAlgorithm;
268
626
  compressionThresholdBytes?: number;
269
627
  logger: ILogger;
628
+ codec?: CacheCodec;
629
+ diskMaxConcurrentWrites?: number;
630
+ diskMaxPendingWrites?: number;
631
+ diskWriteTimeoutMs?: number;
632
+ diskCircuitBreakerThreshold?: number;
633
+ diskCircuitBreakerCooldownMs?: number;
270
634
  }
271
635
  declare class DiskTier {
272
636
  private readonly opts;
637
+ private readonly codec;
638
+ private readonly diskQueue;
273
639
  private dirReady;
274
640
  private diskUsageBytes;
275
641
  private usageCounted;
276
642
  private fileCount;
277
643
  /** Next bucket index (0–255) for the staggered janitor wheel. */
278
644
  private _nextJanitorBucket;
645
+ private _isPruning;
646
+ private _pruneRounds;
647
+ private _entriesPruned;
648
+ private _spillsShedTotal;
649
+ private _hostVolumeLowSpace;
650
+ private _hostVolumeLowSpacePauses;
651
+ private _writeCounter;
279
652
  private _db;
280
653
  private _stmtInsert;
281
654
  private _stmtSelect;
@@ -283,6 +656,7 @@ declare class DiskTier {
283
656
  private _stmtExpire;
284
657
  private _stmtDelExp;
285
658
  private _stmtStats;
659
+ private _stmtPruneChunk;
286
660
  constructor(opts: DiskTierOptions);
287
661
  private ensureDir;
288
662
  /**
@@ -384,45 +758,188 @@ declare class DiskTier {
384
758
  purgeNextBucket(): number;
385
759
  /** Delete every file in the disk cache. Returns the count deleted. */
386
760
  clear(): number;
761
+ /**
762
+ * Proactively checks host volume free space via statfsSync.
763
+ * If free space on the volume drops below 10%, pauses spills to prevent
764
+ * Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
765
+ */
766
+ checkHostVolumeHealth(): boolean;
767
+ /**
768
+ * Non-blocking chunked pruning:
769
+ * Evicts oldest entries in 500-entry chunks down to 60% watermark,
770
+ * yielding to the event loop via setImmediate between chunks.
771
+ */
772
+ triggerChunkedPrune(): Promise<number>;
773
+ get isPruning(): boolean;
774
+ get hostVolumeLowSpace(): boolean;
775
+ get spillsShedTotal(): number;
776
+ getPruningStats(): {
777
+ active: boolean;
778
+ pruneRounds: number;
779
+ entriesPruned: number;
780
+ spillsShedTotal: number;
781
+ hostVolumeLowSpacePauses: number;
782
+ };
387
783
  get stats(): {
388
784
  files: number;
389
785
  sizeKB: number;
390
786
  maxKB: number;
787
+ backpressure?: DiskBackpressureStats;
788
+ pruning?: {
789
+ active: boolean;
790
+ pruneRounds: number;
791
+ entriesPruned: number;
792
+ spillsShedTotal: number;
793
+ hostVolumeLowSpacePauses: number;
794
+ };
391
795
  };
796
+ /** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
797
+ get backpressure(): BoundedDiskQueue;
392
798
  /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
393
799
  get indexMode(): 'sqlite' | 'file-only';
394
800
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
395
801
  close(): void;
396
802
  }
397
803
 
398
- declare class WasmBloomFilter {
399
- private readonly exports;
400
- private readonly mem;
401
- private readonly stagingTarget;
402
- private readonly encoder;
403
- private readonly numBits;
404
- /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
405
- private readonly _maxCapacity;
406
- /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
407
- private _insertionCount;
408
- constructor();
409
- private writeKey;
410
- add(key: string): void;
411
- mightContain(key: string): boolean;
412
- reset(): void;
413
- rebuild(keys: Iterable<string>): void;
804
+ /**
805
+ * Universal driver adapter wrapping `@redis/client` (node-redis) to satisfy TriCache's
806
+ * `IRedisDriver` contract without adding runtime dependencies.
807
+ */
808
+ declare class NodeRedisAdapter implements IRedisDriver {
809
+ readonly client: any;
810
+ constructor(client: any);
811
+ get isOpen(): boolean;
812
+ connect(): Promise<unknown>;
813
+ disconnect(): Promise<void>;
814
+ quit(): Promise<void>;
815
+ get(key: string): Promise<string | null>;
816
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
817
+ setex(key: string, seconds: number, value: string): Promise<unknown>;
818
+ del(...keys: string[]): Promise<number>;
819
+ ping(): Promise<string>;
820
+ expire(key: string, seconds: number): Promise<number | boolean>;
821
+ incr(key: string): Promise<number>;
822
+ eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
823
+ multi(): IRedisPipeline;
824
+ pipeline(): IRedisPipeline;
825
+ smembers(key: string): Promise<string[]>;
826
+ sadd(key: string, ...members: string[]): Promise<number>;
827
+ mget(keys: string[]): Promise<(string | null)[]>;
828
+ hset(key: string, value: Record<string, string>): Promise<unknown>;
829
+ publish(channel: string, message: string): Promise<number>;
830
+ subscribe(...channels: string[]): Promise<unknown>;
831
+ scanStream(options?: {
832
+ match?: string;
833
+ count?: number;
834
+ }): EventEmitter;
835
+ duplicate(): IRedisDriver;
836
+ on(event: string, listener: (...args: any[]) => void): this;
837
+ once(event: string, listener: (...args: any[]) => void): this;
838
+ }
839
+ /**
840
+ * Creates a pluggable `IRedisDriver` adapter wrapping an existing `@redis/client` instance.
841
+ *
842
+ * @example
843
+ * import { createClient } from 'redis';
844
+ * import { CacheService, createNodeRedisAdapter } from 'tricache';
845
+ *
846
+ * const client = createClient({ url: 'redis://localhost:6379' });
847
+ * await client.connect();
848
+ *
849
+ * const cache = CacheService.create({
850
+ * redisClient: createNodeRedisAdapter(client),
851
+ * });
852
+ */
853
+ declare function createNodeRedisAdapter(client: any): IRedisDriver;
854
+
855
+ interface AutoPipelinerOptions {
856
+ /** Maximum number of operations to coalesce before forcing an immediate pipeline dispatch. Default: 100 */
857
+ maxBatchSize?: number;
858
+ /** Whether auto-pipelining is enabled. Default: true */
859
+ enabled?: boolean;
860
+ }
861
+ /**
862
+ * AutoPipeliner — Microtask-coalesced Redis request batching.
863
+ *
864
+ * Automatically combines individual Redis commands dispatched during the same synchronous
865
+ * tick of the Node.js event loop into a single `pipeline()` network round-trip.
866
+ *
867
+ * Uses `queueMicrotask` exclusively (never `setImmediate` or timers) to ensure ZERO
868
+ * artificial latency penalty (0ms overhead) while slashing network syscalls under high concurrency.
869
+ */
870
+ declare class AutoPipeliner {
871
+ private readonly client;
872
+ readonly maxBatchSize: number;
873
+ enabled: boolean;
874
+ private queue;
875
+ private scheduled;
876
+ private inFlight;
877
+ private statsInternal;
878
+ constructor(client: IRedisDriver | any, options?: AutoPipelinerOptions);
414
879
  get stats(): {
415
- bitsSet: number;
416
- fillFactor: number;
880
+ batchesDispatched: number;
881
+ operationsBatched: number;
882
+ pendingQueueSize: number;
417
883
  };
418
- /** Number of add() calls since last reset/rebuild. */
419
- get insertions(): number;
420
- /**
421
- * Maximum safe insertions before false-positive rate exceeds ~1 %.
422
- * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
423
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
424
- */
425
- get maxCapacity(): number;
884
+ get(key: string): Promise<string | null>;
885
+ setex(key: string, seconds: number, value: string): Promise<void>;
886
+ del(...keys: string[]): Promise<number>;
887
+ private supportsPipelines;
888
+ private enqueue;
889
+ flush(): Promise<void>;
426
890
  }
427
891
 
428
- export { CacheEncryption, CacheHit, CachePriority, CategoryLimit, type CompressionAlgorithm, DiskCacheEntry, DiskTier, EvictionReason, ILogger, SmartCacheEntry, SmartMemoryCache, WasmBloomFilter };
892
+ /** Default safety ceiling for autonomous L1 memory allocations: 512 MB */
893
+ declare const DEFAULT_AUTONOMOUS_L1_CEILING_BYTES: number;
894
+ /** Minimum floor for autonomous L1 allocations: 16 MB */
895
+ declare const MIN_AUTONOMOUS_L1_FLOOR_BYTES: number;
896
+ /**
897
+ * Reads the container memory limit from Linux cgroups (v2 or v1).
898
+ *
899
+ * Defaults to `Infinity` when running outside Linux, when cgroup limits are unset ('max'),
900
+ * or when permission errors (EACCES / ENOENT) occur in hardened distroless environments.
901
+ */
902
+ declare function readCgroupMemoryLimit(): number;
903
+ /**
904
+ * Returns the V8 JavaScript heap size limit in bytes.
905
+ * Safely guards against missing or mock environments.
906
+ */
907
+ declare function getV8HeapLimit(): number;
908
+ interface AutonomousL1Options {
909
+ cgroupLimit?: number;
910
+ v8HeapLimit?: number;
911
+ defaultCeilingBytes?: number;
912
+ }
913
+ /**
914
+ * Computes an autonomous, safe memory bound for TriCache L1 RAM.
915
+ *
916
+ * Evaluates both the container cgroup limit (max 40% of container RAM)
917
+ * and the V8 heap limit (max 50% of V8 heap limit from --max-old-space-size),
918
+ * capped at a default 512MB ceiling.
919
+ */
920
+ declare function resolveAutonomousL1MaxBytes(options?: AutonomousL1Options): number;
921
+
922
+ /**
923
+ * Lightweight W3C TraceContext (traceparent) helpers for distributed context propagation.
924
+ *
925
+ * Implements W3C Trace Context Level 1:
926
+ * Format: {version}-{traceId}-{spanId}-{traceFlags}
927
+ * Example: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
928
+ */
929
+ interface ParsedTraceParent {
930
+ version: string;
931
+ traceId: string;
932
+ spanId: string;
933
+ traceFlags: number;
934
+ }
935
+ /**
936
+ * Parses a standard W3C traceparent header string into its components.
937
+ * Returns null if the header is malformed.
938
+ */
939
+ declare function parseTraceParent(header: string | undefined | null): ParsedTraceParent | null;
940
+ /**
941
+ * Formats trace components into a valid W3C traceparent header string.
942
+ */
943
+ declare function formatTraceParent(traceId: string, spanId: string, traceFlags?: number): string;
944
+
945
+ export { AutoPipeliner, type AutoPipelinerOptions, type AutonomousL1Options, CacheCodec, type CacheCodecOptions, CacheEncryption, CacheHit, CachePriority, CategoryLimit, type CompressionAlgorithm, DEFAULT_AUTONOMOUS_L1_CEILING_BYTES, DiskCacheEntry, DiskTier, EvictionReason, type EvictionResult, ILogger, IRedisDriver, IRedisPipeline, IRemoteSnapshotAdapter, MIN_AUTONOMOUS_L1_FLOOR_BYTES, NodeRedisAdapter, type ParsedTraceParent, SigV4SnapshotAdapter, type SigV4SnapshotAdapterOptions, SmartCacheEntry, SmartMemoryCache, TinyLfuSketch, WTinyLfuCache, type WTinyLfuOptions, WTinyLfuPolicy, type WTinyLfuStats, createNodeRedisAdapter, createR2SnapshotAdapter, createS3SnapshotAdapter, createSigV4SnapshotAdapter, defaultCodec, formatTraceParent, getV8HeapLimit, parseTraceParent, readCgroupMemoryLimit, resolveAutonomousL1MaxBytes, resolveDefaultDiskDir };