tricache 1.0.0 → 1.0.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 (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,1006 @@
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-CWI4jkS7.cjs';
2
+ import { j as IRemoteSnapshotAdapter, k as CategoryLimit, S as SmartCacheEntry, l as EvictionReason, i as ILogger, m as CacheHit, f as CachePriority, h as WTinyLfuStats$1, n as CacheEncryption, o as CompressionAlgorithm, p as DiskCacheEntry, D as DiskBackpressureStats, q as IRedisDriver, r as IRedisPipeline } from './types-BA4pz1A0.cjs';
3
+ export { c as CacheHealthStatus, b as CacheMetrics, C as CacheOptions, g as CachePingResult, d as CachePresetType, e as CrossRegionInvalidationEvent, s as CrossRegionRelayOptions, t as CustomCompressor, E as EncryptionMode, u as EnvelopeEncryption, v as EnvelopeEncryptionOptions, H as HttpMeshRelayOptions, w as HttpSnapshotAdapterOptions, x as ICacheBatchObservableCallback, y as ICacheCounter, z as ICacheMeter, A as ICacheObservableGauge, B as ICacheSpan, F as ICacheSpanLink, I as ICacheTracer, G as ICrossRegionRelay, a as InvalidateTagOptions, L as LockOptions, R as RemoteSnapshotOptions, J as WebhookRequestLike, K as WebhookResponseLike, W as WrapOptions, M as consoleLogger, N as createCrossRegionWebhookHandler, O as createCustomCrossRegionRelay, P as createCustomSnapshotAdapter, Q as createHttpMeshRelay, T as createHttpSnapshotAdapter, U as createMemoryCrossRegionRelay, V as createMemorySnapshotAdapter, X as initZstd } from './types-BA4pz1A0.cjs';
4
+ export { B as BloomFilterStats, M as Murmur3BloomFilter, W as WasmBloomFilter, m as murmur3_32 } from './murmur3-CMGw9PbV.cjs';
5
+ import { EventEmitter } from 'node:events';
6
+ export { DashboardActionEvent, DashboardOptions, DashboardPeerInstance, StandaloneDashboardOptions, createNextDashboardHandlers, handleDashboardRequest, startDashboardServer, tricacheDashboard } from './dashboard/index.cjs';
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;
119
+
120
+ /**
121
+ * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
122
+ *
123
+ * Features:
124
+ * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
125
+ * - msgpackr compression for entries ≥ 512 bytes
126
+ * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
127
+ * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
128
+ * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
129
+ * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
130
+ * - Periodic cleanup of hard-expired entries + bloom filter rebuild
131
+ * - Process-level singleton via globalThis (survives Next.js hot reloads)
132
+ */
133
+
134
+ interface SmartMemoryCacheOptions {
135
+ maxBytes: number;
136
+ maxEntries: number;
137
+ categories: Record<string, CategoryLimit>;
138
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
139
+ onEviction?: (key: string, reason: EvictionReason) => void;
140
+ logger: ILogger;
141
+ /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
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';
152
+ }
153
+ declare class SmartMemoryCache {
154
+ private readonly cache;
155
+ private readonly opts;
156
+ private readonly codec;
157
+ private bloom;
158
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
159
+ private readonly categoryPrefixes;
160
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
161
+ private readonly sketch;
162
+ private readonly wtinyPolicy?;
163
+ private totalSize;
164
+ private categoryCount;
165
+ private categorySize;
166
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
167
+ private categoryKeys;
168
+ private bloomChecks;
169
+ private bloomFalsePos;
170
+ private compressions;
171
+ private categoryHits;
172
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
173
+ private _bloomDirtyCount;
174
+ /**
175
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
176
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
177
+ * that is overwritten in-place rather than replaced with a new object literal.
178
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
179
+ * any other code can observe the pool state.
180
+ */
181
+ private readonly _evictPool;
182
+ private readonly _evictGPool;
183
+ constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
184
+ private recalculateStats;
185
+ private getCategory;
186
+ private getCategoryLimit;
187
+ private _delete;
188
+ private ensureCapacity;
189
+ private score;
190
+ /**
191
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
192
+ * saturated the filter past its ~1 % FP capacity.
193
+ *
194
+ * Trigger: (insertions − live entries) > maxCapacity
195
+ *
196
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
197
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
198
+ * cache holds more entries than the filter's rated capacity — which would
199
+ * stall the write path entirely.
200
+ *
201
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
202
+ */
203
+ private maybeRebuildBloom;
204
+ private smartEvict;
205
+ get(key: string): CacheHit | null;
206
+ set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number, tags?: string[], dependsOn?: string[]): boolean;
207
+ private storePacked;
208
+ delete(key: string): boolean;
209
+ private keysMatchingPattern;
210
+ deletePattern(pattern: string): number;
211
+ /** Flush all entries, or only those whose key starts with `prefix`. */
212
+ clear(prefix?: string): number;
213
+ /**
214
+ * Evict entries that violate current category or global limits.
215
+ * Returns the number of entries evicted.
216
+ */
217
+ rebalance(): number;
218
+ /**
219
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
220
+ * Only reflects L1 state — does not query Redis or disk.
221
+ */
222
+ ttl(key: string): number | null;
223
+ /**
224
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
225
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
226
+ * exceeds the configured threshold.
227
+ *
228
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
229
+ * @returns Number of entries evicted
230
+ */
231
+ evictPercentage(pct: number): number;
232
+ cleanup(): number;
233
+ /**
234
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
235
+ *
236
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
237
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
238
+ * Entries written before the disconnect started may have been invalidated by
239
+ * peers while the backplane was down; evicting them forces a controlled
240
+ * cold-start re-fetch from L2 rather than serving silently stale data.
241
+ *
242
+ * Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
243
+ * Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
244
+ * entries with neither field are treated as potentially stale and evicted conservatively.
245
+ *
246
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
247
+ * this time are evicted.
248
+ * @returns Number of entries evicted.
249
+ */
250
+ evictSetBefore(cutoffMs: number): number;
251
+ /**
252
+ * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
253
+ * Used for concurrency-safe compare-and-delete on stale generational reads,
254
+ * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
255
+ */
256
+ deleteIfSetBefore(key: string, cutoffMs: number): boolean;
257
+ exportEntries(forbiddenPrefixes: readonly string[]): Array<{
258
+ key: string;
259
+ entry: SmartCacheEntry;
260
+ }>;
261
+ importEntries(entries: Array<{
262
+ key: string;
263
+ entry: SmartCacheEntry;
264
+ }>, forbiddenPrefixes: readonly string[]): number;
265
+ /**
266
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
267
+ * Expired entries that are still in the Map (awaiting background cleanup)
268
+ * are silently skipped.
269
+ */
270
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
271
+ /**
272
+ * Non-generator bulk scan over all live entries.
273
+ *
274
+ * Faster than the generator-based iterators for bulk operations because:
275
+ * - No generator state-machine overhead (no yield/resume suspend points).
276
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
277
+ * - The same Map call-site is used by a single plain `for` loop instead of being
278
+ * shared across three competing generator functions, giving V8's IC a cleaner
279
+ * monomorphic profile for this path.
280
+ *
281
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
282
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
283
+ * key, avoiding the allocation entirely for callers that don't.
284
+ *
285
+ * @param fn Called once per live entry.
286
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
287
+ * Pass 0 when no namespace is configured.
288
+ */
289
+ scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
290
+ /**
291
+ * Yields only the keys of live entries — no intermediate tuple allocation.
292
+ * Use this instead of liveEntries() when you only need keys.
293
+ */
294
+ liveKeys(): Generator<string>;
295
+ /**
296
+ * Yields only the resolved values of live entries.
297
+ * Iterates Map.values() so the key is never loaded into the yielded path.
298
+ * Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
299
+ */
300
+ liveValues(): Generator<unknown>;
301
+ /**
302
+ * Returns the deserialized value for an entry, unpacking from the msgpackr buffer
303
+ * if the live object was not cached (large-entry optimisation or disk-restored entry).
304
+ */
305
+ resolveValue(entry: SmartCacheEntry): unknown;
306
+ get size(): number;
307
+ get memoryUsage(): number;
308
+ getStats(): {
309
+ entries: number;
310
+ sizeBytes: number;
311
+ sizeKB: number;
312
+ categories: Record<string, {
313
+ entries: number;
314
+ hits: number;
315
+ }>;
316
+ bloom: {
317
+ checks: number;
318
+ falsePositives: number;
319
+ };
320
+ compression: {
321
+ compressed: number;
322
+ uncompressed: number;
323
+ bytesSaved: number;
324
+ };
325
+ };
326
+ /**
327
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
328
+ * Does NOT count as a hit or perform SWR logic.
329
+ */
330
+ getEntry(key: string): SmartCacheEntry | undefined;
331
+ /**
332
+ * Return true if the key exists in L1 and has not expired.
333
+ * Uses the bloom filter as a fast negative check.
334
+ */
335
+ has(key: string): boolean;
336
+ /**
337
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
338
+ * @param newTtlMs - New TTL from now, in milliseconds.
339
+ */
340
+ touch(key: string, newTtlMs: number): boolean;
341
+ /**
342
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
343
+ * Returns `false` if the key is absent or already expired.
344
+ */
345
+ bumpExpiry(key: string, additionalMs: number): boolean;
346
+ bloomMightContain(key: string): boolean;
347
+ bloomStats(): {
348
+ bitsSet: number;
349
+ fillFactor: number;
350
+ } | {
351
+ bitsSet: number;
352
+ fillFactor: number;
353
+ };
354
+ /**
355
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
356
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
357
+ * Useful for diagnosing which keys are driving cache pressure.
358
+ *
359
+ * @param n - Maximum number of entries to return. Default: 10.
360
+ */
361
+ hotKeys(n: number): Array<{
362
+ key: string;
363
+ hits: number;
364
+ sizeBytes: number;
365
+ }>;
366
+ /**
367
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
368
+ * Returns `undefined` when running under default adaptive eviction.
369
+ */
370
+ getWTinyLfuStats(): WTinyLfuStats$1 | undefined;
371
+ }
372
+
373
+ /**
374
+ * tricache — Native Window TinyLFU (W-TinyLFU) Admission Engine
375
+ *
376
+ * Implements the state-of-the-art W-TinyLFU cache architecture popularized by Caffeine:
377
+ *
378
+ * [Incoming Entry]
379
+ * │
380
+ * ▼
381
+ * ┌───────────────────────────┐
382
+ * │ Window Cache (LRU) │ ~1% of Total Capacity
383
+ * │ (Absorbs Burst Recency) │
384
+ * └─────────────┬─────────────┘
385
+ * │ Evicted from Window
386
+ * ▼
387
+ * [TinyLFU Admission]
388
+ * Freq(Candidate) > Freq(Victim)?
389
+ * │
390
+ * ┌───────────────┴───────────────┐
391
+ * │ YES │ NO
392
+ * ▼ ▼
393
+ * ┌──────────────────────┐ [Drop Candidate]
394
+ * │ Probationary SLRU │ ~20% of Main
395
+ * └──────────┬───────────┘
396
+ * │ On 2nd Hit
397
+ * ▼
398
+ * ┌──────────────────────┐
399
+ * │ Protected SLRU │ ~80% of Main
400
+ * └──────────────────────┘
401
+ *
402
+ * Characteristics:
403
+ * - Pure TypeScript with zero external dependencies
404
+ * - Mathematical scan resistance: large sequential scans never pollute the main cache
405
+ * - Burst recency absorption: short-lived temporal spikes hit in the Window without eviction churn
406
+ * - Near-optimal theoretical hit ratios on Zipfian distributions
407
+ */
408
+ interface WTinyLfuOptions {
409
+ /** Total maximum number of entries across all segments (Window + Probation + Protected). Default: 10,000 */
410
+ capacity: number;
411
+ /** Fraction of total capacity dedicated to Window Cache for burst recency absorption. Default: 0.01 (1%) */
412
+ windowPercent?: number;
413
+ /** Fraction of main SLRU space allocated to Protected segment. Default: 0.80 (80%) */
414
+ protectedPercent?: number;
415
+ /** Width of Count-Min Sketch rows (power of 2). Default: 1024 */
416
+ sketchWidth?: number;
417
+ }
418
+ interface WTinyLfuStats {
419
+ capacity: number;
420
+ size: number;
421
+ windowSize: number;
422
+ probationSize: number;
423
+ protectedSize: number;
424
+ hits: number;
425
+ misses: number;
426
+ hitRate: number;
427
+ admissions: number;
428
+ rejections: number;
429
+ demotions: number;
430
+ promotions: number;
431
+ }
432
+ interface EvictionResult<K, V> {
433
+ evicted?: {
434
+ key: K;
435
+ value: V;
436
+ segment: 'window' | 'probation' | 'protected';
437
+ };
438
+ rejected?: {
439
+ key: K;
440
+ value: V;
441
+ segment: 'window';
442
+ };
443
+ }
444
+ /**
445
+ * 4-row Count-Min Sketch for TinyLFU frequency estimation.
446
+ * Uses Murmur3-style bit-mixes of FNV-1a digests with periodic halving decay.
447
+ */
448
+ declare class TinyLfuSketch {
449
+ private readonly rows;
450
+ private readonly width;
451
+ private readonly mask;
452
+ private readonly table;
453
+ private insertions;
454
+ private readonly decayThreshold;
455
+ constructor(width?: number, decayThreshold?: number);
456
+ private hash;
457
+ increment(key: string): void;
458
+ estimate(key: string): number;
459
+ decay(): void;
460
+ clear(): void;
461
+ }
462
+ /**
463
+ * Window TinyLFU (W-TinyLFU) Segmented Cache.
464
+ */
465
+ declare class WTinyLfuCache<K = string, V = unknown> {
466
+ private readonly maxTotal;
467
+ private readonly maxWindow;
468
+ private readonly maxProtected;
469
+ private readonly maxProbation;
470
+ private readonly window;
471
+ private readonly probation;
472
+ private readonly protected_;
473
+ private readonly sketch;
474
+ private hitCount;
475
+ private missCount;
476
+ private admissionCount;
477
+ private rejectionCount;
478
+ private promotionCount;
479
+ private demotionCount;
480
+ constructor(options: WTinyLfuOptions);
481
+ get capacity(): number;
482
+ get size(): number;
483
+ private keyToString;
484
+ /**
485
+ * Retrieves an entry and performs W-TinyLFU access promotion.
486
+ */
487
+ get(key: K): V | undefined;
488
+ /**
489
+ * Returns true if key exists in any segment without updating access frequency.
490
+ */
491
+ has(key: K): boolean;
492
+ /**
493
+ * Puts an entry into the cache using W-TinyLFU admission policies.
494
+ */
495
+ set(key: K, value: V): EvictionResult<K, V>;
496
+ /**
497
+ * Removes a key from whichever segment it resides in.
498
+ */
499
+ delete(key: K): boolean;
500
+ /**
501
+ * Resets all segments, sketch, and metrics.
502
+ */
503
+ clear(): void;
504
+ /**
505
+ * Returns current telemetry and hit-ratio stats.
506
+ */
507
+ stats(): WTinyLfuStats;
508
+ getStats(): WTinyLfuStats;
509
+ /**
510
+ * Returns an iterator of all keys currently in the cache.
511
+ */
512
+ keys(): IterableIterator<K>;
513
+ /**
514
+ * Returns an iterator of all entries currently in the cache.
515
+ */
516
+ entries(): IterableIterator<[K, V]>;
517
+ /**
518
+ * Returns segment membership for a key ('window', 'probation', 'protected', or null).
519
+ */
520
+ getSegment(key: K): 'window' | 'probation' | 'protected' | null;
521
+ }
522
+ interface WTinyLfuAdmissionDecision {
523
+ admit: boolean;
524
+ evictKey?: string;
525
+ candidateKey?: string;
526
+ }
527
+ /**
528
+ * Lightweight W-TinyLFU policy controller for existing tiered caches like SmartMemoryCache.
529
+ */
530
+ declare class WTinyLfuPolicy {
531
+ private readonly sketch;
532
+ private readonly canEvict?;
533
+ private readonly maxTotal;
534
+ private readonly maxWindow;
535
+ private readonly maxProtected;
536
+ private readonly maxProbation;
537
+ private readonly window;
538
+ private readonly probation;
539
+ private readonly protected_;
540
+ private hitCount;
541
+ private missCount;
542
+ private admissionCount;
543
+ private rejectionCount;
544
+ private promotionCount;
545
+ private demotionCount;
546
+ constructor(capacity: number, sketch: {
547
+ estimate(key: string): number;
548
+ increment(key: string): void;
549
+ }, windowPercent?: number, protectedPercent?: number, canEvict?: ((key: string) => boolean) | undefined);
550
+ get windowSize(): number;
551
+ get probationSize(): number;
552
+ get protectedSize(): number;
553
+ onAccess(key: string): void;
554
+ onSet(key: string, isUpdate: boolean): WTinyLfuAdmissionDecision;
555
+ onDelete(key: string): void;
556
+ clear(): void;
557
+ getStats(): WTinyLfuStats;
558
+ getSegment(key: string): 'window' | 'probation' | 'protected' | null;
559
+ }
560
+
561
+ /**
562
+ * DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
563
+ *
564
+ * When L1 evicts an entry it is spilled here instead of being discarded.
565
+ * On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
566
+ * vs 10–100 ms DB round-trip).
567
+ *
568
+ * Storage:
569
+ * - Directory: configurable (default os.tmpdir()/tricache-disk)
570
+ * - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
571
+ * - Format: msgpack({ version, key, entry, writtenAt })
572
+ * - Mode: 0o600 — owner read/write only
573
+ *
574
+ * Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
575
+ */
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
+ get isSaturated(): boolean;
599
+ private releaseSlot;
600
+ schedule<T>(task: () => Promise<T>): Promise<T | null>;
601
+ getStats(): DiskBackpressureStats;
602
+ reset(): void;
603
+ }
604
+ /**
605
+ * Resolves the default directory for DiskTier storage.
606
+ *
607
+ * In Linux container environments, checks if `/dev/shm` (POSIX shared memory tmpfs)
608
+ * is writable and has adequate capacity (total >= 256MB AND free >= 128MB).
609
+ * When valid, targets `/dev/shm` to provide an off-heap, zero-GC RAM extension
610
+ * that runs at memory speeds (~20µs) and burns zero cloud/EBS IOPS.
611
+ * If capacity or free space is insufficient, or on non-Linux platforms,
612
+ * gracefully falls back to `os.tmpdir()`.
613
+ */
614
+ declare function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): {
615
+ dir: string;
616
+ isShm: boolean;
617
+ };
618
+ interface DiskTierOptions {
619
+ dir: string;
620
+ maxBytes: number;
621
+ entryMaxBytes: number;
622
+ forbiddenPrefixes?: readonly string[];
623
+ /** Mode-aware encryption instance. When set, disk files are encrypted with the
624
+ * same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
625
+ * When null, files are written unencrypted. Pass `cache.encryption` here. */
626
+ encryption?: CacheEncryption | null;
627
+ compression?: CompressionAlgorithm;
628
+ compressionThresholdBytes?: number;
629
+ logger: ILogger;
630
+ codec?: CacheCodec;
631
+ diskMaxConcurrentWrites?: number;
632
+ diskMaxPendingWrites?: number;
633
+ diskWriteTimeoutMs?: number;
634
+ diskCircuitBreakerThreshold?: number;
635
+ diskCircuitBreakerCooldownMs?: number;
636
+ }
637
+ declare class DiskTier {
638
+ private readonly opts;
639
+ private readonly codec;
640
+ private readonly diskQueue;
641
+ private dirReady;
642
+ private diskUsageBytes;
643
+ private usageCounted;
644
+ private fileCount;
645
+ private reservedBytes;
646
+ private reservedFiles;
647
+ private saveSequence;
648
+ private epoch;
649
+ private readonly pendingSaves;
650
+ private closed;
651
+ private readonly invalidatedKeys;
652
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
653
+ private _nextJanitorBucket;
654
+ private _isPruning;
655
+ private _pruneRounds;
656
+ private _entriesPruned;
657
+ private _spillsShedTotal;
658
+ private _hostVolumeLowSpace;
659
+ private _hostVolumeLowSpacePauses;
660
+ private _writeCounter;
661
+ private _db;
662
+ private _stmtInsert;
663
+ private _stmtSelect;
664
+ private _stmtDelete;
665
+ private _stmtExpire;
666
+ private _stmtDelExp;
667
+ private _stmtStats;
668
+ private _stmtPruneChunk;
669
+ constructor(opts: DiskTierOptions);
670
+ private ensureDir;
671
+ /**
672
+ * Initialise the SQLite metadata index. Called once after the cache directory
673
+ * is confirmed to exist. On any failure the instance silently falls back to
674
+ * file-only mode — all public methods handle `this._db === null`.
675
+ *
676
+ * Schema:
677
+ * meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
678
+ * idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
679
+ *
680
+ * WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
681
+ * most one WAL frame — acceptable data loss for an L1.5 spill store).
682
+ */
683
+ private _initSqlite;
684
+ private ensureUsageCounted;
685
+ /**
686
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
687
+ * Kept separate from path construction so callers can find files by prefix
688
+ * without knowing which filename generation was used when the file was written.
689
+ */
690
+ private keyToHash;
691
+ /**
692
+ * Build the write path for a NEW file (V3 generation).
693
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
694
+ * with zero file I/O — after readdirSync() it only needs a string parse.
695
+ *
696
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
697
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
698
+ *
699
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
700
+ */
701
+ private hashToWritePath;
702
+ private findFilePaths;
703
+ private fileWrittenAt;
704
+ /**
705
+ * Find the on-disk file for a key hash, handling all filename generations:
706
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
707
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
708
+ * Returns null when the bucket dir does not exist or the key is absent.
709
+ */
710
+ private findFilePath;
711
+ private removeFile;
712
+ /**
713
+ * Recursively list all cache file paths across the 2-level sharded subdirs.
714
+ * Top-level entries that are not directories are skipped (e.g. stale flat
715
+ * files written by older versions).
716
+ */
717
+ private walkCacheFiles;
718
+ private isForbidden;
719
+ private encrypt;
720
+ private decrypt;
721
+ /**
722
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
723
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
724
+ * Returns the buffer unchanged when no encryption instance is configured.
725
+ */
726
+ private encryptV2;
727
+ /**
728
+ * V2 decryption — inner payload after stripping the 16-byte header.
729
+ * When an encryption instance is configured the format is the mode-aware
730
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
731
+ * without one the payload is raw msgpack.
732
+ */
733
+ private decryptV2;
734
+ /**
735
+ * Spill an evicted L1 entry to disk.
736
+ *
737
+ * Returns a Promise that resolves when the file is durably written. Callers
738
+ * that treat the spill as fire-and-forget should do:
739
+ * `void disk.save(key, entry)`
740
+ *
741
+ * Implementation notes:
742
+ * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
743
+ * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
744
+ * on any external resource.
745
+ * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
746
+ * so the Node.js event loop is never stalled waiting for disk I/O.
747
+ */
748
+ save(key: string, entry: DiskCacheEntry): Promise<void>;
749
+ /** Load a key from disk, or return null on miss/expiry/corruption. */
750
+ load(key: string): DiskCacheEntry | null;
751
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
752
+ invalidate(key: string): void;
753
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
754
+ delete(key: string, invalidatedOnly?: boolean): void;
755
+ /** Purge all expired entries. Returns number deleted. */
756
+ purgeExpired(): number;
757
+ /**
758
+ * Purge expired entries. Two modes depending on availability of SQLite:
759
+ *
760
+ * SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
761
+ * One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
762
+ * wheel. All expired entries are found and deleted in a single pass — the
763
+ * 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
764
+ * incremented so tests that inspect the counter continue to work.
765
+ *
766
+ * File-only fallback:
767
+ * Original staggered bucket wheel — purges exactly one of 256 subdirectory
768
+ * buckets per call, spreading the O(fileCount) work across 256 ticks.
769
+ *
770
+ * Returns the number of entries deleted in this tick.
771
+ */
772
+ purgeNextBucket(): number;
773
+ /** Delete every file in the disk cache. Returns the count deleted. */
774
+ clear(): number;
775
+ /**
776
+ * Proactively checks host volume free space via statfsSync.
777
+ * If free space on the volume drops below 10%, pauses spills to prevent
778
+ * Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
779
+ */
780
+ checkHostVolumeHealth(): boolean;
781
+ /**
782
+ * Non-blocking chunked pruning:
783
+ * Evicts oldest entries in 500-entry chunks down to 60% watermark,
784
+ * yielding to the event loop via setImmediate between chunks.
785
+ */
786
+ triggerChunkedPrune(): Promise<number>;
787
+ get isPruning(): boolean;
788
+ get hostVolumeLowSpace(): boolean;
789
+ get spillsShedTotal(): number;
790
+ getPruningStats(): {
791
+ active: boolean;
792
+ pruneRounds: number;
793
+ entriesPruned: number;
794
+ spillsShedTotal: number;
795
+ hostVolumeLowSpacePauses: number;
796
+ };
797
+ get stats(): {
798
+ files: number;
799
+ sizeKB: number;
800
+ maxKB: number;
801
+ backpressure?: DiskBackpressureStats;
802
+ pruning?: {
803
+ active: boolean;
804
+ pruneRounds: number;
805
+ entriesPruned: number;
806
+ spillsShedTotal: number;
807
+ hostVolumeLowSpacePauses: number;
808
+ };
809
+ };
810
+ /** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
811
+ get backpressure(): BoundedDiskQueue;
812
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
813
+ get indexMode(): 'sqlite' | 'file-only';
814
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
815
+ close(): void;
816
+ }
817
+
818
+ /**
819
+ * Universal driver adapter wrapping `@redis/client` (node-redis) to satisfy TriCache's
820
+ * `IRedisDriver` contract without adding runtime dependencies.
821
+ */
822
+ declare class NodeRedisAdapter extends EventEmitter implements IRedisDriver {
823
+ readonly client: any;
824
+ private connecting;
825
+ pttl?: (key: string) => Promise<number>;
826
+ constructor(client: any);
827
+ get isOpen(): boolean;
828
+ connect(): Promise<unknown>;
829
+ disconnect(): Promise<void>;
830
+ quit(): Promise<void>;
831
+ get(key: string): Promise<string | null>;
832
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
833
+ setex(key: string, seconds: number, value: string): Promise<unknown>;
834
+ del(...keys: string[]): Promise<number>;
835
+ ping(): Promise<string>;
836
+ expire(key: string, seconds: number): Promise<number | boolean>;
837
+ incr(key: string): Promise<number>;
838
+ eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
839
+ multi(): IRedisPipeline;
840
+ pipeline(): IRedisPipeline;
841
+ smembers(key: string): Promise<string[]>;
842
+ sadd(key: string, ...members: string[]): Promise<number>;
843
+ mget(keys: string[]): Promise<(string | null)[]>;
844
+ hset(key: string, value: Record<string, string>): Promise<unknown>;
845
+ hgetall(key: string): Promise<Record<string, string>>;
846
+ publish(channel: string, message: string): Promise<number>;
847
+ subscribe(...channels: string[]): Promise<unknown>;
848
+ unsubscribe(...channels: string[]): Promise<unknown>;
849
+ xread(...args: (string | number)[]): Promise<Array<[string, Array<[string, string[]]>]> | null>;
850
+ xadd(...args: (string | number)[]): Promise<unknown>;
851
+ xrange(...args: (string | number)[]): Promise<Array<[string, string[]]>>;
852
+ xrevrange(...args: (string | number)[]): Promise<Array<[string, string[]]>>;
853
+ scanStream(options?: {
854
+ match?: string;
855
+ count?: number;
856
+ }): EventEmitter;
857
+ duplicate(): IRedisDriver;
858
+ on(event: string, listener: (...args: any[]) => void): this;
859
+ once(event: string, listener: (...args: any[]) => void): this;
860
+ removeListener(event: string, listener: (...args: any[]) => void): this;
861
+ }
862
+ /**
863
+ * Creates a pluggable `IRedisDriver` adapter wrapping an existing `@redis/client` instance.
864
+ *
865
+ * @example
866
+ * import { createClient } from 'redis';
867
+ * import { CacheService, createNodeRedisAdapter } from 'tricache';
868
+ *
869
+ * const client = createClient({ url: 'redis://localhost:6379' });
870
+ * await client.connect();
871
+ *
872
+ * const cache = CacheService.create({
873
+ * redisClient: createNodeRedisAdapter(client),
874
+ * });
875
+ */
876
+ declare function createNodeRedisAdapter(client: any): IRedisDriver;
877
+
878
+ interface AutoPipelinerOptions {
879
+ /** Maximum number of operations to coalesce before forcing an immediate pipeline dispatch. Default: 100 */
880
+ maxBatchSize?: number;
881
+ /** Whether auto-pipelining is enabled. Default: true */
882
+ enabled?: boolean;
883
+ }
884
+ interface TimedRedisValue {
885
+ raw: string | Record<string, string> | null;
886
+ ttlMs?: number;
887
+ }
888
+ /**
889
+ * AutoPipeliner — Microtask-coalesced Redis request batching.
890
+ *
891
+ * Automatically combines individual Redis commands dispatched during the same synchronous
892
+ * tick of the Node.js event loop into a single `pipeline()` network round-trip.
893
+ *
894
+ * Uses `queueMicrotask` exclusively (never `setImmediate` or timers) to ensure ZERO
895
+ * artificial latency penalty (0ms overhead) while slashing network syscalls under high concurrency.
896
+ */
897
+ declare class AutoPipeliner {
898
+ private readonly client;
899
+ readonly maxBatchSize: number;
900
+ enabled: boolean;
901
+ private queue;
902
+ private scheduled;
903
+ private inFlight;
904
+ private statsInternal;
905
+ constructor(client: IRedisDriver | any, options?: AutoPipelinerOptions);
906
+ get stats(): {
907
+ batchesDispatched: number;
908
+ operationsBatched: number;
909
+ pendingQueueSize: number;
910
+ };
911
+ get(key: string): Promise<string | null>;
912
+ read(key: string, hash?: boolean): Promise<TimedRedisValue>;
913
+ setex(key: string, seconds: number, value: string): Promise<void>;
914
+ setpx(key: string, milliseconds: number, value: string): Promise<void>;
915
+ del(...keys: string[]): Promise<number>;
916
+ private supportsPipelines;
917
+ private enqueue;
918
+ flush(): Promise<void>;
919
+ private dispatch;
920
+ }
921
+
922
+ /** Default safety ceiling for autonomous L1 memory allocations: 512 MB */
923
+ declare const DEFAULT_AUTONOMOUS_L1_CEILING_BYTES: number;
924
+ /** Minimum floor for autonomous L1 allocations: 16 MB */
925
+ declare const MIN_AUTONOMOUS_L1_FLOOR_BYTES: number;
926
+ /**
927
+ * Reads the container memory limit from Linux cgroups (v2 or v1).
928
+ *
929
+ * Defaults to `Infinity` when running outside Linux, when cgroup limits are unset ('max'),
930
+ * or when permission errors (EACCES / ENOENT) occur in hardened distroless environments.
931
+ */
932
+ declare function readCgroupMemoryLimit(): number;
933
+ /**
934
+ * Returns the V8 JavaScript heap size limit in bytes.
935
+ * Safely guards against missing or mock environments.
936
+ */
937
+ declare function getV8HeapLimit(): number;
938
+ interface AutonomousL1Options {
939
+ cgroupLimit?: number;
940
+ v8HeapLimit?: number;
941
+ defaultCeilingBytes?: number;
942
+ }
943
+ /**
944
+ * Computes an autonomous, safe memory bound for TriCache L1 RAM.
945
+ *
946
+ * Evaluates both the container cgroup limit (max 40% of container RAM)
947
+ * and the V8 heap limit (max 50% of V8 heap limit from --max-old-space-size),
948
+ * capped at a default 512MB ceiling.
949
+ */
950
+ declare function resolveAutonomousL1MaxBytes(options?: AutonomousL1Options): number;
951
+
952
+ /**
953
+ * Lightweight W3C TraceContext (traceparent) helpers for distributed context propagation.
954
+ *
955
+ * Implements W3C Trace Context Level 1:
956
+ * Format: {version}-{traceId}-{spanId}-{traceFlags}
957
+ * Example: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
958
+ */
959
+ interface ParsedTraceParent {
960
+ version: string;
961
+ traceId: string;
962
+ spanId: string;
963
+ traceFlags: number;
964
+ }
965
+ /**
966
+ * Parses a standard W3C traceparent header string into its components.
967
+ * Returns null if the header is malformed.
968
+ */
969
+ declare function parseTraceParent(header: string | undefined | null): ParsedTraceParent | null;
970
+ /**
971
+ * Formats trace components into a valid W3C traceparent header string.
972
+ */
973
+ declare function formatTraceParent(traceId: string, spanId: string, traceFlags?: number): string;
974
+
975
+ /**
976
+ * Utilities for wildcard matching and hierarchical cascading of cache tags.
977
+ */
978
+ /**
979
+ * Returns true if the given tag contains glob wildcard characters ('*' or '?').
980
+ */
981
+ declare function isWildcardTag(tag: string): boolean;
982
+ /**
983
+ * Matches a tag name against a pattern supporting '*' (0 or more chars) and '?' (single char).
984
+ * Optimized with fast-paths for exact match, universal wildcard, and single prefix/suffix wildcards.
985
+ */
986
+ declare function matchesTagPattern(pattern: string, tag: string): boolean;
987
+ /**
988
+ * Determines whether `candidateTag` is either identical to `parentTag`
989
+ * or a child descendant in the hierarchy separated by `delimiter`.
990
+ *
991
+ * Example:
992
+ * isChildTag('org:123', 'org:123', ':') -> true
993
+ * isChildTag('org:123', 'org:123:dept', ':') -> true
994
+ * isChildTag('org:123', 'org:1234', ':') -> false (must match delimiter boundary)
995
+ */
996
+ declare function isChildTag(parentTag: string, candidateTag: string, delimiter?: string): boolean;
997
+ /**
998
+ * Expands hierarchical tags into all ancestor namespace levels.
999
+ *
1000
+ * Example:
1001
+ * expandHierarchicalTags(['org:123:dept:456', 'role:admin'], ':')
1002
+ * => ['org', 'org:123', 'org:123:dept', 'org:123:dept:456', 'role', 'role:admin']
1003
+ */
1004
+ declare function expandHierarchicalTags(tags: string[], delimiter?: string): string[];
1005
+
1006
+ export { AutoPipeliner, type AutoPipelinerOptions, type AutonomousL1Options, CacheCodec, type CacheCodecOptions, CacheEncryption, CacheHit, CachePriority, CategoryLimit, 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, expandHierarchicalTags, formatTraceParent, getV8HeapLimit, isChildTag, isWildcardTag, matchesTagPattern, parseTraceParent, readCgroupMemoryLimit, resolveAutonomousL1MaxBytes, resolveDefaultDiskDir };