tricache 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +284 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +315 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
import { C as CacheOptions, a as CacheMetrics, b as CacheHealthStatus, c as CachePresetType, d as CrossRegionInvalidationEvent, e as CachePriority, W as WrapOptions, f as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, g as WTinyLfuStats } from './types-B_QkVwJ7.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
|
|
5
|
+
*
|
|
6
|
+
* Prevents EBS/cloud NVMe latency degradation from impacting application p95 response times.
|
|
7
|
+
* Incorporates control-theory safeguards:
|
|
8
|
+
* - Amortized zero-allocation p95 calculation (fires every 32 samples on pre-allocated typed arrays).
|
|
9
|
+
* - Graduated probabilistic shedding (Stage 0: 0% -> Stage 1: 25% -> Stage 2: 75% -> Stage 3: 100%).
|
|
10
|
+
* - Asymmetric hysteresis on Redis circuit (cuts diversion at 15ms, requires recovery below 10ms).
|
|
11
|
+
* - Anti-synchronicity cooldown jitter (±30%) to eliminate fleet-wide failover shockwaves.
|
|
12
|
+
* - Single-canary half-open recovery probing.
|
|
13
|
+
*/
|
|
14
|
+
interface LatencyWatchdogOptions {
|
|
15
|
+
enabled?: boolean;
|
|
16
|
+
minDiskBypassMs?: number;
|
|
17
|
+
bypassRatio?: number;
|
|
18
|
+
cooldownMs?: number;
|
|
19
|
+
redisCutoffMs?: number;
|
|
20
|
+
redisRecoveryFloorMs?: number;
|
|
21
|
+
minSamples?: number;
|
|
22
|
+
disableRedis?: boolean;
|
|
23
|
+
}
|
|
24
|
+
interface LatencyWatchdogTelemetry {
|
|
25
|
+
bypassActive: boolean;
|
|
26
|
+
bypassStage: 0 | 1 | 2 | 3;
|
|
27
|
+
diskP95Ms: number;
|
|
28
|
+
redisP95Ms: number;
|
|
29
|
+
redisDampened: boolean;
|
|
30
|
+
bypassedTotal: number;
|
|
31
|
+
}
|
|
32
|
+
declare class TierLatencyWatchdog {
|
|
33
|
+
private readonly enabled;
|
|
34
|
+
private readonly minDiskBypassMs;
|
|
35
|
+
private readonly bypassRatio;
|
|
36
|
+
private readonly cooldownMs;
|
|
37
|
+
private readonly redisCutoffMs;
|
|
38
|
+
private readonly redisRecoveryFloorMs;
|
|
39
|
+
private readonly minSamples;
|
|
40
|
+
private disableRedis;
|
|
41
|
+
private readonly diskRing;
|
|
42
|
+
private readonly redisRing;
|
|
43
|
+
private readonly scratch;
|
|
44
|
+
private diskIdx;
|
|
45
|
+
private redisIdx;
|
|
46
|
+
private diskCount;
|
|
47
|
+
private redisCount;
|
|
48
|
+
private cachedDiskP95;
|
|
49
|
+
private cachedRedisP95;
|
|
50
|
+
private stage;
|
|
51
|
+
private redisDampened;
|
|
52
|
+
private redisRecoveryConsecutiveSamples;
|
|
53
|
+
private bypassedUntilMonotonic;
|
|
54
|
+
private canaryInFlight;
|
|
55
|
+
private bypassedTotal;
|
|
56
|
+
constructor(options?: LatencyWatchdogOptions);
|
|
57
|
+
setDisableRedis(disabled: boolean): void;
|
|
58
|
+
/**
|
|
59
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
60
|
+
*/
|
|
61
|
+
recordDisk(ms: number): void;
|
|
62
|
+
/**
|
|
63
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
64
|
+
*/
|
|
65
|
+
recordRedis(ms: number): void;
|
|
66
|
+
private recalculateP95;
|
|
67
|
+
private computeP95;
|
|
68
|
+
/**
|
|
69
|
+
* Core Control Loop:
|
|
70
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
71
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
72
|
+
*/
|
|
73
|
+
private evaluateControlLoop;
|
|
74
|
+
private calculateJitteredCooldown;
|
|
75
|
+
/**
|
|
76
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
77
|
+
*
|
|
78
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
79
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
80
|
+
*
|
|
81
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
82
|
+
*/
|
|
83
|
+
isDiskAllowed(randomOverride?: number): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Callback invoked when the single canary read probe completes.
|
|
86
|
+
*/
|
|
87
|
+
onCanaryResult(success: boolean, elapsedMs: number): void;
|
|
88
|
+
getTelemetry(): LatencyWatchdogTelemetry;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Platform-agnostic IPC socket / named pipe path resolver.
|
|
93
|
+
* - POSIX: `/tmp/tricache-<id>.sock` (or `$TMPDIR/tricache-<id>.sock`)
|
|
94
|
+
* - Windows: `\\.\pipe\tricache-<id>`
|
|
95
|
+
*/
|
|
96
|
+
declare function resolveIpcSocketPath(id?: string | number): string;
|
|
97
|
+
/**
|
|
98
|
+
* Cache provider interface required by the IPC telemetry server.
|
|
99
|
+
*/
|
|
100
|
+
interface IIpcCacheProvider {
|
|
101
|
+
options?: CacheOptions;
|
|
102
|
+
metrics(): CacheMetrics;
|
|
103
|
+
stats?(): {
|
|
104
|
+
l1: Record<string, unknown>;
|
|
105
|
+
disk: Record<string, unknown>;
|
|
106
|
+
};
|
|
107
|
+
hotKeys?(n?: number): Array<{
|
|
108
|
+
key: string;
|
|
109
|
+
hits: number;
|
|
110
|
+
sizeBytes: number;
|
|
111
|
+
}>;
|
|
112
|
+
health?(): CacheHealthStatus;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Serialized telemetry payload transferred across the IPC bridge.
|
|
116
|
+
*/
|
|
117
|
+
interface IpcMetricsPayload {
|
|
118
|
+
pid: number;
|
|
119
|
+
uptimeMs: number;
|
|
120
|
+
timestamp: number;
|
|
121
|
+
namespace?: string;
|
|
122
|
+
l1MaxBytes?: number;
|
|
123
|
+
metrics: CacheMetrics;
|
|
124
|
+
stats?: {
|
|
125
|
+
l1: Record<string, unknown>;
|
|
126
|
+
disk: Record<string, unknown>;
|
|
127
|
+
};
|
|
128
|
+
hotKeys?: Array<{
|
|
129
|
+
key: string;
|
|
130
|
+
hits: number;
|
|
131
|
+
sizeBytes: number;
|
|
132
|
+
}>;
|
|
133
|
+
health?: CacheHealthStatus;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Lightweight, non-blocking IPC Telemetry Server.
|
|
137
|
+
* Exposes real-time cache metrics over Unix domain sockets (POSIX) or Named Pipes (Windows).
|
|
138
|
+
*/
|
|
139
|
+
declare class IpcTelemetryServer {
|
|
140
|
+
private readonly cache;
|
|
141
|
+
private server;
|
|
142
|
+
readonly socketPath: string;
|
|
143
|
+
private _closed;
|
|
144
|
+
private _exitHandler;
|
|
145
|
+
private _sigintHandler;
|
|
146
|
+
private _sigtermHandler;
|
|
147
|
+
constructor(cache: IIpcCacheProvider, customSocketPath?: string);
|
|
148
|
+
/**
|
|
149
|
+
* Start listening on the IPC socket / pipe.
|
|
150
|
+
*/
|
|
151
|
+
start(): Promise<void>;
|
|
152
|
+
/**
|
|
153
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
154
|
+
*/
|
|
155
|
+
getSnapshot(): IpcMetricsPayload;
|
|
156
|
+
private _unlinkSocket;
|
|
157
|
+
/**
|
|
158
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
159
|
+
*/
|
|
160
|
+
close(): Promise<void>;
|
|
161
|
+
get isListening(): boolean;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* IPC Telemetry Client for connecting to and querying a running TriCache instance.
|
|
165
|
+
*/
|
|
166
|
+
declare class IpcTelemetryClient {
|
|
167
|
+
readonly socketPath: string;
|
|
168
|
+
constructor(socketPath?: string);
|
|
169
|
+
/**
|
|
170
|
+
* Fetch a live metrics snapshot from the IPC server.
|
|
171
|
+
*/
|
|
172
|
+
getMetrics(timeoutMs?: number): Promise<IpcMetricsPayload>;
|
|
173
|
+
/**
|
|
174
|
+
* Send a ping over the IPC bridge and measure round-trip latency.
|
|
175
|
+
*/
|
|
176
|
+
ping(timeoutMs?: number): Promise<number>;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Probe local system for active TriCache IPC sockets.
|
|
180
|
+
*/
|
|
181
|
+
declare function findActiveSockets(): Promise<string[]>;
|
|
182
|
+
declare function renderProgressBar(ratio: number, width?: number): string;
|
|
183
|
+
declare function formatBytes(bytes: number): string;
|
|
184
|
+
declare function formatNumber(n: number): string;
|
|
185
|
+
declare function formatDuration(ms: number): string;
|
|
186
|
+
/**
|
|
187
|
+
* Render an ANSI/ASCII dashboard representation of the cache metrics.
|
|
188
|
+
*/
|
|
189
|
+
declare function renderTopDashboard(payload: IpcMetricsPayload): string;
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Centralized static process termination bus.
|
|
193
|
+
* Prevents MaxListenersExceededWarning by attaching at most ONE SIGTERM and ONE SIGINT
|
|
194
|
+
* listener to process, broadcasting to all active CacheService instances.
|
|
195
|
+
* Automatically detaches listeners when the instance count reaches 0, preventing
|
|
196
|
+
* event loop / test runner hangs.
|
|
197
|
+
*/
|
|
198
|
+
declare class ProcessTerminationBus {
|
|
199
|
+
private static readonly instances;
|
|
200
|
+
private static registered;
|
|
201
|
+
private static sigtermHandler;
|
|
202
|
+
private static sigintHandler;
|
|
203
|
+
static register(instance: CacheService): void;
|
|
204
|
+
static unregister(instance: CacheService): void;
|
|
205
|
+
/**
|
|
206
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
207
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
208
|
+
*
|
|
209
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
210
|
+
*/
|
|
211
|
+
static flushAll(timeoutMs?: number): Promise<void>;
|
|
212
|
+
/** For testing diagnostics and assertions */
|
|
213
|
+
static get size(): number;
|
|
214
|
+
static get isRegistered(): boolean;
|
|
215
|
+
}
|
|
216
|
+
declare function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOptions>): CacheOptions;
|
|
217
|
+
declare class CacheService {
|
|
218
|
+
private readonly logger;
|
|
219
|
+
private readonly enc;
|
|
220
|
+
private readonly codec;
|
|
221
|
+
private readonly l1;
|
|
222
|
+
private readonly disk;
|
|
223
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
224
|
+
private _diskDisabled;
|
|
225
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
226
|
+
private _workerPool;
|
|
227
|
+
private readonly opts;
|
|
228
|
+
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
229
|
+
private readonly _namespace;
|
|
230
|
+
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
231
|
+
private readonly _redisDisabled;
|
|
232
|
+
private readonly watchdog;
|
|
233
|
+
private pipeliner;
|
|
234
|
+
private readonly inflight;
|
|
235
|
+
private readonly revalidating;
|
|
236
|
+
private readonly _l1Counters;
|
|
237
|
+
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
238
|
+
private readonly tagIndex;
|
|
239
|
+
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
240
|
+
private readonly tagVersions;
|
|
241
|
+
/**
|
|
242
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
243
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
244
|
+
*/
|
|
245
|
+
private readonly dependencyIndex;
|
|
246
|
+
private redis;
|
|
247
|
+
private redisConnecting;
|
|
248
|
+
private readonly cb;
|
|
249
|
+
/** In-process mutex lock map for single-process environments or Redis outages. */
|
|
250
|
+
private _localLocks;
|
|
251
|
+
/** Active OpenTelemetry monotonic counters. */
|
|
252
|
+
private _otelMetrics;
|
|
253
|
+
private snapshotLoaded;
|
|
254
|
+
private _readyPromise;
|
|
255
|
+
private cleanupInterval;
|
|
256
|
+
private diskJanitorInterval;
|
|
257
|
+
private oomInterval;
|
|
258
|
+
private metricsInterval;
|
|
259
|
+
private remoteSnapshotInterval;
|
|
260
|
+
private _shutdownHandler;
|
|
261
|
+
private latencyTracker;
|
|
262
|
+
private readonly instanceId;
|
|
263
|
+
private readonly backplaneChannel;
|
|
264
|
+
private readonly backplaneStreamKey;
|
|
265
|
+
private subClient;
|
|
266
|
+
private streamClient;
|
|
267
|
+
private _lastStreamId;
|
|
268
|
+
private _destroyed;
|
|
269
|
+
private readonly _pendingDiskDeletes;
|
|
270
|
+
private _globalEpoch;
|
|
271
|
+
private readonly _keyMutationEpochs;
|
|
272
|
+
/**
|
|
273
|
+
* Pattern tombstones for disk tier.
|
|
274
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
275
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
276
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
277
|
+
*/
|
|
278
|
+
private readonly _patternTombstones;
|
|
279
|
+
private _addPatternTombstone;
|
|
280
|
+
private _isTombstonedByPattern;
|
|
281
|
+
private _assertActive;
|
|
282
|
+
private _bumpKeyMutation;
|
|
283
|
+
private _getKeyMutationEpoch;
|
|
284
|
+
private _ipcServer?;
|
|
285
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
286
|
+
private _subDisconnectedAt;
|
|
287
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
288
|
+
private readonly _seenCrossRegionEvents;
|
|
289
|
+
private counters;
|
|
290
|
+
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
291
|
+
private _incrementFallbackWarned;
|
|
292
|
+
constructor(options?: CacheOptions);
|
|
293
|
+
/**
|
|
294
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
295
|
+
*
|
|
296
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
297
|
+
* generational tags, and Redis stream backplane.
|
|
298
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
299
|
+
* TTL jitter, and L2 circuit breaking.
|
|
300
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
301
|
+
* and Pub/Sub backplane.
|
|
302
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
303
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
304
|
+
*
|
|
305
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
306
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
307
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
308
|
+
*/
|
|
309
|
+
static preset(type: CachePresetType, overrides?: Partial<CacheOptions>): CacheService;
|
|
310
|
+
/**
|
|
311
|
+
* Get (or create) the process-level singleton CacheService instance.
|
|
312
|
+
*
|
|
313
|
+
* Options are only applied on first call — subsequent calls return the
|
|
314
|
+
* existing instance regardless of options passed. When the new options differ
|
|
315
|
+
* from what the existing singleton was built with, this is a silent no-op by
|
|
316
|
+
* default; set `strictSingleton: true` to throw instead, or watch the
|
|
317
|
+
* `singletonDivergences` metric for detection.
|
|
318
|
+
*
|
|
319
|
+
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
320
|
+
* with different namespaces return independent instances.
|
|
321
|
+
*/
|
|
322
|
+
static create(options?: CacheOptions): CacheService;
|
|
323
|
+
/**
|
|
324
|
+
* Keys that, if set differently on a later `create()` call, represent a
|
|
325
|
+
* meaningful configuration divergence worth flagging (security/correctness
|
|
326
|
+
* relevant — not cosmetic, e.g. log level).
|
|
327
|
+
*/
|
|
328
|
+
private static readonly DIVERGENT_KEYS;
|
|
329
|
+
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
330
|
+
private static optionsDiff;
|
|
331
|
+
/** Increment the singleton-divergence counter (surfaced in `metrics()`). */
|
|
332
|
+
bumpSingletonDivergence(): void;
|
|
333
|
+
/** Read-only view of the options the singleton was constructed with. */
|
|
334
|
+
get options(): CacheOptions;
|
|
335
|
+
/**
|
|
336
|
+
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
337
|
+
* Useful when config is fetched from a secret store at startup.
|
|
338
|
+
*
|
|
339
|
+
* @example
|
|
340
|
+
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
341
|
+
*/
|
|
342
|
+
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
343
|
+
/** Replace the singleton (useful in tests). */
|
|
344
|
+
static reset(options?: CacheOptions): CacheService;
|
|
345
|
+
/** Derive the globalThis key for a given set of options. */
|
|
346
|
+
private static globalKey;
|
|
347
|
+
/**
|
|
348
|
+
* Prepend the configured namespace to a raw cache key.
|
|
349
|
+
* Returns the key unchanged when namespace is empty.
|
|
350
|
+
*
|
|
351
|
+
* This is the only place the namespace prefix is applied — callers always
|
|
352
|
+
* receive and provide un-prefixed keys in the public API.
|
|
353
|
+
*/
|
|
354
|
+
private nk;
|
|
355
|
+
/** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
|
|
356
|
+
private unnk;
|
|
357
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
358
|
+
private _jitterTtl;
|
|
359
|
+
/** Shared no-op span for the common case where no tracer is configured.
|
|
360
|
+
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
361
|
+
private static readonly _nullSpan;
|
|
362
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
363
|
+
private _startSpan;
|
|
364
|
+
private createDedicatedRedisClient;
|
|
365
|
+
private initBackplane;
|
|
366
|
+
private _startStreamConsumer;
|
|
367
|
+
/**
|
|
368
|
+
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
369
|
+
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
370
|
+
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
371
|
+
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
372
|
+
* number. Invalid entries are logged and dropped — never applied.
|
|
373
|
+
*/
|
|
374
|
+
/** @internal Exposed for testing. */
|
|
375
|
+
_processStreamEntry(fields: string[]): void;
|
|
376
|
+
private _applyInvalidationEvent;
|
|
377
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
378
|
+
_handleBackplaneMessage(message: string): void;
|
|
379
|
+
private publishInvalidation;
|
|
380
|
+
private _markCrossRegionEventSeen;
|
|
381
|
+
private _isCrossRegionEventSeen;
|
|
382
|
+
private _broadcastCrossRegion;
|
|
383
|
+
/**
|
|
384
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
385
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
386
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
387
|
+
*
|
|
388
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
389
|
+
*/
|
|
390
|
+
receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean>;
|
|
391
|
+
private _setLocalTagVersion;
|
|
392
|
+
private _getTagVersion;
|
|
393
|
+
private _deleteIfStale;
|
|
394
|
+
/**
|
|
395
|
+
* Serialize payload for L2 Redis storage applying compression and encryption as configured.
|
|
396
|
+
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
397
|
+
*/
|
|
398
|
+
private _serializeAndEncrypt;
|
|
399
|
+
/**
|
|
400
|
+
* Deserialize raw L2 Redis entry applying decryption and decompression as needed.
|
|
401
|
+
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
402
|
+
*/
|
|
403
|
+
private _decryptAndDeserialize;
|
|
404
|
+
/**
|
|
405
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
406
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
407
|
+
*/
|
|
408
|
+
private _scanKeys;
|
|
409
|
+
private _checkAndLogResp3Hint;
|
|
410
|
+
private getRedis;
|
|
411
|
+
/**
|
|
412
|
+
* Writes the cold-start snapshot to disk.
|
|
413
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
414
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
415
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
416
|
+
*/
|
|
417
|
+
writeSnapshot(altPath?: string): void;
|
|
418
|
+
/**
|
|
419
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
420
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
421
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
422
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
423
|
+
*/
|
|
424
|
+
loadSnapshot(): void;
|
|
425
|
+
/**
|
|
426
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
427
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
428
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
429
|
+
*/
|
|
430
|
+
writeRemoteSnapshot(): Promise<boolean>;
|
|
431
|
+
/**
|
|
432
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
433
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
434
|
+
* Returns the number of entries successfully imported.
|
|
435
|
+
*/
|
|
436
|
+
loadRemoteSnapshot(): Promise<number>;
|
|
437
|
+
/**
|
|
438
|
+
* Get a value from cache, or fetch and cache it.
|
|
439
|
+
*
|
|
440
|
+
* @param cacheKey - Unique key identifying this value
|
|
441
|
+
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
442
|
+
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
443
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
444
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
445
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
446
|
+
* is triggered proactively while the caller still receives the
|
|
447
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
448
|
+
* Requires `fetchFn` to be stable across calls.
|
|
449
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
450
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
451
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
452
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
453
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
454
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
455
|
+
*/
|
|
456
|
+
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
457
|
+
priority?: CachePriority;
|
|
458
|
+
swr?: number;
|
|
459
|
+
refreshAhead?: number;
|
|
460
|
+
xfetchBeta?: number;
|
|
461
|
+
notFoundTtl?: number;
|
|
462
|
+
/**
|
|
463
|
+
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
464
|
+
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
465
|
+
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
466
|
+
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
467
|
+
*/
|
|
468
|
+
tags?: string[];
|
|
469
|
+
}): Promise<T>;
|
|
470
|
+
/**
|
|
471
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
472
|
+
* or manual microservice teardown.
|
|
473
|
+
*
|
|
474
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
475
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
476
|
+
*
|
|
477
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
478
|
+
*/
|
|
479
|
+
flushSnapshotOnShutdown(timeoutMs?: number): Promise<boolean>;
|
|
480
|
+
/**
|
|
481
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
482
|
+
*/
|
|
483
|
+
_triggerShutdown(): void;
|
|
484
|
+
/**
|
|
485
|
+
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
486
|
+
*
|
|
487
|
+
* Drop-in ergonomic alternative to `get()` matching developer expectations
|
|
488
|
+
* from `cache-manager` and `keyv`.
|
|
489
|
+
*
|
|
490
|
+
* @param cacheKey - Unique cache key.
|
|
491
|
+
* @param fetchFn - Executed on a cache miss to retrieve fresh data.
|
|
492
|
+
* @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
|
|
496
|
+
* ttl: 300,
|
|
497
|
+
* swr: 60,
|
|
498
|
+
* tags: ['users'],
|
|
499
|
+
* });
|
|
500
|
+
*/
|
|
501
|
+
wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
|
|
502
|
+
private _revalidate;
|
|
503
|
+
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
504
|
+
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
505
|
+
tags?: string[];
|
|
506
|
+
dependsOn?: string[];
|
|
507
|
+
}): Promise<void>;
|
|
508
|
+
/**
|
|
509
|
+
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
510
|
+
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
511
|
+
*/
|
|
512
|
+
private _registerTags;
|
|
513
|
+
/**
|
|
514
|
+
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
515
|
+
*
|
|
516
|
+
* @example
|
|
517
|
+
* await cache.delete('user:abc:profile'); // exact key
|
|
518
|
+
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
519
|
+
*/
|
|
520
|
+
delete(cacheKey: string): Promise<void>;
|
|
521
|
+
/**
|
|
522
|
+
* Distributed counter.
|
|
523
|
+
*
|
|
524
|
+
* When Redis is active, atomically increments the key via `INCR` and returns
|
|
525
|
+
* the new (fleet-wide) value. On a Redis error it increments `counters.errors`
|
|
526
|
+
* and, by default, fails OPEN — returning `0` so a caller's
|
|
527
|
+
* `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
|
|
528
|
+
* `failClosed: true` to re-throw the error instead, enforcing the limit even
|
|
529
|
+
* when Redis is unavailable.
|
|
530
|
+
*
|
|
531
|
+
* When Redis is disabled (or `disableRedis: true`), this maintains an
|
|
532
|
+
* IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
|
|
533
|
+
* works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
|
|
534
|
+
* a one-time warning is logged because rate-limiting is then per-instance, not
|
|
535
|
+
* fleet-wide.
|
|
536
|
+
*/
|
|
537
|
+
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
538
|
+
/**
|
|
539
|
+
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
540
|
+
*
|
|
541
|
+
* @example
|
|
542
|
+
* await cache.clear(); // flush everything
|
|
543
|
+
* await cache.clear('user:abc'); // flush all keys for one user
|
|
544
|
+
*/
|
|
545
|
+
clear(prefix?: string): Promise<void>;
|
|
546
|
+
/**
|
|
547
|
+
* Evict L1 entries that violate the current category or global capacity limits.
|
|
548
|
+
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
549
|
+
* Returns the number of entries evicted.
|
|
550
|
+
*/
|
|
551
|
+
rebalance(): number;
|
|
552
|
+
/**
|
|
553
|
+
* Return the remaining TTL in seconds for a key currently in L1.
|
|
554
|
+
* Returns null if the key is absent from L1 or has already expired.
|
|
555
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
556
|
+
*/
|
|
557
|
+
ttl(cacheKey: string): number | null;
|
|
558
|
+
/**
|
|
559
|
+
* Return true if the key exists in L1 and has not expired.
|
|
560
|
+
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
561
|
+
*/
|
|
562
|
+
has(cacheKey: string): boolean;
|
|
563
|
+
/**
|
|
564
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
565
|
+
*
|
|
566
|
+
* @example
|
|
567
|
+
* for (const key of cache.keys()) console.log(key);
|
|
568
|
+
*/
|
|
569
|
+
keys(): Generator<string>;
|
|
570
|
+
/**
|
|
571
|
+
* Lazily yield every non-expired L1 value.
|
|
572
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
573
|
+
*
|
|
574
|
+
* @example
|
|
575
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
576
|
+
*/
|
|
577
|
+
values<T = unknown>(): Generator<T>;
|
|
578
|
+
/**
|
|
579
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
580
|
+
* Keys are stripped of their namespace prefix.
|
|
581
|
+
*
|
|
582
|
+
* @example
|
|
583
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
584
|
+
*/
|
|
585
|
+
entries<T = unknown>(): Generator<[string, T]>;
|
|
586
|
+
/**
|
|
587
|
+
* High-throughput bulk scan over all live L1 entries.
|
|
588
|
+
*
|
|
589
|
+
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
590
|
+
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
591
|
+
* caller uses the `offset` parameter instead of pre-slicing.
|
|
592
|
+
*
|
|
593
|
+
* ```typescript
|
|
594
|
+
* // Zero extra string allocations — use rawKey + offset directly:
|
|
595
|
+
* cache.scan((rawKey, value, offset) => {
|
|
596
|
+
* const key = rawKey.slice(offset); // allocate only if needed
|
|
597
|
+
* sync(key, value as User);
|
|
598
|
+
* });
|
|
599
|
+
* ```
|
|
600
|
+
*
|
|
601
|
+
* @param fn Called once per live L1 entry.
|
|
602
|
+
* `rawKey` — key with namespace prefix still attached.
|
|
603
|
+
* `value` — deserialized cached value.
|
|
604
|
+
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
605
|
+
*/
|
|
606
|
+
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
|
|
607
|
+
/**
|
|
608
|
+
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
609
|
+
* Returns `false` if the key is absent or already expired.
|
|
610
|
+
*
|
|
611
|
+
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
612
|
+
*/
|
|
613
|
+
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
614
|
+
/**
|
|
615
|
+
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
616
|
+
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
617
|
+
*
|
|
618
|
+
* @example
|
|
619
|
+
* const fresh = cache.getIfFresh('user:123');
|
|
620
|
+
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
621
|
+
*/
|
|
622
|
+
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
623
|
+
/**
|
|
624
|
+
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
625
|
+
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
626
|
+
* Does not write dummy entries on misses or trigger side-effects.
|
|
627
|
+
*
|
|
628
|
+
* @example
|
|
629
|
+
* const val = await cache.peek<User>('user:123');
|
|
630
|
+
*/
|
|
631
|
+
peek<T = unknown>(cacheKey: string): Promise<T | null>;
|
|
632
|
+
/**
|
|
633
|
+
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
634
|
+
* Preserves input ordering. Uses inflight coalescing per key.
|
|
635
|
+
*
|
|
636
|
+
* @param keys - Array of cache keys.
|
|
637
|
+
* @param fetchFn - Called with only the keys that missed L1.
|
|
638
|
+
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
639
|
+
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
640
|
+
*/
|
|
641
|
+
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
642
|
+
/**
|
|
643
|
+
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
644
|
+
* startup warming configured via `warmKeys` has completed.
|
|
645
|
+
*
|
|
646
|
+
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
647
|
+
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
648
|
+
*
|
|
649
|
+
* @example
|
|
650
|
+
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
651
|
+
* await cache.ready(); // gate traffic until warm
|
|
652
|
+
*/
|
|
653
|
+
ready(): Promise<void>;
|
|
654
|
+
/**
|
|
655
|
+
* Batch write — set multiple entries in a single call.
|
|
656
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
657
|
+
*
|
|
658
|
+
* @example
|
|
659
|
+
* await cache.mset({
|
|
660
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
661
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
662
|
+
* });
|
|
663
|
+
*/
|
|
664
|
+
mset<T = unknown>(entries: Record<string, {
|
|
665
|
+
value: T;
|
|
666
|
+
ttl?: number;
|
|
667
|
+
priority?: CachePriority;
|
|
668
|
+
tags?: string[];
|
|
669
|
+
dependsOn?: string[];
|
|
670
|
+
}>): Promise<void>;
|
|
671
|
+
/**
|
|
672
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
673
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
677
|
+
*/
|
|
678
|
+
mdel(keys: string[]): Promise<void>;
|
|
679
|
+
/**
|
|
680
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
681
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
682
|
+
* the local snapshot is unavailable or too stale.
|
|
683
|
+
*
|
|
684
|
+
* Returns the number of keys loaded into L1.
|
|
685
|
+
*
|
|
686
|
+
* @example
|
|
687
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
688
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
689
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
690
|
+
*/
|
|
691
|
+
warmFromL2(pattern: string, opts?: {
|
|
692
|
+
priority?: CachePriority;
|
|
693
|
+
}): Promise<number>;
|
|
694
|
+
/**
|
|
695
|
+
* Invalidate all keys associated with a tag.
|
|
696
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
700
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
701
|
+
*/
|
|
702
|
+
invalidateTag(tag: string): Promise<void>;
|
|
703
|
+
/**
|
|
704
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
705
|
+
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
706
|
+
* reducing latency when invalidating several related tags together.
|
|
707
|
+
*
|
|
708
|
+
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
709
|
+
* synchronously before the Redis round-trip.
|
|
710
|
+
*
|
|
711
|
+
* @example
|
|
712
|
+
* // Instead of three serial round-trips:
|
|
713
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
714
|
+
*/
|
|
715
|
+
invalidateTags(tags: string[]): Promise<void>;
|
|
716
|
+
/**
|
|
717
|
+
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
718
|
+
*/
|
|
719
|
+
getTagVersion(tag: string): Promise<number>;
|
|
720
|
+
/**
|
|
721
|
+
* Measure L1 / disk / Redis latency.
|
|
722
|
+
* Useful for health checks and dashboards.
|
|
723
|
+
*
|
|
724
|
+
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
725
|
+
* `l2` is `null` when Redis is disabled.
|
|
726
|
+
*/
|
|
727
|
+
ping(): Promise<CachePingResult>;
|
|
728
|
+
/**
|
|
729
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
730
|
+
*
|
|
731
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
732
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
733
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
734
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
735
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
736
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
737
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
738
|
+
*
|
|
739
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
740
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
741
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
742
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
743
|
+
*
|
|
744
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
745
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
746
|
+
* to route ingress traffic away while degraded.
|
|
747
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
748
|
+
*/
|
|
749
|
+
health(): CacheHealthStatus;
|
|
750
|
+
/**
|
|
751
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
752
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
753
|
+
*/
|
|
754
|
+
getLatencyWatchdog(): TierLatencyWatchdog;
|
|
755
|
+
/**
|
|
756
|
+
* Export all live L1 entries to Redis via a single pipeline.
|
|
757
|
+
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
758
|
+
* Returns the number of keys written.
|
|
759
|
+
*/
|
|
760
|
+
drainToL2(): Promise<number>;
|
|
761
|
+
stats(): {
|
|
762
|
+
l1: {
|
|
763
|
+
entries: number;
|
|
764
|
+
sizeBytes: number;
|
|
765
|
+
sizeKB: number;
|
|
766
|
+
categories: Record<string, {
|
|
767
|
+
entries: number;
|
|
768
|
+
hits: number;
|
|
769
|
+
}>;
|
|
770
|
+
bloom: {
|
|
771
|
+
checks: number;
|
|
772
|
+
falsePositives: number;
|
|
773
|
+
};
|
|
774
|
+
compression: {
|
|
775
|
+
compressed: number;
|
|
776
|
+
uncompressed: number;
|
|
777
|
+
bytesSaved: number;
|
|
778
|
+
};
|
|
779
|
+
};
|
|
780
|
+
disk: {
|
|
781
|
+
files: number;
|
|
782
|
+
sizeKB: number;
|
|
783
|
+
maxKB: number;
|
|
784
|
+
backpressure?: DiskBackpressureStats;
|
|
785
|
+
pruning?: {
|
|
786
|
+
active: boolean;
|
|
787
|
+
pruneRounds: number;
|
|
788
|
+
entriesPruned: number;
|
|
789
|
+
spillsShedTotal: number;
|
|
790
|
+
hostVolumeLowSpacePauses: number;
|
|
791
|
+
};
|
|
792
|
+
};
|
|
793
|
+
};
|
|
794
|
+
/**
|
|
795
|
+
* Write `value` only if the key is not already cached.
|
|
796
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
797
|
+
*
|
|
798
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
799
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
800
|
+
* multiple instances. L1 is populated on success.
|
|
801
|
+
*
|
|
802
|
+
* @example
|
|
803
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
804
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
805
|
+
*/
|
|
806
|
+
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
807
|
+
/**
|
|
808
|
+
* Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
|
|
809
|
+
* execute `fn`, and automatically release the lock on completion or error.
|
|
810
|
+
*
|
|
811
|
+
* When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
|
|
812
|
+
* safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
|
|
813
|
+
* When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
|
|
814
|
+
*
|
|
815
|
+
* @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
|
|
816
|
+
* @param fn Task to run exclusively while holding the lock.
|
|
817
|
+
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
818
|
+
*/
|
|
819
|
+
lock<T>(resourceKey: string, fn: () => Promise<T>, options?: LockOptions): Promise<T>;
|
|
820
|
+
private _initOtelMetrics;
|
|
821
|
+
/**
|
|
822
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
823
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
824
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
825
|
+
*
|
|
826
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
827
|
+
* collection overhead.
|
|
828
|
+
*
|
|
829
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
830
|
+
*
|
|
831
|
+
* @example
|
|
832
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
833
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
834
|
+
*/
|
|
835
|
+
hotKeys(n?: number): Array<{
|
|
836
|
+
key: string;
|
|
837
|
+
hits: number;
|
|
838
|
+
sizeBytes: number;
|
|
839
|
+
}>;
|
|
840
|
+
/**
|
|
841
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
842
|
+
* pattern that may contain `*` wildcards).
|
|
843
|
+
*/
|
|
844
|
+
private _matchesGlob;
|
|
845
|
+
/**
|
|
846
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
847
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
848
|
+
* Transitive dependencies are traversed with cycle protection via a visited Set.
|
|
849
|
+
*/
|
|
850
|
+
private _cascadeDependencies;
|
|
851
|
+
/** Return a full metrics snapshot. */
|
|
852
|
+
metrics(): CacheMetrics;
|
|
853
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
854
|
+
getPipelinerStats(): {
|
|
855
|
+
batchesDispatched: number;
|
|
856
|
+
operationsBatched: number;
|
|
857
|
+
pendingQueueSize: number;
|
|
858
|
+
} | null;
|
|
859
|
+
/**
|
|
860
|
+
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
861
|
+
* Paste the result into your `/metrics` endpoint.
|
|
862
|
+
*
|
|
863
|
+
* @param m - Snapshot returned by `cache.metrics()`
|
|
864
|
+
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
865
|
+
*/
|
|
866
|
+
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
867
|
+
/**
|
|
868
|
+
* Dynamically rotate the active encryption key at runtime without restarting.
|
|
869
|
+
* Installs the new key as primary for all subsequent writes, while preserving
|
|
870
|
+
* the previous key for seamless fallback decryption of existing cache entries.
|
|
871
|
+
*/
|
|
872
|
+
rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void>;
|
|
873
|
+
/** Close Redis connections and stop all background timers. */
|
|
874
|
+
destroy(): Promise<void>;
|
|
875
|
+
/**
|
|
876
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
877
|
+
*/
|
|
878
|
+
getIpcServer(): IpcTelemetryServer | undefined;
|
|
879
|
+
/**
|
|
880
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
881
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
882
|
+
*/
|
|
883
|
+
getWTinyLfuStats(): WTinyLfuStats | undefined;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
export { CacheService as C, type IIpcCacheProvider as I, type LatencyWatchdogOptions as L, ProcessTerminationBus as P, TierLatencyWatchdog as T, type IpcMetricsPayload as a, IpcTelemetryClient as b, IpcTelemetryServer as c, type LatencyWatchdogTelemetry as d, deepMergeOptions as e, findActiveSockets as f, formatBytes as g, formatDuration as h, formatNumber as i, renderTopDashboard as j, resolveIpcSocketPath as k, renderProgressBar as r };
|