tricache 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +87 -1371
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2790 -471
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -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 +2553 -470
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +2926 -562
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +220 -72
- package/dist/index.cjs +6936 -2518
- 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 +2494 -463
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2517 -483
- 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-B6krw64X.d.ts} +596 -659
- package/package.json +34 -6
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1339 -402
- package/src/cli.ts +120 -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 +203 -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/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +39 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -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 +290 -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
|
@@ -1,3 +1,335 @@
|
|
|
1
|
+
import { KeyObject } from 'crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
|
|
5
|
+
*
|
|
6
|
+
* Four modes are supported via the `encryptionMode` CacheOption:
|
|
7
|
+
*
|
|
8
|
+
* ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
|
|
9
|
+
* │ Mode │ Key bytes │ Notes │
|
|
10
|
+
* ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
|
|
11
|
+
* │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
|
|
12
|
+
* │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
|
|
13
|
+
* │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
|
|
14
|
+
* │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
|
|
15
|
+
* │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
|
|
16
|
+
* │ │ │ Use only for dev or non-sensitive data. │
|
|
17
|
+
* └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
|
|
18
|
+
*
|
|
19
|
+
* Key generation:
|
|
20
|
+
* AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
21
|
+
* AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
22
|
+
* CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
23
|
+
* XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
24
|
+
*
|
|
25
|
+
* Redis envelope formats:
|
|
26
|
+
* enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
|
|
27
|
+
* a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
|
|
28
|
+
* ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
|
|
29
|
+
* xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
|
|
30
|
+
*
|
|
31
|
+
* Disk envelope formats:
|
|
32
|
+
* TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
|
|
33
|
+
* TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
|
|
34
|
+
* TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
|
|
35
|
+
* TRIC1XOR | key⊕data[N] ← XOR
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
|
|
39
|
+
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
40
|
+
declare class CacheEncryption {
|
|
41
|
+
private _key;
|
|
42
|
+
private _keyObj;
|
|
43
|
+
private _mode;
|
|
44
|
+
/** Fail-closed on invalid key material when opted in via constructor opts. */
|
|
45
|
+
private readonly _strictKeyValidation;
|
|
46
|
+
private _prevKey;
|
|
47
|
+
private _prevKeyObj;
|
|
48
|
+
private _prevMode;
|
|
49
|
+
private readonly _ivPool;
|
|
50
|
+
private _ivOffset;
|
|
51
|
+
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
52
|
+
private _nextIV;
|
|
53
|
+
private readonly _ctrIvPool;
|
|
54
|
+
private _ctrIvOffset;
|
|
55
|
+
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
56
|
+
private _nextCtrIV;
|
|
57
|
+
/**
|
|
58
|
+
* XOR `data` with the key, cycling through key bytes.
|
|
59
|
+
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
60
|
+
*
|
|
61
|
+
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
62
|
+
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
63
|
+
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
64
|
+
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
65
|
+
*
|
|
66
|
+
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
67
|
+
*/
|
|
68
|
+
private _xorBuffer;
|
|
69
|
+
constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode, opts?: {
|
|
70
|
+
strictKeyValidation?: boolean;
|
|
71
|
+
});
|
|
72
|
+
get isEnabled(): boolean;
|
|
73
|
+
get mode(): EncryptionMode;
|
|
74
|
+
/**
|
|
75
|
+
* Snapshot the key material needed to spin up an off-main-thread worker pool.
|
|
76
|
+
* Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
|
|
77
|
+
* cast in cache-service.ts — the worker pool reads these via this accessor
|
|
78
|
+
* instead of reaching into underscore-prefixed internals.
|
|
79
|
+
*/
|
|
80
|
+
toWorkerInit(): {
|
|
81
|
+
keyBase64: string;
|
|
82
|
+
mode: EncryptionMode;
|
|
83
|
+
prevKeyBase64: string | undefined;
|
|
84
|
+
prevMode: EncryptionMode;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Rotate the active encryption key dynamically at runtime.
|
|
88
|
+
* Promotes the current primary key to previousEncryptionKey for zero-downtime
|
|
89
|
+
* fallback decryption of existing cache entries in L2/Disk, and installs
|
|
90
|
+
* the new key as primary for all subsequent writes.
|
|
91
|
+
*/
|
|
92
|
+
rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void;
|
|
93
|
+
/**
|
|
94
|
+
* Encrypt a string for Redis storage.
|
|
95
|
+
* Returns a mode-prefixed base64 string when a key is configured;
|
|
96
|
+
* otherwise returns the original string unchanged (backward-compatible).
|
|
97
|
+
*/
|
|
98
|
+
encrypt(plaintext: string): string;
|
|
99
|
+
/**
|
|
100
|
+
* Decrypt a Redis value.
|
|
101
|
+
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
102
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
103
|
+
*/
|
|
104
|
+
decrypt(value: string): string;
|
|
105
|
+
private _decryptWithKey;
|
|
106
|
+
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
107
|
+
encryptBuffer(data: Buffer): Buffer;
|
|
108
|
+
/**
|
|
109
|
+
* Decrypt a raw Buffer from disk/snapshot.
|
|
110
|
+
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
111
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
112
|
+
*/
|
|
113
|
+
decryptBuffer(data: Buffer): Buffer;
|
|
114
|
+
private _decryptBufferWithKey;
|
|
115
|
+
}
|
|
116
|
+
interface EnvelopeEncryptionOptions {
|
|
117
|
+
/** RSA public key (PEM string, KeyObject, or Buffer) for encrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
|
|
118
|
+
publicKey?: string | KeyObject | Buffer;
|
|
119
|
+
/** RSA private key (PEM string, KeyObject, or Buffer) for decrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
|
|
120
|
+
privateKey?: string | KeyObject | Buffer;
|
|
121
|
+
/** Optional custom KMS encrypt hook for cloud HSM / KMS integration */
|
|
122
|
+
kmsEncrypt?: (dek: Buffer) => Promise<Buffer> | Buffer;
|
|
123
|
+
/** Optional custom KMS decrypt hook for cloud HSM / KMS integration */
|
|
124
|
+
kmsDecrypt?: (encryptedDek: Buffer) => Promise<Buffer> | Buffer;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* EnvelopeEncryption — Asymmetric envelope encryption for remote snapshots and cold backups.
|
|
128
|
+
*
|
|
129
|
+
* Encrypts payload with an ephemeral 256-bit AES-GCM data encryption key (DEK),
|
|
130
|
+
* then wraps the DEK using asymmetric RSA-OAEP (SHA-256) or a custom KMS hook.
|
|
131
|
+
*
|
|
132
|
+
* Storage format:
|
|
133
|
+
* [MAGIC "TRICENV1" (8B)] | [keyLen (4B BE)] | [encryptedDEK (N bytes)] | [iv (12B)] | [tag (16B)] | [ciphertext (M bytes)]
|
|
134
|
+
*/
|
|
135
|
+
declare class EnvelopeEncryption {
|
|
136
|
+
static isEnvelope(data: Buffer): boolean;
|
|
137
|
+
static encrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer>;
|
|
138
|
+
static decrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer>;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* tricache — Remote Blob Storage Cold-Start Hydration
|
|
143
|
+
*
|
|
144
|
+
* Enables stateless containers (Kubernetes, AWS ECS/Fargate, Google Cloud Run, Fly.io)
|
|
145
|
+
* to persist and hydrate L1 cache snapshots from remote object storage (S3, GCS, R2, Azure, MinIO, or HTTP).
|
|
146
|
+
*/
|
|
147
|
+
interface IRemoteSnapshotAdapter {
|
|
148
|
+
/**
|
|
149
|
+
* Read the latest snapshot blob from remote storage.
|
|
150
|
+
* Returns null if no snapshot exists yet (e.g. 404 Not Found / first deploy).
|
|
151
|
+
*/
|
|
152
|
+
get(): Promise<Buffer | Uint8Array | null>;
|
|
153
|
+
/**
|
|
154
|
+
* Write the snapshot blob to remote storage.
|
|
155
|
+
*/
|
|
156
|
+
put(data: Buffer): Promise<void>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface RemoteSnapshotOptions {
|
|
160
|
+
/**
|
|
161
|
+
* Remote storage adapter implementation.
|
|
162
|
+
*/
|
|
163
|
+
adapter: IRemoteSnapshotAdapter;
|
|
164
|
+
/**
|
|
165
|
+
* Maximum age in milliseconds of a remote snapshot before it is rejected as stale.
|
|
166
|
+
* Default: 2 hours (7,200,000 ms).
|
|
167
|
+
*/
|
|
168
|
+
maxAgeMs?: number;
|
|
169
|
+
/**
|
|
170
|
+
* Whether to trigger an asynchronous remote snapshot upload during graceful shutdown (SIGTERM/SIGINT).
|
|
171
|
+
* Ensure your container orchestration allows sufficient termination grace period (e.g. >= 10s).
|
|
172
|
+
* Default: true.
|
|
173
|
+
*/
|
|
174
|
+
saveOnShutdown?: boolean;
|
|
175
|
+
/**
|
|
176
|
+
* Optional periodic background upload interval in milliseconds.
|
|
177
|
+
* Ensures remote snapshots stay fresh even in the event of ungraceful container termination (SIGKILL / OOM / spot eviction).
|
|
178
|
+
* Default: undefined (disabled).
|
|
179
|
+
*/
|
|
180
|
+
intervalMs?: number;
|
|
181
|
+
/**
|
|
182
|
+
* Optional asymmetric envelope encryption configuration.
|
|
183
|
+
* When configured, snapshot payloads are encrypted with an ephemeral AES-256 DEK wrapped by RSA-OAEP or KMS.
|
|
184
|
+
*/
|
|
185
|
+
envelope?: EnvelopeEncryptionOptions;
|
|
186
|
+
}
|
|
187
|
+
interface HttpSnapshotAdapterOptions {
|
|
188
|
+
/**
|
|
189
|
+
* URL to fetch the snapshot from (e.g. S3 presigned GET URL or internal blob service).
|
|
190
|
+
*/
|
|
191
|
+
getUrl: string;
|
|
192
|
+
/**
|
|
193
|
+
* URL to upload the snapshot to via HTTP PUT. If omitted, defaults to `getUrl`.
|
|
194
|
+
*/
|
|
195
|
+
putUrl?: string;
|
|
196
|
+
/**
|
|
197
|
+
* Optional HTTP headers (e.g. Authorization or custom metadata).
|
|
198
|
+
*/
|
|
199
|
+
headers?: Record<string, string>;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Creates an HTTP-based remote snapshot adapter using standard global `fetch()`.
|
|
203
|
+
* Ideal for S3/R2 presigned URLs, internal storage gateways, or serverless webhooks.
|
|
204
|
+
*/
|
|
205
|
+
declare function createHttpSnapshotAdapter(options: HttpSnapshotAdapterOptions): IRemoteSnapshotAdapter;
|
|
206
|
+
/**
|
|
207
|
+
* Helper to define and type-check a custom remote snapshot adapter (e.g. AWS SDK v3, GCS, Azure Blob).
|
|
208
|
+
*/
|
|
209
|
+
declare function createCustomSnapshotAdapter(adapter: IRemoteSnapshotAdapter): IRemoteSnapshotAdapter;
|
|
210
|
+
/**
|
|
211
|
+
* In-memory snapshot adapter designed for unit testing, CI pipelines, and ephemeral mock environments.
|
|
212
|
+
*/
|
|
213
|
+
declare function createMemorySnapshotAdapter(): IRemoteSnapshotAdapter & {
|
|
214
|
+
getBuffer(): Buffer | null;
|
|
215
|
+
clear(): void;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* tricache — Multi-Cluster / Geo-Distributed Cross-Region Invalidation Relay
|
|
220
|
+
*
|
|
221
|
+
* Enables multi-region architectures (e.g. us-east-1 + eu-central-1) with independent
|
|
222
|
+
* Redis clusters to synchronize invalidations across regions without expensive
|
|
223
|
+
* active-active Redis Enterprise licenses.
|
|
224
|
+
*/
|
|
225
|
+
interface CrossRegionInvalidationEvent {
|
|
226
|
+
/** Unique ID of this invalidation event (UUIDv4) */
|
|
227
|
+
id: string;
|
|
228
|
+
/** Region where the invalidation originated, e.g. 'us-east-1' */
|
|
229
|
+
originRegion: string;
|
|
230
|
+
/** Instance ID that initiated the invalidation */
|
|
231
|
+
originInstanceId: string;
|
|
232
|
+
/** Invalidation operation */
|
|
233
|
+
op: 'del' | 'del-glob' | 'tag_incr';
|
|
234
|
+
/** Cache key or tag name */
|
|
235
|
+
key: string;
|
|
236
|
+
/** New tag version for generational tag invalidation */
|
|
237
|
+
tagVersion?: number;
|
|
238
|
+
/** Timestamp when the event was created */
|
|
239
|
+
timestamp: number;
|
|
240
|
+
/** Optional namespace of the origin cache */
|
|
241
|
+
namespace?: string;
|
|
242
|
+
/** Optional W3C traceparent header for distributed context propagation */
|
|
243
|
+
traceparent?: string;
|
|
244
|
+
}
|
|
245
|
+
interface ICrossRegionRelay {
|
|
246
|
+
/**
|
|
247
|
+
* Broadcasts an invalidation event across regions (via HTTP mesh, SNS, SQS, EventBridge, or custom bus).
|
|
248
|
+
*/
|
|
249
|
+
broadcast(event: CrossRegionInvalidationEvent): Promise<void>;
|
|
250
|
+
}
|
|
251
|
+
interface CrossRegionRelayOptions {
|
|
252
|
+
/**
|
|
253
|
+
* Region identifier for this instance, e.g. 'us-east-1' or 'eu-central-1'.
|
|
254
|
+
*/
|
|
255
|
+
currentRegion: string;
|
|
256
|
+
/**
|
|
257
|
+
* Cross-region relay implementation.
|
|
258
|
+
*/
|
|
259
|
+
relay: ICrossRegionRelay;
|
|
260
|
+
/**
|
|
261
|
+
* Optional shared secret or bearer token for authenticating HTTP webhook mesh calls.
|
|
262
|
+
*/
|
|
263
|
+
authSecret?: string;
|
|
264
|
+
/**
|
|
265
|
+
* Max entries stored in the deduplication cache for preventing invalidation loop echoes.
|
|
266
|
+
* Default: 10,000.
|
|
267
|
+
*/
|
|
268
|
+
dedupCacheSize?: number;
|
|
269
|
+
/**
|
|
270
|
+
* Whether writes via `set()` should also broadcast cross-region.
|
|
271
|
+
* Default: `false` (only explicit invalidations `delete()`, `deletePattern()`,
|
|
272
|
+
* and `invalidateTag()` broadcast cross-region, avoiding inter-region thrashing
|
|
273
|
+
* when independent caches populate from local databases).
|
|
274
|
+
*/
|
|
275
|
+
broadcastOnSet?: boolean;
|
|
276
|
+
}
|
|
277
|
+
interface HttpMeshRelayOptions {
|
|
278
|
+
/**
|
|
279
|
+
* Array of peer regional webhook endpoints (e.g. ['https://eu.internal.api/cache/invalidation']).
|
|
280
|
+
*/
|
|
281
|
+
peerUrls: string[];
|
|
282
|
+
/**
|
|
283
|
+
* Optional authentication secret sent in the `Authorization: Bearer <secret>` header.
|
|
284
|
+
*/
|
|
285
|
+
authSecret?: string;
|
|
286
|
+
/**
|
|
287
|
+
* Request timeout in milliseconds for each peer. Default: 3000 ms.
|
|
288
|
+
*/
|
|
289
|
+
timeoutMs?: number;
|
|
290
|
+
/**
|
|
291
|
+
* Optional fetch implementation (defaults to globalThis.fetch).
|
|
292
|
+
*/
|
|
293
|
+
fetchFn?: typeof fetch;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Creates an HTTP-based peer mesh relay using native Node 22 `fetch()`.
|
|
297
|
+
* Broadcasts events concurrently to all configured peer URLs.
|
|
298
|
+
*/
|
|
299
|
+
declare function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegionRelay;
|
|
300
|
+
/**
|
|
301
|
+
* Type-checking helper for custom cross-region relays (AWS SNS/SQS, EventBridge, Kafka, NATS).
|
|
302
|
+
*/
|
|
303
|
+
declare function createCustomCrossRegionRelay(relay: ICrossRegionRelay): ICrossRegionRelay;
|
|
304
|
+
/**
|
|
305
|
+
* In-memory cross-region mesh bus designed for unit testing and multi-region simulations.
|
|
306
|
+
*/
|
|
307
|
+
declare function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
|
|
308
|
+
register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void;
|
|
309
|
+
getBroadcastCount(): number;
|
|
310
|
+
clear(): void;
|
|
311
|
+
};
|
|
312
|
+
interface WebhookRequestLike {
|
|
313
|
+
headers: Record<string, string | string[] | undefined>;
|
|
314
|
+
body: unknown;
|
|
315
|
+
}
|
|
316
|
+
interface WebhookResponseLike {
|
|
317
|
+
status: number;
|
|
318
|
+
body: {
|
|
319
|
+
ok: boolean;
|
|
320
|
+
message?: string;
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Creates a generic webhook handler to receive incoming cross-region invalidation requests.
|
|
325
|
+
* Compatible with Express, Fastify, Next.js route handlers, or Node's `http.createServer`.
|
|
326
|
+
*/
|
|
327
|
+
declare function createCrossRegionWebhookHandler(cache: {
|
|
328
|
+
receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> | boolean;
|
|
329
|
+
}, options?: {
|
|
330
|
+
authSecret?: string;
|
|
331
|
+
}): (req: WebhookRequestLike) => Promise<WebhookResponseLike>;
|
|
332
|
+
|
|
1
333
|
/**
|
|
2
334
|
* tricache — shared types and interfaces
|
|
3
335
|
*/
|
|
@@ -5,19 +337,29 @@
|
|
|
5
337
|
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
6
338
|
* Pass your existing OTEL tracer; no extra package required.
|
|
7
339
|
*/
|
|
340
|
+
interface ICacheSpanLink {
|
|
341
|
+
context: {
|
|
342
|
+
traceId: string;
|
|
343
|
+
spanId: string;
|
|
344
|
+
traceFlags?: number;
|
|
345
|
+
};
|
|
346
|
+
}
|
|
8
347
|
interface ICacheSpan {
|
|
9
348
|
setAttribute(key: string, value: string | number | boolean): this;
|
|
10
349
|
setStatus(status: {
|
|
11
350
|
code: 0 | 1 | 2;
|
|
12
351
|
message?: string;
|
|
13
352
|
}): this;
|
|
353
|
+
recordException?(err: Error | unknown): this;
|
|
14
354
|
end(): void;
|
|
15
355
|
}
|
|
16
356
|
/**
|
|
17
357
|
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
18
358
|
*/
|
|
19
359
|
interface ICacheTracer {
|
|
20
|
-
startSpan(name: string
|
|
360
|
+
startSpan(name: string, options?: {
|
|
361
|
+
links?: ICacheSpanLink[];
|
|
362
|
+
}): ICacheSpan;
|
|
21
363
|
}
|
|
22
364
|
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
23
365
|
interface ILogger {
|
|
@@ -218,6 +560,30 @@ interface CacheMetrics {
|
|
|
218
560
|
/** Timestamp of the most recent OOM eviction, or null */
|
|
219
561
|
lastTriggeredAt: number | null;
|
|
220
562
|
};
|
|
563
|
+
/** Remote snapshot statistics — present when remoteSnapshot is configured */
|
|
564
|
+
remoteSnapshot?: {
|
|
565
|
+
enabled: boolean;
|
|
566
|
+
uploads: number;
|
|
567
|
+
downloads: number;
|
|
568
|
+
errors: number;
|
|
569
|
+
lastUploadedAt: number | null;
|
|
570
|
+
lastDownloadedAt: number | null;
|
|
571
|
+
};
|
|
572
|
+
/** Cross-region invalidation relay statistics — present when crossRegion is configured */
|
|
573
|
+
crossRegion?: {
|
|
574
|
+
enabled: boolean;
|
|
575
|
+
currentRegion: string;
|
|
576
|
+
sent: number;
|
|
577
|
+
received: number;
|
|
578
|
+
deduplicated: number;
|
|
579
|
+
errors: number;
|
|
580
|
+
};
|
|
581
|
+
/** Auto-pipelining statistics — present when autoPipeline is enabled */
|
|
582
|
+
pipelining?: {
|
|
583
|
+
batchesDispatched: number;
|
|
584
|
+
operationsBatched: number;
|
|
585
|
+
pendingQueueSize: number;
|
|
586
|
+
};
|
|
221
587
|
l1: {
|
|
222
588
|
entries: number;
|
|
223
589
|
sizeBytes: number;
|
|
@@ -228,6 +594,21 @@ interface CacheMetrics {
|
|
|
228
594
|
sizeKB: number;
|
|
229
595
|
maxKB: number;
|
|
230
596
|
disabled: boolean;
|
|
597
|
+
latencyWatchdog?: {
|
|
598
|
+
bypassActive: boolean;
|
|
599
|
+
bypassStage: 0 | 1 | 2 | 3;
|
|
600
|
+
diskP95Ms: number;
|
|
601
|
+
redisP95Ms: number;
|
|
602
|
+
redisDampened: boolean;
|
|
603
|
+
bypassedTotal: number;
|
|
604
|
+
};
|
|
605
|
+
pruning?: {
|
|
606
|
+
active: boolean;
|
|
607
|
+
pruneRounds: number;
|
|
608
|
+
entriesPruned: number;
|
|
609
|
+
spillsShedTotal: number;
|
|
610
|
+
hostVolumeLowSpacePauses: number;
|
|
611
|
+
};
|
|
231
612
|
};
|
|
232
613
|
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
233
614
|
adaptiveTtl?: {
|
|
@@ -246,11 +627,28 @@ interface CacheMetrics {
|
|
|
246
627
|
}>;
|
|
247
628
|
};
|
|
248
629
|
}
|
|
630
|
+
/**
|
|
631
|
+
* Result returned by cache.health()
|
|
632
|
+
*
|
|
633
|
+
* NOTE: Intended strictly for Kubernetes Readiness probes (/ready).
|
|
634
|
+
* Do NOT hook into Liveness probes (/healthz), as degraded caches should shed ingress
|
|
635
|
+
* traffic while keeping the container alive to heal local storage and drain in-flight tasks.
|
|
636
|
+
*/
|
|
637
|
+
interface CacheHealthStatus {
|
|
638
|
+
healthy: boolean;
|
|
639
|
+
degraded: boolean;
|
|
640
|
+
reasons: string[];
|
|
641
|
+
details?: Record<string, unknown>;
|
|
642
|
+
}
|
|
249
643
|
/** Per-category memory limits for L1 */
|
|
250
644
|
interface CategoryLimit {
|
|
251
645
|
maxEntries: number;
|
|
252
646
|
maxSizeBytes: number;
|
|
253
647
|
}
|
|
648
|
+
/**
|
|
649
|
+
* Supported opinionated pre-configurations for CacheService.preset()
|
|
650
|
+
*/
|
|
651
|
+
type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened';
|
|
254
652
|
/**
|
|
255
653
|
* Options accepted by CacheService.create()
|
|
256
654
|
*
|
|
@@ -282,12 +680,75 @@ interface CacheOptions {
|
|
|
282
680
|
* Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
|
|
283
681
|
*/
|
|
284
682
|
forbiddenSnapshotPrefixes?: string[];
|
|
683
|
+
/**
|
|
684
|
+
* L1 cache admission and eviction policy:
|
|
685
|
+
* - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
|
|
686
|
+
* mathematical scan resistance and burst recency absorption.
|
|
687
|
+
* - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
|
|
688
|
+
* Default: `'wtinylfu'`
|
|
689
|
+
*/
|
|
690
|
+
l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
|
|
285
691
|
/** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
|
|
286
692
|
diskCacheDir?: string;
|
|
287
693
|
/** Max total bytes for the disk tier. Default: 500 MB */
|
|
288
694
|
diskMaxBytes?: number;
|
|
289
695
|
/** Max bytes for a single disk entry. Default: 10 MB */
|
|
290
696
|
diskEntryMaxBytes?: number;
|
|
697
|
+
/**
|
|
698
|
+
* Maximum concurrent asynchronous filesystem writes permitted in-flight for disk spills.
|
|
699
|
+
* Protects against libuv threadpool (UV_THREADPOOL_SIZE=4) saturation during cloud I/O throttling.
|
|
700
|
+
* Default: Math.min(4, Math.max(1, Math.floor(os.availableParallelism() / 4)))
|
|
701
|
+
*/
|
|
702
|
+
diskMaxConcurrentWrites?: number;
|
|
703
|
+
/**
|
|
704
|
+
* Maximum queued spill writes awaiting execution before shedding kicks in.
|
|
705
|
+
* Once pending writes hit this limit, incoming spills are dropped without touching libuv.
|
|
706
|
+
* Default: 512
|
|
707
|
+
*/
|
|
708
|
+
diskMaxPendingWrites?: number;
|
|
709
|
+
/**
|
|
710
|
+
* Maximum time permitted for an individual write before timing out and tripping backpressure.
|
|
711
|
+
* Default: 500 ms
|
|
712
|
+
*/
|
|
713
|
+
diskWriteTimeoutMs?: number;
|
|
714
|
+
/**
|
|
715
|
+
* Number of consecutive slow or failed disk writes before tripping the disk circuit breaker to OPEN.
|
|
716
|
+
* Default: 5
|
|
717
|
+
*/
|
|
718
|
+
diskCircuitBreakerThreshold?: number;
|
|
719
|
+
/**
|
|
720
|
+
* Cooldown time in ms before transitioning the disk circuit breaker from OPEN to HALF-OPEN for canary probing.
|
|
721
|
+
* Default: 5000 ms
|
|
722
|
+
*/
|
|
723
|
+
diskCircuitBreakerCooldownMs?: number;
|
|
724
|
+
/**
|
|
725
|
+
* Enable dynamic tier latency watchdog.
|
|
726
|
+
* Compares disk read latency against Redis and automatically sheds traffic to Redis when disk slows down.
|
|
727
|
+
* Default: true
|
|
728
|
+
*/
|
|
729
|
+
diskLatencyWatchdog?: boolean;
|
|
730
|
+
/**
|
|
731
|
+
* Ratio of disk p95 latency to Redis p95 latency required to trip bypass.
|
|
732
|
+
* Default: 1.5
|
|
733
|
+
*/
|
|
734
|
+
diskLatencyBypassRatio?: number;
|
|
735
|
+
/**
|
|
736
|
+
* Minimum disk p95 latency floor in ms before bypass can be considered.
|
|
737
|
+
* Default: 10 ms
|
|
738
|
+
*/
|
|
739
|
+
diskLatencyBypassMinMs?: number;
|
|
740
|
+
/**
|
|
741
|
+
* Cooldown time in ms before probing canary during Stage 3 bypass.
|
|
742
|
+
* Subject to ±30% anti-synchronicity jitter.
|
|
743
|
+
* Default: 30_000 ms
|
|
744
|
+
*/
|
|
745
|
+
diskLatencyBypassCooldownMs?: number;
|
|
746
|
+
/**
|
|
747
|
+
* When true, cache.health().healthy returns false when degraded, causing
|
|
748
|
+
* Kubernetes readiness probes to fail and route traffic away from this pod.
|
|
749
|
+
* Default: false (graceful local degradation without failing readiness)
|
|
750
|
+
*/
|
|
751
|
+
failReadinessOnDegraded?: boolean;
|
|
291
752
|
/**
|
|
292
753
|
* Redis/Valkey hostname (no `redis://` prefix).
|
|
293
754
|
* Falls back to the `REDIS_HOST` environment variable.
|
|
@@ -296,6 +757,29 @@ interface CacheOptions {
|
|
|
296
757
|
redisHost?: string;
|
|
297
758
|
/** Redis port. Default: 6379 */
|
|
298
759
|
redisPort?: number;
|
|
760
|
+
/**
|
|
761
|
+
* Strict per-command timeout for Redis operations.
|
|
762
|
+
* When expired, triggers connection reset / socket destruction to prevent RESP multiplexing desync.
|
|
763
|
+
* Default: 2500 ms
|
|
764
|
+
*/
|
|
765
|
+
redisCommandTimeoutMs?: number;
|
|
766
|
+
/**
|
|
767
|
+
* Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
|
|
768
|
+
* Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
|
|
769
|
+
* Default: false
|
|
770
|
+
*/
|
|
771
|
+
autoPipeline?: boolean;
|
|
772
|
+
/**
|
|
773
|
+
* Maximum batch size for auto-pipelined Redis requests before forcing an immediate dispatch.
|
|
774
|
+
* Default: 100
|
|
775
|
+
*/
|
|
776
|
+
maxPipelineBatchSize?: number;
|
|
777
|
+
/**
|
|
778
|
+
* Clock skew tolerance window in milliseconds across cluster nodes / containers.
|
|
779
|
+
* Allows timestamps within this tolerance ahead of the local clock to prevent premature eviction anomalies.
|
|
780
|
+
* Default: 250 ms
|
|
781
|
+
*/
|
|
782
|
+
clockSkewToleranceMs?: number;
|
|
299
783
|
/**
|
|
300
784
|
* Whether to enable TLS for the Redis connection. Default: true in production,
|
|
301
785
|
* false otherwise.
|
|
@@ -312,6 +796,17 @@ interface CacheOptions {
|
|
|
312
796
|
* true in development.
|
|
313
797
|
*/
|
|
314
798
|
disableRedis?: boolean;
|
|
799
|
+
/**
|
|
800
|
+
* Pre-existing or custom Redis client or driver adapter (e.g. `NodeRedisAdapter` wrapping
|
|
801
|
+
* `@redis/client`, or a pre-configured `ioredis` instance).
|
|
802
|
+
* When supplied, TriCache bypasses internal connection construction and uses this client directly.
|
|
803
|
+
*/
|
|
804
|
+
redisClient?: IRedisDriver | any;
|
|
805
|
+
/**
|
|
806
|
+
* Dedicated subscriber client for Redis Pub/Sub invalidation backplane.
|
|
807
|
+
* If omitted and `redisClient` supports `.duplicate()`, TriCache will duplicate `redisClient`.
|
|
808
|
+
*/
|
|
809
|
+
redisSubClient?: IRedisDriver | any;
|
|
315
810
|
/**
|
|
316
811
|
* Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
|
|
317
812
|
* disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
|
|
@@ -347,6 +842,13 @@ interface CacheOptions {
|
|
|
347
842
|
* Has no effect when no key is configured at all (encryption stays off, by design).
|
|
348
843
|
*/
|
|
349
844
|
strictKeyValidation?: boolean;
|
|
845
|
+
/**
|
|
846
|
+
* Whether to call `.toJSON()` when serializing objects into binary cache buffers.
|
|
847
|
+
* - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
|
|
848
|
+
* - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
|
|
849
|
+
* avoiding accidental API response projections on cached domain entities.
|
|
850
|
+
*/
|
|
851
|
+
serializeToJSON?: boolean;
|
|
350
852
|
/**
|
|
351
853
|
* Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
|
|
352
854
|
* - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
|
|
@@ -370,6 +872,11 @@ interface CacheOptions {
|
|
|
370
872
|
* Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
|
|
371
873
|
*/
|
|
372
874
|
snapshotMaxAgeMs?: number;
|
|
875
|
+
/**
|
|
876
|
+
* Optional remote blob storage snapshot configuration for stateless containers (S3, GCS, R2, HTTP).
|
|
877
|
+
* Enables persisting and hydrating L1 RAM cache snapshots across Kubernetes / container deployments.
|
|
878
|
+
*/
|
|
879
|
+
remoteSnapshot?: RemoteSnapshotOptions;
|
|
373
880
|
/**
|
|
374
881
|
* Optional namespace prefix for all cache keys.
|
|
375
882
|
*
|
|
@@ -439,6 +946,13 @@ interface CacheOptions {
|
|
|
439
946
|
* Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
|
|
440
947
|
*/
|
|
441
948
|
useShardedPubSub?: boolean;
|
|
949
|
+
/**
|
|
950
|
+
* Optional cross-region invalidation relay configuration for geo-distributed deployments.
|
|
951
|
+
* Synchronizes `delete()` and `invalidateTag()` events across separate regional Redis clusters
|
|
952
|
+
* (e.g. `us-east-1` and `eu-central-1`) via HTTP mesh or custom message brokers (SNS, SQS, EventBridge)
|
|
953
|
+
* with automatic origin deduplication to prevent invalidation loops.
|
|
954
|
+
*/
|
|
955
|
+
crossRegion?: CrossRegionRelayOptions;
|
|
442
956
|
/**
|
|
443
957
|
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
444
958
|
* `oomHeapThreshold`, a fraction of the coldest L1 entries are
|
|
@@ -467,6 +981,17 @@ interface CacheOptions {
|
|
|
467
981
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
468
982
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
469
983
|
metricsIntervalMs?: number;
|
|
984
|
+
/**
|
|
985
|
+
* Enable local IPC telemetry server (Unix domain socket on POSIX, Windows Named Pipe on win32)
|
|
986
|
+
* allowing external monitors like `tricache top` to inspect this instance.
|
|
987
|
+
* Default: `false`.
|
|
988
|
+
*/
|
|
989
|
+
enableIpc?: boolean;
|
|
990
|
+
/**
|
|
991
|
+
* Custom socket path or Windows named pipe path for the IPC telemetry server.
|
|
992
|
+
* Default: `/tmp/tricache-<pid>.sock` (POSIX) or `\\.\pipe\tricache-<pid>` (Windows).
|
|
993
|
+
*/
|
|
994
|
+
ipcSocketPath?: string;
|
|
470
995
|
/**
|
|
471
996
|
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
472
997
|
* `delete()` are each wrapped in a span with attributes:
|
|
@@ -831,668 +1356,80 @@ interface ICacheMeter {
|
|
|
831
1356
|
}): ICacheObservableGauge;
|
|
832
1357
|
addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
833
1358
|
}
|
|
834
|
-
|
|
835
1359
|
/**
|
|
836
|
-
*
|
|
837
|
-
*
|
|
838
|
-
* Four modes are supported via the `encryptionMode` CacheOption:
|
|
839
|
-
*
|
|
840
|
-
* ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
|
|
841
|
-
* │ Mode │ Key bytes │ Notes │
|
|
842
|
-
* ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
|
|
843
|
-
* │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
|
|
844
|
-
* │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
|
|
845
|
-
* │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
|
|
846
|
-
* │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
|
|
847
|
-
* │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
|
|
848
|
-
* │ │ │ Use only for dev or non-sensitive data. │
|
|
849
|
-
* └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
|
|
850
|
-
*
|
|
851
|
-
* Key generation:
|
|
852
|
-
* AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
853
|
-
* AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
854
|
-
* CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
855
|
-
* XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
856
|
-
*
|
|
857
|
-
* Redis envelope formats:
|
|
858
|
-
* enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
|
|
859
|
-
* a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
|
|
860
|
-
* ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
|
|
861
|
-
* xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
|
|
862
|
-
*
|
|
863
|
-
* Disk envelope formats:
|
|
864
|
-
* TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
|
|
865
|
-
* TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
|
|
866
|
-
* TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
|
|
867
|
-
* TRIC1XOR | key⊕data[N] ← XOR
|
|
1360
|
+
* Common pipeline / transaction interface matching ioredis and adapted drivers.
|
|
868
1361
|
*/
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
private _prevMode;
|
|
881
|
-
private readonly _ivPool;
|
|
882
|
-
private _ivOffset;
|
|
883
|
-
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
884
|
-
private _nextIV;
|
|
885
|
-
private readonly _ctrIvPool;
|
|
886
|
-
private _ctrIvOffset;
|
|
887
|
-
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
888
|
-
private _nextCtrIV;
|
|
889
|
-
/**
|
|
890
|
-
* XOR `data` with the key, cycling through key bytes.
|
|
891
|
-
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
892
|
-
*
|
|
893
|
-
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
894
|
-
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
895
|
-
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
896
|
-
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
897
|
-
*
|
|
898
|
-
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
899
|
-
*/
|
|
900
|
-
private _xorBuffer;
|
|
901
|
-
constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode, opts?: {
|
|
902
|
-
strictKeyValidation?: boolean;
|
|
903
|
-
});
|
|
904
|
-
get isEnabled(): boolean;
|
|
905
|
-
get mode(): EncryptionMode;
|
|
906
|
-
/**
|
|
907
|
-
* Snapshot the key material needed to spin up an off-main-thread worker pool.
|
|
908
|
-
* Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
|
|
909
|
-
* cast in cache-service.ts — the worker pool reads these via this accessor
|
|
910
|
-
* instead of reaching into underscore-prefixed internals.
|
|
911
|
-
*/
|
|
912
|
-
toWorkerInit(): {
|
|
913
|
-
keyBase64: string;
|
|
914
|
-
mode: EncryptionMode;
|
|
915
|
-
prevKeyBase64: string | undefined;
|
|
916
|
-
prevMode: EncryptionMode;
|
|
917
|
-
};
|
|
918
|
-
/**
|
|
919
|
-
* Rotate the active encryption key dynamically at runtime.
|
|
920
|
-
* Promotes the current primary key to previousEncryptionKey for zero-downtime
|
|
921
|
-
* fallback decryption of existing cache entries in L2/Disk, and installs
|
|
922
|
-
* the new key as primary for all subsequent writes.
|
|
923
|
-
*/
|
|
924
|
-
rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void;
|
|
925
|
-
/**
|
|
926
|
-
* Encrypt a string for Redis storage.
|
|
927
|
-
* Returns a mode-prefixed base64 string when a key is configured;
|
|
928
|
-
* otherwise returns the original string unchanged (backward-compatible).
|
|
929
|
-
*/
|
|
930
|
-
encrypt(plaintext: string): string;
|
|
931
|
-
/**
|
|
932
|
-
* Decrypt a Redis value.
|
|
933
|
-
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
934
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
935
|
-
*/
|
|
936
|
-
decrypt(value: string): string;
|
|
937
|
-
private _decryptWithKey;
|
|
938
|
-
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
939
|
-
encryptBuffer(data: Buffer): Buffer;
|
|
940
|
-
/**
|
|
941
|
-
* Decrypt a raw Buffer from disk/snapshot.
|
|
942
|
-
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
943
|
-
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
944
|
-
*/
|
|
945
|
-
decryptBuffer(data: Buffer): Buffer;
|
|
946
|
-
private _decryptBufferWithKey;
|
|
1362
|
+
interface IRedisPipeline {
|
|
1363
|
+
get(key: string): this;
|
|
1364
|
+
set(key: string, value: string, ...args: (string | number)[]): this;
|
|
1365
|
+
setex(key: string, seconds: number, value: string): this;
|
|
1366
|
+
del(...keys: string[]): this;
|
|
1367
|
+
expire(key: string, seconds: number): this;
|
|
1368
|
+
incr(key: string): this;
|
|
1369
|
+
sadd(key: string, ...members: string[]): this;
|
|
1370
|
+
smembers(key: string): this;
|
|
1371
|
+
hset(key: string, value: Record<string, string>): this;
|
|
1372
|
+
exec(): Promise<Array<[Error | null, any]> | null>;
|
|
947
1373
|
}
|
|
948
|
-
|
|
949
1374
|
/**
|
|
950
|
-
*
|
|
951
|
-
*
|
|
952
|
-
* Architecture:
|
|
953
|
-
* L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
|
|
954
|
-
* L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
|
|
955
|
-
* L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
|
|
956
|
-
* DB → your fetchFunction (cache miss path)
|
|
957
|
-
*
|
|
958
|
-
* Key features:
|
|
959
|
-
* - Thundering-herd / cache-stampede prevention (inflight Promise registry)
|
|
960
|
-
* - Stale-While-Revalidate (serve stale instantly + revalidate in background)
|
|
961
|
-
* - AES-256-GCM encryption for L2 and disk data at rest
|
|
962
|
-
* - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
|
|
963
|
-
* - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
|
|
964
|
-
* - Periodic cleanup of expired entries every 5 minutes
|
|
1375
|
+
* Pluggable contract for external Redis drivers (e.g. `@redis/client` / `node-redis`,
|
|
1376
|
+
* custom connection pools, or pre-configured `ioredis` instances).
|
|
965
1377
|
*/
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
/**
|
|
1022
|
-
* Get (or create) the process-level singleton CacheService instance.
|
|
1023
|
-
*
|
|
1024
|
-
* Options are only applied on first call — subsequent calls return the
|
|
1025
|
-
* existing instance regardless of options passed. When the new options differ
|
|
1026
|
-
* from what the existing singleton was built with, this is a silent no-op by
|
|
1027
|
-
* default; set `strictSingleton: true` to throw instead, or watch the
|
|
1028
|
-
* `singletonDivergences` metric for detection.
|
|
1029
|
-
*
|
|
1030
|
-
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
1031
|
-
* with different namespaces return independent instances.
|
|
1032
|
-
*/
|
|
1033
|
-
static create(options?: CacheOptions): CacheService;
|
|
1034
|
-
/**
|
|
1035
|
-
* Keys that, if set differently on a later `create()` call, represent a
|
|
1036
|
-
* meaningful configuration divergence worth flagging (security/correctness
|
|
1037
|
-
* relevant — not cosmetic, e.g. log level).
|
|
1038
|
-
*/
|
|
1039
|
-
private static readonly DIVERGENT_KEYS;
|
|
1040
|
-
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
1041
|
-
private static optionsDiff;
|
|
1042
|
-
/** Increment the singleton-divergence counter (surfaced in `metrics()`). */
|
|
1043
|
-
bumpSingletonDivergence(): void;
|
|
1044
|
-
/** Read-only view of the options the singleton was constructed with. */
|
|
1045
|
-
get options(): CacheOptions;
|
|
1046
|
-
/**
|
|
1047
|
-
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
1048
|
-
* Useful when config is fetched from a secret store at startup.
|
|
1049
|
-
*
|
|
1050
|
-
* @example
|
|
1051
|
-
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
1052
|
-
*/
|
|
1053
|
-
static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
|
|
1054
|
-
/** Replace the singleton (useful in tests). */
|
|
1055
|
-
static reset(options?: CacheOptions): CacheService;
|
|
1056
|
-
/** Derive the globalThis key for a given set of options. */
|
|
1057
|
-
private static globalKey;
|
|
1058
|
-
/**
|
|
1059
|
-
* Prepend the configured namespace to a raw cache key.
|
|
1060
|
-
* Returns the key unchanged when namespace is empty.
|
|
1061
|
-
*
|
|
1062
|
-
* This is the only place the namespace prefix is applied — callers always
|
|
1063
|
-
* receive and provide un-prefixed keys in the public API.
|
|
1064
|
-
*/
|
|
1065
|
-
private nk;
|
|
1066
|
-
/** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
|
|
1067
|
-
private unnk;
|
|
1068
|
-
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
1069
|
-
private _jitterTtl;
|
|
1070
|
-
/** Shared no-op span for the common case where no tracer is configured.
|
|
1071
|
-
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
1072
|
-
private static readonly _nullSpan;
|
|
1073
|
-
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
1074
|
-
private _startSpan;
|
|
1075
|
-
private createDedicatedRedisClient;
|
|
1076
|
-
private initBackplane;
|
|
1077
|
-
private _startStreamConsumer;
|
|
1078
|
-
/**
|
|
1079
|
-
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
1080
|
-
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
1081
|
-
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
1082
|
-
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
1083
|
-
* number. Invalid entries are logged and dropped — never applied.
|
|
1084
|
-
*/
|
|
1085
|
-
/** @internal Exposed for testing. */
|
|
1086
|
-
_processStreamEntry(fields: string[]): void;
|
|
1087
|
-
private _applyInvalidationEvent;
|
|
1088
|
-
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
1089
|
-
_handleBackplaneMessage(message: string): void;
|
|
1090
|
-
private publishInvalidation;
|
|
1091
|
-
private _setLocalTagVersion;
|
|
1092
|
-
private _getTagVersion;
|
|
1093
|
-
private _deleteIfStale;
|
|
1094
|
-
/**
|
|
1095
|
-
* Serialize payload for L2 Redis storage applying compression and encryption as configured.
|
|
1096
|
-
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
1097
|
-
*/
|
|
1098
|
-
private _serializeAndEncrypt;
|
|
1099
|
-
/**
|
|
1100
|
-
* Deserialize raw L2 Redis entry applying decryption and decompression as needed.
|
|
1101
|
-
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
1102
|
-
*/
|
|
1103
|
-
private _decryptAndDeserialize;
|
|
1104
|
-
/**
|
|
1105
|
-
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
1106
|
-
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
1107
|
-
*/
|
|
1108
|
-
private _scanKeys;
|
|
1109
|
-
private _checkAndLogResp3Hint;
|
|
1110
|
-
private getRedis;
|
|
1111
|
-
writeSnapshot(altPath?: string): void;
|
|
1112
|
-
loadSnapshot(): void;
|
|
1113
|
-
/**
|
|
1114
|
-
* Get a value from cache, or fetch and cache it.
|
|
1115
|
-
*
|
|
1116
|
-
* @param cacheKey - Unique key identifying this value
|
|
1117
|
-
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
1118
|
-
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
1119
|
-
* @param opts.priority - Override the auto-inferred eviction priority
|
|
1120
|
-
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
1121
|
-
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
1122
|
-
* is triggered proactively while the caller still receives the
|
|
1123
|
-
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
1124
|
-
* Requires `fetchFn` to be stable across calls.
|
|
1125
|
-
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
1126
|
-
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
1127
|
-
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
1128
|
-
* decide probabilistically rather than at a fixed threshold.
|
|
1129
|
-
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
1130
|
-
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
1131
|
-
*/
|
|
1132
|
-
get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
|
|
1133
|
-
priority?: CachePriority;
|
|
1134
|
-
swr?: number;
|
|
1135
|
-
refreshAhead?: number;
|
|
1136
|
-
xfetchBeta?: number;
|
|
1137
|
-
notFoundTtl?: number;
|
|
1138
|
-
/**
|
|
1139
|
-
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
1140
|
-
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
1141
|
-
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
1142
|
-
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
1143
|
-
*/
|
|
1144
|
-
tags?: string[];
|
|
1145
|
-
}): Promise<T>;
|
|
1146
|
-
/**
|
|
1147
|
-
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
1148
|
-
*
|
|
1149
|
-
* Drop-in ergonomic alternative to `get()` matching developer expectations
|
|
1150
|
-
* from `cache-manager` and `keyv`.
|
|
1151
|
-
*
|
|
1152
|
-
* @param cacheKey - Unique cache key.
|
|
1153
|
-
* @param fetchFn - Executed on a cache miss to retrieve fresh data.
|
|
1154
|
-
* @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
|
|
1155
|
-
*
|
|
1156
|
-
* @example
|
|
1157
|
-
* const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
|
|
1158
|
-
* ttl: 300,
|
|
1159
|
-
* swr: 60,
|
|
1160
|
-
* tags: ['users'],
|
|
1161
|
-
* });
|
|
1162
|
-
*/
|
|
1163
|
-
wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
|
|
1164
|
-
private _revalidate;
|
|
1165
|
-
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1166
|
-
set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
|
|
1167
|
-
tags?: string[];
|
|
1168
|
-
dependsOn?: string[];
|
|
1169
|
-
}): Promise<void>;
|
|
1170
|
-
/**
|
|
1171
|
-
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
1172
|
-
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
1173
|
-
*/
|
|
1174
|
-
private _registerTags;
|
|
1175
|
-
/**
|
|
1176
|
-
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
1177
|
-
*
|
|
1178
|
-
* @example
|
|
1179
|
-
* await cache.delete('user:abc:profile'); // exact key
|
|
1180
|
-
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
1181
|
-
*/
|
|
1182
|
-
delete(cacheKey: string): Promise<void>;
|
|
1183
|
-
/**
|
|
1184
|
-
* Distributed counter.
|
|
1185
|
-
*
|
|
1186
|
-
* When Redis is active, atomically increments the key via `INCR` and returns
|
|
1187
|
-
* the new (fleet-wide) value. On a Redis error it increments `counters.errors`
|
|
1188
|
-
* and, by default, fails OPEN — returning `0` so a caller's
|
|
1189
|
-
* `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
|
|
1190
|
-
* `failClosed: true` to re-throw the error instead, enforcing the limit even
|
|
1191
|
-
* when Redis is unavailable.
|
|
1192
|
-
*
|
|
1193
|
-
* When Redis is disabled (or `disableRedis: true`), this maintains an
|
|
1194
|
-
* IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
|
|
1195
|
-
* works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
|
|
1196
|
-
* a one-time warning is logged because rate-limiting is then per-instance, not
|
|
1197
|
-
* fleet-wide.
|
|
1198
|
-
*/
|
|
1199
|
-
increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
|
|
1200
|
-
/**
|
|
1201
|
-
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
1202
|
-
*
|
|
1203
|
-
* @example
|
|
1204
|
-
* await cache.clear(); // flush everything
|
|
1205
|
-
* await cache.clear('user:abc'); // flush all keys for one user
|
|
1206
|
-
*/
|
|
1207
|
-
clear(prefix?: string): Promise<void>;
|
|
1208
|
-
/**
|
|
1209
|
-
* Evict L1 entries that violate the current category or global capacity limits.
|
|
1210
|
-
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
1211
|
-
* Returns the number of entries evicted.
|
|
1212
|
-
*/
|
|
1213
|
-
rebalance(): number;
|
|
1214
|
-
/**
|
|
1215
|
-
* Return the remaining TTL in seconds for a key currently in L1.
|
|
1216
|
-
* Returns null if the key is absent from L1 or has already expired.
|
|
1217
|
-
* Only reflects L1 state — does not query Redis or disk.
|
|
1218
|
-
*/
|
|
1219
|
-
ttl(cacheKey: string): number | null;
|
|
1220
|
-
/**
|
|
1221
|
-
* Return true if the key exists in L1 and has not expired.
|
|
1222
|
-
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
1223
|
-
*/
|
|
1224
|
-
has(cacheKey: string): boolean;
|
|
1225
|
-
/**
|
|
1226
|
-
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
1227
|
-
*
|
|
1228
|
-
* @example
|
|
1229
|
-
* for (const key of cache.keys()) console.log(key);
|
|
1230
|
-
*/
|
|
1231
|
-
keys(): Generator<string>;
|
|
1232
|
-
/**
|
|
1233
|
-
* Lazily yield every non-expired L1 value.
|
|
1234
|
-
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
1235
|
-
*
|
|
1236
|
-
* @example
|
|
1237
|
-
* for (const val of cache.values<User>()) console.log(val.id);
|
|
1238
|
-
*/
|
|
1239
|
-
values<T = unknown>(): Generator<T>;
|
|
1240
|
-
/**
|
|
1241
|
-
* Lazily yield every non-expired L1 [key, value] pair.
|
|
1242
|
-
* Keys are stripped of their namespace prefix.
|
|
1243
|
-
*
|
|
1244
|
-
* @example
|
|
1245
|
-
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
1246
|
-
*/
|
|
1247
|
-
entries<T = unknown>(): Generator<[string, T]>;
|
|
1248
|
-
/**
|
|
1249
|
-
* High-throughput bulk scan over all live L1 entries.
|
|
1250
|
-
*
|
|
1251
|
-
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
1252
|
-
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
1253
|
-
* caller uses the `offset` parameter instead of pre-slicing.
|
|
1254
|
-
*
|
|
1255
|
-
* ```typescript
|
|
1256
|
-
* // Zero extra string allocations — use rawKey + offset directly:
|
|
1257
|
-
* cache.scan((rawKey, value, offset) => {
|
|
1258
|
-
* const key = rawKey.slice(offset); // allocate only if needed
|
|
1259
|
-
* sync(key, value as User);
|
|
1260
|
-
* });
|
|
1261
|
-
* ```
|
|
1262
|
-
*
|
|
1263
|
-
* @param fn Called once per live L1 entry.
|
|
1264
|
-
* `rawKey` — key with namespace prefix still attached.
|
|
1265
|
-
* `value` — deserialized cached value.
|
|
1266
|
-
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
1267
|
-
*/
|
|
1268
|
-
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
|
|
1269
|
-
/**
|
|
1270
|
-
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
1271
|
-
* Returns `false` if the key is absent or already expired.
|
|
1272
|
-
*
|
|
1273
|
-
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
1274
|
-
*/
|
|
1275
|
-
touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
|
|
1276
|
-
/**
|
|
1277
|
-
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
1278
|
-
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
1279
|
-
*
|
|
1280
|
-
* @example
|
|
1281
|
-
* const fresh = cache.getIfFresh('user:123');
|
|
1282
|
-
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
1283
|
-
*/
|
|
1284
|
-
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
1285
|
-
/**
|
|
1286
|
-
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
1287
|
-
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
1288
|
-
* Does not write dummy entries on misses or trigger side-effects.
|
|
1289
|
-
*
|
|
1290
|
-
* @example
|
|
1291
|
-
* const val = await cache.peek<User>('user:123');
|
|
1292
|
-
*/
|
|
1293
|
-
peek<T = unknown>(cacheKey: string): Promise<T | null>;
|
|
1294
|
-
/**
|
|
1295
|
-
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
1296
|
-
* Preserves input ordering. Uses inflight coalescing per key.
|
|
1297
|
-
*
|
|
1298
|
-
* @param keys - Array of cache keys.
|
|
1299
|
-
* @param fetchFn - Called with only the keys that missed L1.
|
|
1300
|
-
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
1301
|
-
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
1302
|
-
*/
|
|
1303
|
-
mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
1304
|
-
/**
|
|
1305
|
-
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
1306
|
-
* startup warming configured via `warmKeys` has completed.
|
|
1307
|
-
*
|
|
1308
|
-
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
1309
|
-
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
1310
|
-
*
|
|
1311
|
-
* @example
|
|
1312
|
-
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
1313
|
-
* await cache.ready(); // gate traffic until warm
|
|
1314
|
-
*/
|
|
1315
|
-
ready(): Promise<void>;
|
|
1316
|
-
/**
|
|
1317
|
-
* Batch write — set multiple entries in a single call.
|
|
1318
|
-
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
1319
|
-
*
|
|
1320
|
-
* @example
|
|
1321
|
-
* await cache.mset({
|
|
1322
|
-
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
1323
|
-
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
1324
|
-
* });
|
|
1325
|
-
*/
|
|
1326
|
-
mset<T = unknown>(entries: Record<string, {
|
|
1327
|
-
value: T;
|
|
1328
|
-
ttl?: number;
|
|
1329
|
-
priority?: CachePriority;
|
|
1330
|
-
tags?: string[];
|
|
1331
|
-
dependsOn?: string[];
|
|
1332
|
-
}>): Promise<void>;
|
|
1333
|
-
/**
|
|
1334
|
-
* Batch delete — delete multiple exact keys in a single call.
|
|
1335
|
-
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
1336
|
-
*
|
|
1337
|
-
* @example
|
|
1338
|
-
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
1339
|
-
*/
|
|
1340
|
-
mdel(keys: string[]): Promise<void>;
|
|
1341
|
-
/**
|
|
1342
|
-
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
1343
|
-
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
1344
|
-
* the local snapshot is unavailable or too stale.
|
|
1345
|
-
*
|
|
1346
|
-
* Returns the number of keys loaded into L1.
|
|
1347
|
-
*
|
|
1348
|
-
* @example
|
|
1349
|
-
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
1350
|
-
* const loaded = await cache.warmFromL2('org:*');
|
|
1351
|
-
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
1352
|
-
*/
|
|
1353
|
-
warmFromL2(pattern: string, opts?: {
|
|
1354
|
-
priority?: CachePriority;
|
|
1355
|
-
}): Promise<number>;
|
|
1356
|
-
/**
|
|
1357
|
-
* Invalidate all keys associated with a tag.
|
|
1358
|
-
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
1359
|
-
*
|
|
1360
|
-
* @example
|
|
1361
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
1362
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
1363
|
-
*/
|
|
1364
|
-
invalidateTag(tag: string): Promise<void>;
|
|
1365
|
-
/**
|
|
1366
|
-
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
1367
|
-
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
1368
|
-
* reducing latency when invalidating several related tags together.
|
|
1369
|
-
*
|
|
1370
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
1371
|
-
* synchronously before the Redis round-trip.
|
|
1372
|
-
*
|
|
1373
|
-
* @example
|
|
1374
|
-
* // Instead of three serial round-trips:
|
|
1375
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
1376
|
-
*/
|
|
1377
|
-
invalidateTags(tags: string[]): Promise<void>;
|
|
1378
|
-
/**
|
|
1379
|
-
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
1380
|
-
*/
|
|
1381
|
-
getTagVersion(tag: string): Promise<number>;
|
|
1382
|
-
/**
|
|
1383
|
-
* Measure L1 / disk / Redis latency.
|
|
1384
|
-
* Useful for health checks and dashboards.
|
|
1385
|
-
*
|
|
1386
|
-
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
1387
|
-
* `l2` is `null` when Redis is disabled.
|
|
1388
|
-
*/
|
|
1389
|
-
ping(): Promise<CachePingResult>;
|
|
1390
|
-
/**
|
|
1391
|
-
* Export all live L1 entries to Redis via a single pipeline.
|
|
1392
|
-
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
1393
|
-
* Returns the number of keys written.
|
|
1394
|
-
*/
|
|
1395
|
-
drainToL2(): Promise<number>;
|
|
1396
|
-
stats(): {
|
|
1397
|
-
l1: {
|
|
1398
|
-
entries: number;
|
|
1399
|
-
sizeBytes: number;
|
|
1400
|
-
sizeKB: number;
|
|
1401
|
-
categories: Record<string, {
|
|
1402
|
-
entries: number;
|
|
1403
|
-
hits: number;
|
|
1404
|
-
}>;
|
|
1405
|
-
bloom: {
|
|
1406
|
-
checks: number;
|
|
1407
|
-
falsePositives: number;
|
|
1408
|
-
};
|
|
1409
|
-
compression: {
|
|
1410
|
-
compressed: number;
|
|
1411
|
-
uncompressed: number;
|
|
1412
|
-
bytesSaved: number;
|
|
1413
|
-
};
|
|
1414
|
-
};
|
|
1415
|
-
disk: {
|
|
1416
|
-
files: number;
|
|
1417
|
-
sizeKB: number;
|
|
1418
|
-
maxKB: number;
|
|
1419
|
-
};
|
|
1420
|
-
};
|
|
1421
|
-
/**
|
|
1422
|
-
* Write `value` only if the key is not already cached.
|
|
1423
|
-
* Returns `true` if the write happened, `false` if the key already existed.
|
|
1424
|
-
*
|
|
1425
|
-
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
1426
|
-
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
1427
|
-
* multiple instances. L1 is populated on success.
|
|
1428
|
-
*
|
|
1429
|
-
* @example
|
|
1430
|
-
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
1431
|
-
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
1432
|
-
*/
|
|
1433
|
-
setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
|
|
1434
|
-
/**
|
|
1435
|
-
* Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
|
|
1436
|
-
* execute `fn`, and automatically release the lock on completion or error.
|
|
1437
|
-
*
|
|
1438
|
-
* When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
|
|
1439
|
-
* safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
|
|
1440
|
-
* When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
|
|
1441
|
-
*
|
|
1442
|
-
* @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
|
|
1443
|
-
* @param fn Task to run exclusively while holding the lock.
|
|
1444
|
-
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
1445
|
-
*/
|
|
1446
|
-
lock<T>(resourceKey: string, fn: () => Promise<T>, options?: LockOptions): Promise<T>;
|
|
1447
|
-
private _initOtelMetrics;
|
|
1448
|
-
/**
|
|
1449
|
-
* Return the top-N live L1 keys by historical access frequency.
|
|
1450
|
-
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
1451
|
-
* whose historical frequency exceeds their current in-memory hit count.
|
|
1452
|
-
*
|
|
1453
|
-
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
1454
|
-
* collection overhead.
|
|
1455
|
-
*
|
|
1456
|
-
* @param n - Maximum number of keys to return. Default: 10.
|
|
1457
|
-
*
|
|
1458
|
-
* @example
|
|
1459
|
-
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
1460
|
-
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
1461
|
-
*/
|
|
1462
|
-
hotKeys(n?: number): Array<{
|
|
1463
|
-
key: string;
|
|
1464
|
-
hits: number;
|
|
1465
|
-
sizeBytes: number;
|
|
1466
|
-
}>;
|
|
1467
|
-
/**
|
|
1468
|
-
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
1469
|
-
* pattern that may contain `*` wildcards).
|
|
1470
|
-
*/
|
|
1471
|
-
private _matchesGlob;
|
|
1472
|
-
/**
|
|
1473
|
-
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
1474
|
-
* that was registered via `dependsOn` and whose source pattern matches.
|
|
1475
|
-
* Transitive dependencies are traversed with cycle protection via a visited Set.
|
|
1476
|
-
*/
|
|
1477
|
-
private _cascadeDependencies;
|
|
1478
|
-
/** Return a full metrics snapshot. */
|
|
1479
|
-
metrics(): CacheMetrics;
|
|
1480
|
-
/**
|
|
1481
|
-
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
1482
|
-
* Paste the result into your `/metrics` endpoint.
|
|
1483
|
-
*
|
|
1484
|
-
* @param m - Snapshot returned by `cache.metrics()`
|
|
1485
|
-
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
1486
|
-
*/
|
|
1487
|
-
static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
|
|
1488
|
-
/**
|
|
1489
|
-
* Dynamically rotate the active encryption key at runtime without restarting.
|
|
1490
|
-
* Installs the new key as primary for all subsequent writes, while preserving
|
|
1491
|
-
* the previous key for seamless fallback decryption of existing cache entries.
|
|
1492
|
-
*/
|
|
1493
|
-
rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void>;
|
|
1494
|
-
/** Close Redis connections and stop all background timers. */
|
|
1495
|
-
destroy(): Promise<void>;
|
|
1378
|
+
interface IRedisDriver {
|
|
1379
|
+
get(key: string): Promise<string | null>;
|
|
1380
|
+
set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
|
|
1381
|
+
setex?(key: string, seconds: number, value: string): Promise<unknown>;
|
|
1382
|
+
del(...keys: string[]): Promise<number>;
|
|
1383
|
+
ping(): Promise<string>;
|
|
1384
|
+
expire(key: string, seconds: number): Promise<number | boolean>;
|
|
1385
|
+
incr(key: string): Promise<number>;
|
|
1386
|
+
eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
1387
|
+
multi(): IRedisPipeline;
|
|
1388
|
+
pipeline?(): IRedisPipeline;
|
|
1389
|
+
smembers?(key: string): Promise<string[]>;
|
|
1390
|
+
sadd?(key: string, ...members: string[]): Promise<number>;
|
|
1391
|
+
scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
|
|
1392
|
+
scanStream?(options?: {
|
|
1393
|
+
match?: string;
|
|
1394
|
+
count?: number;
|
|
1395
|
+
}): any;
|
|
1396
|
+
hset?(key: string, value: Record<string, string>): Promise<unknown>;
|
|
1397
|
+
publish?(channel: string, message: string): Promise<number>;
|
|
1398
|
+
subscribe?(...channels: string[]): Promise<unknown>;
|
|
1399
|
+
disconnect(): Promise<void> | void;
|
|
1400
|
+
quit?(): Promise<void> | void;
|
|
1401
|
+
duplicate?(): IRedisDriver;
|
|
1402
|
+
on?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1403
|
+
once?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1404
|
+
isOpen?: boolean;
|
|
1405
|
+
connect?(): Promise<unknown>;
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Real-time telemetry and state for the disk tier backpressure queue.
|
|
1409
|
+
*/
|
|
1410
|
+
interface DiskBackpressureStats {
|
|
1411
|
+
activeWrites: number;
|
|
1412
|
+
pendingWrites: number;
|
|
1413
|
+
spillsDropped: number;
|
|
1414
|
+
circuitState: 'closed' | 'open' | 'half-open';
|
|
1415
|
+
lastTripTimestamp: number;
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Telemetry metrics and counters for Window TinyLFU cache admission.
|
|
1419
|
+
*/
|
|
1420
|
+
interface WTinyLfuStats {
|
|
1421
|
+
capacity: number;
|
|
1422
|
+
size: number;
|
|
1423
|
+
windowSize: number;
|
|
1424
|
+
probationSize: number;
|
|
1425
|
+
protectedSize: number;
|
|
1426
|
+
hits: number;
|
|
1427
|
+
misses: number;
|
|
1428
|
+
hitRate: number;
|
|
1429
|
+
admissions: number;
|
|
1430
|
+
rejections: number;
|
|
1431
|
+
demotions: number;
|
|
1432
|
+
promotions: number;
|
|
1496
1433
|
}
|
|
1497
1434
|
|
|
1498
|
-
export {
|
|
1435
|
+
export { type ICrossRegionRelay as A, type WebhookRequestLike as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type WebhookResponseLike as F, consoleLogger as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, createCrossRegionWebhookHandler as J, createCustomCrossRegionRelay as K, type LockOptions as L, createCustomSnapshotAdapter as M, createHttpMeshRelay as N, createHttpSnapshotAdapter as O, createMemoryCrossRegionRelay as P, createMemorySnapshotAdapter as Q, type RemoteSnapshotOptions as R, type SmartCacheEntry as S, type WrapOptions as W, type CacheMetrics as a, type CacheHealthStatus as b, type CachePresetType as c, type CrossRegionInvalidationEvent as d, CachePriority as e, type CachePingResult as f, type WTinyLfuStats as g, type ILogger as h, type IRemoteSnapshotAdapter as i, type CategoryLimit as j, type EvictionReason as k, type CacheHit as l, CacheEncryption as m, type DiskCacheEntry as n, type IRedisDriver as o, type IRedisPipeline as p, type CrossRegionRelayOptions as q, EnvelopeEncryption as r, type EnvelopeEncryptionOptions as s, type HttpSnapshotAdapterOptions as t, type ICacheBatchObservableCallback as u, type ICacheCounter as v, type ICacheMeter as w, type ICacheObservableGauge as x, type ICacheSpan as y, type ICacheSpanLink as z };
|