tricache 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -28
- package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
- package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
- package/dist/cli.cjs +1757 -777
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1757 -773
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +280 -153
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +254 -147
- package/dist/hono/index.cjs +1805 -793
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1946 -842
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +137 -57
- package/dist/index.cjs +2073 -937
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +40 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1849 -806
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1913 -887
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +174 -107
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +123 -25
- package/src/cache-service.ts +1238 -659
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +202 -129
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +110 -26
- package/src/http/fastify.ts +38 -28
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +132 -57
- package/src/next/index.ts +1 -0
- package/src/next/isr-handler.ts +1 -4
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +65 -27
- package/src/types.ts +27 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
|
@@ -0,0 +1,1519 @@
|
|
|
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
|
+
interface CrossRegionInvalidationEvent {
|
|
219
|
+
/** Unique ID of this invalidation event (UUIDv4) */
|
|
220
|
+
id: string;
|
|
221
|
+
/** Region where the invalidation originated, e.g. 'us-east-1' */
|
|
222
|
+
originRegion: string;
|
|
223
|
+
/** Instance ID that initiated the invalidation */
|
|
224
|
+
originInstanceId: string;
|
|
225
|
+
/** Invalidation operation */
|
|
226
|
+
op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del';
|
|
227
|
+
/** Cache key or tag name */
|
|
228
|
+
key: string;
|
|
229
|
+
/** New tag version for generational tag invalidation */
|
|
230
|
+
tagVersion?: number;
|
|
231
|
+
/** Timestamp when the event was created */
|
|
232
|
+
timestamp: number;
|
|
233
|
+
/** Optional namespace of the origin cache */
|
|
234
|
+
namespace?: string;
|
|
235
|
+
/** Optional W3C traceparent header for distributed context propagation */
|
|
236
|
+
traceparent?: string;
|
|
237
|
+
}
|
|
238
|
+
interface ICrossRegionRelay {
|
|
239
|
+
/**
|
|
240
|
+
* Broadcasts an invalidation event across regions (via HTTP mesh, SNS, SQS, EventBridge, or custom bus).
|
|
241
|
+
*/
|
|
242
|
+
broadcast(event: CrossRegionInvalidationEvent): Promise<void>;
|
|
243
|
+
}
|
|
244
|
+
interface CrossRegionRelayOptions {
|
|
245
|
+
/**
|
|
246
|
+
* Region identifier for this instance, e.g. 'us-east-1' or 'eu-central-1'.
|
|
247
|
+
*/
|
|
248
|
+
currentRegion: string;
|
|
249
|
+
/**
|
|
250
|
+
* Cross-region relay implementation.
|
|
251
|
+
*/
|
|
252
|
+
relay: ICrossRegionRelay;
|
|
253
|
+
/**
|
|
254
|
+
* Optional shared secret or bearer token for authenticating HTTP webhook mesh calls.
|
|
255
|
+
*/
|
|
256
|
+
authSecret?: string;
|
|
257
|
+
/**
|
|
258
|
+
* Max entries stored in the deduplication cache for preventing invalidation loop echoes.
|
|
259
|
+
* Default: 10,000.
|
|
260
|
+
*/
|
|
261
|
+
dedupCacheSize?: number;
|
|
262
|
+
/**
|
|
263
|
+
* Whether writes via `set()` should also broadcast cross-region.
|
|
264
|
+
* Default: `false` (only explicit invalidations `delete()`, `deletePattern()`,
|
|
265
|
+
* and `invalidateTag()` broadcast cross-region, avoiding inter-region thrashing
|
|
266
|
+
* when independent caches populate from local databases).
|
|
267
|
+
*/
|
|
268
|
+
broadcastOnSet?: boolean;
|
|
269
|
+
}
|
|
270
|
+
interface HttpMeshRelayOptions {
|
|
271
|
+
/**
|
|
272
|
+
* Array of peer regional webhook endpoints (e.g. ['https://eu.internal.api/cache/invalidation']).
|
|
273
|
+
*/
|
|
274
|
+
peerUrls: string[];
|
|
275
|
+
/**
|
|
276
|
+
* Optional authentication secret sent in the `Authorization: Bearer <secret>` header.
|
|
277
|
+
*/
|
|
278
|
+
authSecret?: string;
|
|
279
|
+
/**
|
|
280
|
+
* Request timeout in milliseconds for each peer. Default: 3000 ms.
|
|
281
|
+
*/
|
|
282
|
+
timeoutMs?: number;
|
|
283
|
+
/**
|
|
284
|
+
* Optional fetch implementation (defaults to globalThis.fetch).
|
|
285
|
+
*/
|
|
286
|
+
fetchFn?: typeof fetch;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Creates an HTTP-based peer mesh relay using native Node 22 `fetch()`.
|
|
290
|
+
* Broadcasts events concurrently to all configured peer URLs.
|
|
291
|
+
*/
|
|
292
|
+
declare function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegionRelay;
|
|
293
|
+
/**
|
|
294
|
+
* Type-checking helper for custom cross-region relays (AWS SNS/SQS, EventBridge, Kafka, NATS).
|
|
295
|
+
*/
|
|
296
|
+
declare function createCustomCrossRegionRelay(relay: ICrossRegionRelay): ICrossRegionRelay;
|
|
297
|
+
/**
|
|
298
|
+
* In-memory cross-region mesh bus designed for unit testing and multi-region simulations.
|
|
299
|
+
*/
|
|
300
|
+
declare function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
|
|
301
|
+
register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void;
|
|
302
|
+
getBroadcastCount(): number;
|
|
303
|
+
clear(): void;
|
|
304
|
+
};
|
|
305
|
+
interface WebhookRequestLike {
|
|
306
|
+
headers: Record<string, string | string[] | undefined>;
|
|
307
|
+
body: unknown;
|
|
308
|
+
}
|
|
309
|
+
interface WebhookResponseLike {
|
|
310
|
+
status: number;
|
|
311
|
+
body: {
|
|
312
|
+
ok: boolean;
|
|
313
|
+
message?: string;
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Creates a generic webhook handler to receive incoming cross-region invalidation requests.
|
|
318
|
+
* Compatible with Express, Fastify, Next.js route handlers, or Node's `http.createServer`.
|
|
319
|
+
*/
|
|
320
|
+
declare function createCrossRegionWebhookHandler(cache: {
|
|
321
|
+
receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> | boolean;
|
|
322
|
+
}, options?: {
|
|
323
|
+
authSecret?: string;
|
|
324
|
+
}): (req: WebhookRequestLike) => Promise<WebhookResponseLike>;
|
|
325
|
+
|
|
326
|
+
type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
|
|
327
|
+
interface CustomCompressor {
|
|
328
|
+
name: string;
|
|
329
|
+
compress: (buf: Buffer) => Buffer;
|
|
330
|
+
decompress: (buf: Buffer) => Buffer;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Initializes the WebAssembly Zstandard codec.
|
|
334
|
+
* Resolves immediately if already initialized.
|
|
335
|
+
*/
|
|
336
|
+
declare function initZstd(): Promise<any>;
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* tricache — shared types and interfaces
|
|
340
|
+
*/
|
|
341
|
+
/**
|
|
342
|
+
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
343
|
+
* Pass your existing OTEL tracer; no extra package required.
|
|
344
|
+
*/
|
|
345
|
+
interface ICacheSpanLink {
|
|
346
|
+
context: {
|
|
347
|
+
traceId: string;
|
|
348
|
+
spanId: string;
|
|
349
|
+
traceFlags?: number;
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
interface ICacheSpan {
|
|
353
|
+
setAttribute(key: string, value: string | number | boolean): this;
|
|
354
|
+
setStatus(status: {
|
|
355
|
+
code: 0 | 1 | 2;
|
|
356
|
+
message?: string;
|
|
357
|
+
}): this;
|
|
358
|
+
recordException?(err: unknown): void;
|
|
359
|
+
end(): void;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
363
|
+
*/
|
|
364
|
+
interface ICacheTracer {
|
|
365
|
+
startSpan(name: string, options?: {
|
|
366
|
+
links?: ICacheSpanLink[];
|
|
367
|
+
}): ICacheSpan;
|
|
368
|
+
}
|
|
369
|
+
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
370
|
+
interface ILogger {
|
|
371
|
+
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
372
|
+
info(msg: string, meta?: Record<string, unknown>): void;
|
|
373
|
+
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
374
|
+
error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
|
|
375
|
+
}
|
|
376
|
+
/** Default no-op logger — swap out via CacheService options */
|
|
377
|
+
declare const consoleLogger: ILogger;
|
|
378
|
+
/**
|
|
379
|
+
* Reason passed to the `onEviction` callback.
|
|
380
|
+
* - `'capacity'` — L1 over-capacity; evicted during a `set()` call
|
|
381
|
+
* - `'category'` — Per-category limit exceeded
|
|
382
|
+
* - `'rebalance'` — `cache.rebalance()` was called
|
|
383
|
+
* - `'oom'` — OOM guard emergency eviction
|
|
384
|
+
* - `'ttl'` — Entry expired during periodic cleanup
|
|
385
|
+
* - `'manual'` — Explicit `cache.delete()` call
|
|
386
|
+
*/
|
|
387
|
+
type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
|
|
388
|
+
/** Per-tier latency returned by `cache.ping()`. */
|
|
389
|
+
interface CachePingResult {
|
|
390
|
+
/** L1 RAM check latency in milliseconds */
|
|
391
|
+
l1: number;
|
|
392
|
+
/** L1.5 disk stats access in milliseconds */
|
|
393
|
+
disk: number;
|
|
394
|
+
/** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
|
|
395
|
+
l2: number | null;
|
|
396
|
+
}
|
|
397
|
+
/** Priority levels for L1 eviction — higher = less likely to be evicted */
|
|
398
|
+
declare enum CachePriority {
|
|
399
|
+
LOW = 1,// Easily regenerated (analytics, reports)
|
|
400
|
+
NORMAL = 2,// General data
|
|
401
|
+
HIGH = 3,// Frequently accessed (profiles, config)
|
|
402
|
+
CRITICAL = 4
|
|
403
|
+
}
|
|
404
|
+
/** Internal representation of a single cache entry in the L1 Map */
|
|
405
|
+
interface SmartCacheEntry {
|
|
406
|
+
/** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
|
|
407
|
+
data: Buffer;
|
|
408
|
+
/**
|
|
409
|
+
* Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
|
|
410
|
+
* Undefined for entries restored from disk/snapshot (populated lazily on first access).
|
|
411
|
+
* NOTE: returned by reference — callers should treat the value as immutable.
|
|
412
|
+
*/
|
|
413
|
+
value?: unknown;
|
|
414
|
+
/** always true for entries written by the current code;
|
|
415
|
+
* may be false in legacy snapshots/disk files — handled transparently on import */
|
|
416
|
+
isCompressed: boolean;
|
|
417
|
+
/** Hard expiry — entry is deleted after this timestamp */
|
|
418
|
+
expiresAt: number;
|
|
419
|
+
/** SWR soft expiry — serve stale + revalidate in background when past this */
|
|
420
|
+
staleAt?: number;
|
|
421
|
+
/** Exact byte size of the stored value */
|
|
422
|
+
size: number;
|
|
423
|
+
/** Access count (LFU numerator) */
|
|
424
|
+
hits: number;
|
|
425
|
+
/** Last access timestamp (LRU comparator) */
|
|
426
|
+
lastAccess: number;
|
|
427
|
+
/** Eviction priority */
|
|
428
|
+
priority: CachePriority;
|
|
429
|
+
/** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
|
|
430
|
+
ttlMs?: number;
|
|
431
|
+
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
432
|
+
delta?: number;
|
|
433
|
+
/**
|
|
434
|
+
* Unix timestamp (ms) when this entry was written.
|
|
435
|
+
* Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
|
|
436
|
+
* instead of approximating via `expiresAt - ttlMs`.
|
|
437
|
+
* Optional for backward compatibility with snapshots written by older versions.
|
|
438
|
+
*/
|
|
439
|
+
setAt?: number;
|
|
440
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
441
|
+
tagVersions?: Record<string, number>;
|
|
442
|
+
/** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
|
|
443
|
+
tags?: string[];
|
|
444
|
+
dependsOn?: string[];
|
|
445
|
+
}
|
|
446
|
+
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
447
|
+
interface CacheHit {
|
|
448
|
+
value: unknown;
|
|
449
|
+
/** true = past soft TTL (staleAt) but within hard expiry → SWR path */
|
|
450
|
+
isStale: boolean;
|
|
451
|
+
/** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
|
|
452
|
+
* without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
|
|
453
|
+
expiresAt: number;
|
|
454
|
+
/** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
|
|
455
|
+
ttlMs?: number;
|
|
456
|
+
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
457
|
+
delta?: number;
|
|
458
|
+
/** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
|
|
459
|
+
* reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
|
|
460
|
+
fetchedAt?: number;
|
|
461
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
462
|
+
tagVersions?: Record<string, number>;
|
|
463
|
+
/** Timestamp (ms) when this entry was written into memory */
|
|
464
|
+
setAt?: number;
|
|
465
|
+
tags?: string[];
|
|
466
|
+
dependsOn?: string[];
|
|
467
|
+
}
|
|
468
|
+
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
469
|
+
* legacy disk files written by older versions may have a JSON string in data) */
|
|
470
|
+
interface DiskCacheEntry {
|
|
471
|
+
data: string | Buffer | Uint8Array;
|
|
472
|
+
isCompressed: boolean;
|
|
473
|
+
expiresAt: number;
|
|
474
|
+
staleAt?: number;
|
|
475
|
+
size: number;
|
|
476
|
+
hits: number;
|
|
477
|
+
lastAccess: number;
|
|
478
|
+
priority: number;
|
|
479
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
480
|
+
tagVersions?: Record<string, number>;
|
|
481
|
+
/** Original write time and TTL, preserved on spill and promotion. */
|
|
482
|
+
setAt?: number;
|
|
483
|
+
ttlMs?: number;
|
|
484
|
+
delta?: number;
|
|
485
|
+
tags?: string[];
|
|
486
|
+
dependsOn?: string[];
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Snapshot of runtime metrics for a CacheService instance.
|
|
490
|
+
* Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
|
|
491
|
+
* Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
|
|
492
|
+
*/
|
|
493
|
+
interface CacheMetrics {
|
|
494
|
+
/** Configured namespace (empty string = no namespace) */
|
|
495
|
+
namespace: string;
|
|
496
|
+
/** Milliseconds since the CacheService instance was constructed */
|
|
497
|
+
uptimeMs: number;
|
|
498
|
+
gets: {
|
|
499
|
+
total: number;
|
|
500
|
+
l1Hits: number;
|
|
501
|
+
/** Fraction of gets served from L1 RAM cache (0–1) */
|
|
502
|
+
l1HitRate: number;
|
|
503
|
+
diskHits: number;
|
|
504
|
+
/** Fraction of gets served from L1.5 disk tier (0–1) */
|
|
505
|
+
diskHitRate: number;
|
|
506
|
+
l2Hits: number;
|
|
507
|
+
/** Fraction of gets served from L2 Redis (0–1) */
|
|
508
|
+
l2HitRate: number;
|
|
509
|
+
/** fetchFn calls (cache misses that fell through to the DB) */
|
|
510
|
+
fetches: number;
|
|
511
|
+
/** Fraction of gets that called fetchFn (0–1) */
|
|
512
|
+
fetchRate: number;
|
|
513
|
+
/** Concurrent get() calls deduplicated by the stampede guard */
|
|
514
|
+
stampedePrevented: number;
|
|
515
|
+
};
|
|
516
|
+
sets: {
|
|
517
|
+
total: number;
|
|
518
|
+
};
|
|
519
|
+
deletes: {
|
|
520
|
+
total: number;
|
|
521
|
+
};
|
|
522
|
+
revalidations: {
|
|
523
|
+
total: number;
|
|
524
|
+
};
|
|
525
|
+
/** Rate-limit / singleton diagnostics */
|
|
526
|
+
counters: {
|
|
527
|
+
/** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
|
|
528
|
+
errors: number;
|
|
529
|
+
/** Times a later `create(ns)` call passed options diverging from the live singleton. */
|
|
530
|
+
singletonDivergences: number;
|
|
531
|
+
};
|
|
532
|
+
bloom: {
|
|
533
|
+
/** Total bloom-filter checks (get() calls that passed prefix filter) */
|
|
534
|
+
checksTotal: number;
|
|
535
|
+
/**
|
|
536
|
+
* Times the filter said "might contain" but the key was absent in L1.
|
|
537
|
+
* A high rate suggests the bloom filter capacity needs increasing.
|
|
538
|
+
*/
|
|
539
|
+
falsePositives: number;
|
|
540
|
+
/** falsePositives / checksTotal (0–1; ideal < 0.01) */
|
|
541
|
+
falsePositiveRate: number;
|
|
542
|
+
};
|
|
543
|
+
compression: {
|
|
544
|
+
entriesCompressed: number;
|
|
545
|
+
entriesUncompressed: number;
|
|
546
|
+
/** Approximate bytes saved by msgpackr vs raw JSON */
|
|
547
|
+
bytesSaved: number;
|
|
548
|
+
};
|
|
549
|
+
/** Invalidation backplane statistics */
|
|
550
|
+
backplane: {
|
|
551
|
+
enabled: boolean;
|
|
552
|
+
mode: 'pubsub' | 'stream';
|
|
553
|
+
/** Invalidation messages published to other instances */
|
|
554
|
+
sent: number;
|
|
555
|
+
/** Invalidation messages received from other instances */
|
|
556
|
+
received: number;
|
|
557
|
+
/** Own messages silently skipped (prevents double-eviction) */
|
|
558
|
+
skipped: number;
|
|
559
|
+
/** Stream entries received (when backplaneMode is 'stream') */
|
|
560
|
+
streamEntriesReceived?: number;
|
|
561
|
+
/** Replayed invalidations after network reconnect */
|
|
562
|
+
streamReplays?: number;
|
|
563
|
+
/** Stream trim gaps detected (where consumer fell behind oldest entry) */
|
|
564
|
+
streamGaps?: number;
|
|
565
|
+
};
|
|
566
|
+
/** L2 Redis circuit breaker state */
|
|
567
|
+
l2CircuitBreaker: {
|
|
568
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
569
|
+
state: 'closed' | 'open' | 'half_open';
|
|
570
|
+
};
|
|
571
|
+
/** OOM guard statistics */
|
|
572
|
+
oom: {
|
|
573
|
+
enabled: boolean;
|
|
574
|
+
/** Number of emergency L1 eviction rounds triggered */
|
|
575
|
+
evictions: number;
|
|
576
|
+
/** Timestamp of the most recent OOM eviction, or null */
|
|
577
|
+
lastTriggeredAt: number | null;
|
|
578
|
+
};
|
|
579
|
+
/** Remote snapshot statistics — present when remoteSnapshot is configured */
|
|
580
|
+
remoteSnapshot?: {
|
|
581
|
+
enabled: boolean;
|
|
582
|
+
uploads: number;
|
|
583
|
+
downloads: number;
|
|
584
|
+
errors: number;
|
|
585
|
+
lastUploadedAt: number | null;
|
|
586
|
+
lastDownloadedAt: number | null;
|
|
587
|
+
};
|
|
588
|
+
/** Cross-region invalidation relay statistics — present when crossRegion is configured */
|
|
589
|
+
crossRegion?: {
|
|
590
|
+
enabled: boolean;
|
|
591
|
+
currentRegion: string;
|
|
592
|
+
sent: number;
|
|
593
|
+
received: number;
|
|
594
|
+
deduplicated: number;
|
|
595
|
+
errors: number;
|
|
596
|
+
};
|
|
597
|
+
/** Auto-pipelining statistics — present when autoPipeline is enabled */
|
|
598
|
+
pipelining?: {
|
|
599
|
+
batchesDispatched: number;
|
|
600
|
+
operationsBatched: number;
|
|
601
|
+
pendingQueueSize: number;
|
|
602
|
+
};
|
|
603
|
+
l1: {
|
|
604
|
+
entries: number;
|
|
605
|
+
sizeBytes: number;
|
|
606
|
+
maxBytes: number;
|
|
607
|
+
};
|
|
608
|
+
disk: {
|
|
609
|
+
files: number;
|
|
610
|
+
sizeKB: number;
|
|
611
|
+
maxKB: number;
|
|
612
|
+
disabled: boolean;
|
|
613
|
+
latencyWatchdog?: {
|
|
614
|
+
bypassActive: boolean;
|
|
615
|
+
bypassStage: 0 | 1 | 2 | 3;
|
|
616
|
+
diskP95Ms: number;
|
|
617
|
+
redisP95Ms: number;
|
|
618
|
+
redisDampened: boolean;
|
|
619
|
+
bypassedTotal: number;
|
|
620
|
+
};
|
|
621
|
+
pruning?: {
|
|
622
|
+
active: boolean;
|
|
623
|
+
pruneRounds: number;
|
|
624
|
+
entriesPruned: number;
|
|
625
|
+
spillsShedTotal: number;
|
|
626
|
+
hostVolumeLowSpacePauses: number;
|
|
627
|
+
};
|
|
628
|
+
};
|
|
629
|
+
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
630
|
+
adaptiveTtl?: {
|
|
631
|
+
enabled: true;
|
|
632
|
+
/** Number of unique keys currently tracked in the latency ring buffers */
|
|
633
|
+
trackedKeys: number;
|
|
634
|
+
/**
|
|
635
|
+
* Top-20 slowest keys by p95 fetch latency, sorted descending.
|
|
636
|
+
* Keys are shown without the instance namespace prefix.
|
|
637
|
+
* Only keys with ≥ 5 recorded samples appear here.
|
|
638
|
+
*/
|
|
639
|
+
slowestKeys: Array<{
|
|
640
|
+
key: string;
|
|
641
|
+
p95Ms: number;
|
|
642
|
+
adaptedTtlSec: number;
|
|
643
|
+
}>;
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Result returned by cache.health()
|
|
648
|
+
*
|
|
649
|
+
* NOTE: Intended strictly for Kubernetes Readiness probes (/ready).
|
|
650
|
+
* Do NOT hook into Liveness probes (/healthz), as degraded caches should shed ingress
|
|
651
|
+
* traffic while keeping the container alive to heal local storage and drain in-flight tasks.
|
|
652
|
+
*/
|
|
653
|
+
interface CacheHealthStatus {
|
|
654
|
+
healthy: boolean;
|
|
655
|
+
degraded: boolean;
|
|
656
|
+
reasons: string[];
|
|
657
|
+
details?: Record<string, unknown>;
|
|
658
|
+
}
|
|
659
|
+
/** Per-category memory limits for L1 */
|
|
660
|
+
interface CategoryLimit {
|
|
661
|
+
maxEntries: number;
|
|
662
|
+
maxSizeBytes: number;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Supported opinionated pre-configurations for CacheService.preset()
|
|
666
|
+
*/
|
|
667
|
+
type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened';
|
|
668
|
+
/**
|
|
669
|
+
* Options accepted by CacheService.create()
|
|
670
|
+
*
|
|
671
|
+
* All fields are optional — sensible defaults are used when omitted.
|
|
672
|
+
*/
|
|
673
|
+
interface CacheOptions {
|
|
674
|
+
/**
|
|
675
|
+
* Plug in your own logger (pino, winston, bunyan, …).
|
|
676
|
+
* Defaults to a minimal console logger that only prints warn/error.
|
|
677
|
+
*/
|
|
678
|
+
logger?: ILogger;
|
|
679
|
+
/** Max total bytes held in L1 RAM cache. Default: 200 MB */
|
|
680
|
+
l1MaxBytes?: number;
|
|
681
|
+
/** Max total entries in L1. Default: 2000 */
|
|
682
|
+
l1MaxEntries?: number;
|
|
683
|
+
/**
|
|
684
|
+
* Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
|
|
685
|
+
* before the hard limit is reached. Range: 0–1. Default: 0.9.
|
|
686
|
+
* Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
|
|
687
|
+
*/
|
|
688
|
+
l1EvictionWatermark?: number;
|
|
689
|
+
/**
|
|
690
|
+
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
691
|
+
* Merged over the built-in defaults.
|
|
692
|
+
*/
|
|
693
|
+
categoryLimits?: Record<string, CategoryLimit>;
|
|
694
|
+
/**
|
|
695
|
+
* Key prefixes that are never written to disk snapshots or the disk tier.
|
|
696
|
+
* Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
|
|
697
|
+
*/
|
|
698
|
+
forbiddenSnapshotPrefixes?: string[];
|
|
699
|
+
/**
|
|
700
|
+
* L1 cache admission and eviction policy:
|
|
701
|
+
* - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
|
|
702
|
+
* mathematical scan resistance and burst recency absorption.
|
|
703
|
+
* - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
|
|
704
|
+
* Default: `'wtinylfu'`
|
|
705
|
+
*/
|
|
706
|
+
l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
|
|
707
|
+
/** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
|
|
708
|
+
diskCacheDir?: string;
|
|
709
|
+
/** Max total bytes for the disk tier. Default: 500 MB */
|
|
710
|
+
diskMaxBytes?: number;
|
|
711
|
+
/** Max bytes for a single disk entry. Default: 10 MB */
|
|
712
|
+
diskEntryMaxBytes?: number;
|
|
713
|
+
/**
|
|
714
|
+
* Maximum concurrent asynchronous filesystem writes permitted in-flight for disk spills.
|
|
715
|
+
* Protects against libuv threadpool (UV_THREADPOOL_SIZE=4) saturation during cloud I/O throttling.
|
|
716
|
+
* Default: Math.min(4, Math.max(1, Math.floor(os.availableParallelism() / 4)))
|
|
717
|
+
*/
|
|
718
|
+
diskMaxConcurrentWrites?: number;
|
|
719
|
+
/**
|
|
720
|
+
* Maximum queued spill writes awaiting execution before shedding kicks in.
|
|
721
|
+
* Once pending writes hit this limit, incoming spills are dropped without touching libuv.
|
|
722
|
+
* Default: 512
|
|
723
|
+
*/
|
|
724
|
+
diskMaxPendingWrites?: number;
|
|
725
|
+
/**
|
|
726
|
+
* Maximum time permitted for an individual write before timing out and tripping backpressure.
|
|
727
|
+
* Default: 500 ms
|
|
728
|
+
*/
|
|
729
|
+
diskWriteTimeoutMs?: number;
|
|
730
|
+
/**
|
|
731
|
+
* Number of consecutive slow or failed disk writes before tripping the disk circuit breaker to OPEN.
|
|
732
|
+
* Default: 5
|
|
733
|
+
*/
|
|
734
|
+
diskCircuitBreakerThreshold?: number;
|
|
735
|
+
/**
|
|
736
|
+
* Cooldown time in ms before transitioning the disk circuit breaker from OPEN to HALF-OPEN for canary probing.
|
|
737
|
+
* Default: 5000 ms
|
|
738
|
+
*/
|
|
739
|
+
diskCircuitBreakerCooldownMs?: number;
|
|
740
|
+
/**
|
|
741
|
+
* Enable dynamic tier latency watchdog.
|
|
742
|
+
* Compares disk read latency against Redis and automatically sheds traffic to Redis when disk slows down.
|
|
743
|
+
* Default: true
|
|
744
|
+
*/
|
|
745
|
+
diskLatencyWatchdog?: boolean;
|
|
746
|
+
/**
|
|
747
|
+
* Ratio of disk p95 latency to Redis p95 latency required to trip bypass.
|
|
748
|
+
* Default: 1.5
|
|
749
|
+
*/
|
|
750
|
+
diskLatencyBypassRatio?: number;
|
|
751
|
+
/**
|
|
752
|
+
* Minimum disk p95 latency floor in ms before bypass can be considered.
|
|
753
|
+
* Default: 10 ms
|
|
754
|
+
*/
|
|
755
|
+
diskLatencyBypassMinMs?: number;
|
|
756
|
+
/**
|
|
757
|
+
* Cooldown time in ms before probing canary during Stage 3 bypass.
|
|
758
|
+
* Subject to ±30% anti-synchronicity jitter.
|
|
759
|
+
* Default: 30_000 ms
|
|
760
|
+
*/
|
|
761
|
+
diskLatencyBypassCooldownMs?: number;
|
|
762
|
+
/**
|
|
763
|
+
* When true, cache.health().healthy returns false when degraded, causing
|
|
764
|
+
* Kubernetes readiness probes to fail and route traffic away from this pod.
|
|
765
|
+
* Default: false (graceful local degradation without failing readiness)
|
|
766
|
+
*/
|
|
767
|
+
failReadinessOnDegraded?: boolean;
|
|
768
|
+
/**
|
|
769
|
+
* Redis/Valkey hostname (no `redis://` prefix).
|
|
770
|
+
* Falls back to the `REDIS_HOST` environment variable.
|
|
771
|
+
* When neither is provided, L2 is disabled.
|
|
772
|
+
*/
|
|
773
|
+
redisHost?: string;
|
|
774
|
+
/** Redis port. Default: 6379 */
|
|
775
|
+
redisPort?: number;
|
|
776
|
+
/**
|
|
777
|
+
* Strict per-command timeout for Redis operations.
|
|
778
|
+
* When expired, triggers connection reset / socket destruction to prevent RESP multiplexing desync.
|
|
779
|
+
* Default: 2500 ms
|
|
780
|
+
*/
|
|
781
|
+
redisCommandTimeoutMs?: number;
|
|
782
|
+
/**
|
|
783
|
+
* Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
|
|
784
|
+
* Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
|
|
785
|
+
* Default: false
|
|
786
|
+
*/
|
|
787
|
+
autoPipeline?: boolean;
|
|
788
|
+
/**
|
|
789
|
+
* Maximum batch size for auto-pipelined Redis requests before forcing an immediate dispatch.
|
|
790
|
+
* Default: 100
|
|
791
|
+
*/
|
|
792
|
+
maxPipelineBatchSize?: number;
|
|
793
|
+
/**
|
|
794
|
+
* Clock skew tolerance window in milliseconds across cluster nodes / containers.
|
|
795
|
+
* Allows timestamps within this tolerance ahead of the local clock to prevent premature eviction anomalies.
|
|
796
|
+
* Default: 250 ms
|
|
797
|
+
*/
|
|
798
|
+
clockSkewToleranceMs?: number;
|
|
799
|
+
/**
|
|
800
|
+
* Whether to enable TLS for the Redis connection. Default: true in production,
|
|
801
|
+
* false otherwise.
|
|
802
|
+
*/
|
|
803
|
+
redisTls?: boolean;
|
|
804
|
+
/**
|
|
805
|
+
* Redis wire protocol version (RESP2 or RESP3).
|
|
806
|
+
* Defaults to 3 in ioredis v6+. Set to 2 for legacy proxies or servers without RESP3 support.
|
|
807
|
+
*/
|
|
808
|
+
redisProtocol?: 2 | 3;
|
|
809
|
+
/**
|
|
810
|
+
* Set to `true` to disable L2 Redis entirely (e.g. when running single-process
|
|
811
|
+
* services that don't need distributed caching). Default: false in production,
|
|
812
|
+
* true in development.
|
|
813
|
+
*/
|
|
814
|
+
disableRedis?: boolean;
|
|
815
|
+
/**
|
|
816
|
+
* Pre-existing or custom Redis client or driver adapter (e.g. `NodeRedisAdapter` wrapping
|
|
817
|
+
* `@redis/client`, or a pre-configured `ioredis` instance).
|
|
818
|
+
* When supplied, TriCache bypasses internal connection construction and uses this client directly.
|
|
819
|
+
*/
|
|
820
|
+
redisClient?: IRedisDriver | any;
|
|
821
|
+
/**
|
|
822
|
+
* Dedicated subscriber client for Redis Pub/Sub invalidation backplane.
|
|
823
|
+
* If omitted and `redisClient` supports `.duplicate()`, TriCache will duplicate `redisClient`.
|
|
824
|
+
*/
|
|
825
|
+
redisSubClient?: IRedisDriver | any;
|
|
826
|
+
/**
|
|
827
|
+
* Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
|
|
828
|
+
* disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
|
|
829
|
+
* If not provided in production, a warning is logged and data is stored plaintext.
|
|
830
|
+
*/
|
|
831
|
+
encryptionKey?: string;
|
|
832
|
+
/**
|
|
833
|
+
* Encryption algorithm used for L2 (Redis) values and disk-tier files.
|
|
834
|
+
* - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
|
|
835
|
+
* - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
|
|
836
|
+
* - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
|
|
837
|
+
* Any key length (minimum 16 bytes recommended).
|
|
838
|
+
* Use for dev environments or non-sensitive data only.
|
|
839
|
+
* Default: `'aes-256-gcm'`
|
|
840
|
+
*/
|
|
841
|
+
encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
842
|
+
/**
|
|
843
|
+
* Fallback encryption key for zero-downtime key rotation.
|
|
844
|
+
* On every read, tricache tries the current `encryptionKey` first.
|
|
845
|
+
* If decryption fails (wrong key), it retries with `previousEncryptionKey`.
|
|
846
|
+
* All writes always use the current `encryptionKey`.
|
|
847
|
+
* Remove this field once you are confident all data has been re-encrypted.
|
|
848
|
+
*/
|
|
849
|
+
previousEncryptionKey?: string;
|
|
850
|
+
/** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
|
|
851
|
+
previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
852
|
+
/**
|
|
853
|
+
* Fail closed when `encryptionKey` is present but INVALID (wrong length for the
|
|
854
|
+
* selected `encryptionMode`, or empty). Default: `false` — tricache logs an error
|
|
855
|
+
* and continues with at-rest encryption DISABLED (fail-open, backward compatible).
|
|
856
|
+
* Set to `true` for deployments where serving plaintext at rest is unacceptable:
|
|
857
|
+
* the constructor then throws instead of silently downgrading security.
|
|
858
|
+
* Has no effect when no key is configured at all (encryption stays off, by design).
|
|
859
|
+
*/
|
|
860
|
+
strictKeyValidation?: boolean;
|
|
861
|
+
/**
|
|
862
|
+
* Whether to call `.toJSON()` when serializing objects into binary cache buffers.
|
|
863
|
+
* - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
|
|
864
|
+
* - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
|
|
865
|
+
* avoiding accidental API response projections on cached domain entities.
|
|
866
|
+
*/
|
|
867
|
+
serializeToJSON?: boolean;
|
|
868
|
+
/**
|
|
869
|
+
* Compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
|
|
870
|
+
* - `'zstd'` (default) — Facebook Zstandard (via WebAssembly) for ultra-high throughput and ~96% ratio.
|
|
871
|
+
* - `'lz4'` — Ultra-fast compression/decompression for high-throughput, latency-critical workloads.
|
|
872
|
+
* - `'brotli'` — High compression ratio for JSON / text payloads.
|
|
873
|
+
* - `'gzip'` — Standard Deflate/Gzip compression.
|
|
874
|
+
* - `'none'` — disable compression.
|
|
875
|
+
* Default: `'zstd'`.
|
|
876
|
+
*/
|
|
877
|
+
compression?: CompressionAlgorithm;
|
|
878
|
+
/**
|
|
879
|
+
* Custom compression engine plugin. When provided, overrides the built-in algorithms
|
|
880
|
+
* and delegates compression/decompression to this provider.
|
|
881
|
+
*/
|
|
882
|
+
customCompressor?: CustomCompressor;
|
|
883
|
+
/**
|
|
884
|
+
* Minimum payload size in bytes before compression is applied.
|
|
885
|
+
* Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
|
|
886
|
+
* Default: `1024` (1 KB).
|
|
887
|
+
*/
|
|
888
|
+
compressionThresholdBytes?: number;
|
|
889
|
+
/**
|
|
890
|
+
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
891
|
+
* on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
|
|
892
|
+
*/
|
|
893
|
+
snapshotPath?: string;
|
|
894
|
+
/**
|
|
895
|
+
* Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
|
|
896
|
+
*/
|
|
897
|
+
snapshotMaxAgeMs?: number;
|
|
898
|
+
/**
|
|
899
|
+
* Optional remote blob storage snapshot configuration for stateless containers (S3, GCS, R2, HTTP).
|
|
900
|
+
* Enables persisting and hydrating L1 RAM cache snapshots across Kubernetes / container deployments.
|
|
901
|
+
*/
|
|
902
|
+
remoteSnapshot?: RemoteSnapshotOptions;
|
|
903
|
+
/**
|
|
904
|
+
* Optional namespace prefix for all cache keys.
|
|
905
|
+
*
|
|
906
|
+
* When set, every key is transparently stored as `${namespace}:${key}` in
|
|
907
|
+
* L1, L1.5 (disk), and L2 (Redis). This enables:
|
|
908
|
+
* - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
|
|
909
|
+
* — tenants sharing the same Redis instance or disk dir are fully isolated.
|
|
910
|
+
* - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
|
|
911
|
+
* - **Service-level scoping**: microservices sharing one Redis without key collisions.
|
|
912
|
+
*
|
|
913
|
+
* Consumers never see the prefix — `get('user:1')` behaves identically
|
|
914
|
+
* whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
|
|
915
|
+
* scope to the namespace.
|
|
916
|
+
*
|
|
917
|
+
* The process-level singleton, disk cache directory, and cold-start snapshot
|
|
918
|
+
* path are all scoped per namespace, so two `CacheService.create()` calls
|
|
919
|
+
* with different namespaces return completely independent instances.
|
|
920
|
+
*
|
|
921
|
+
* Default: `''` (no prefix)
|
|
922
|
+
*/
|
|
923
|
+
namespace?: string;
|
|
924
|
+
/**
|
|
925
|
+
* Seconds to extend a stale SWR entry's life when background revalidation fails.
|
|
926
|
+
* Without this, a failed revalidation leaves the entry stale until its hard TTL
|
|
927
|
+
* expires, after which the next caller blocks. With `staleIfError`, tricache bumps
|
|
928
|
+
* the expiry by this many seconds on every failed revalidation, keeping the stale
|
|
929
|
+
* value available while the underlying service is degraded.
|
|
930
|
+
* Default: `0` (disabled — entry expires normally on revalidation failure).
|
|
931
|
+
*/
|
|
932
|
+
staleIfError?: number;
|
|
933
|
+
/**
|
|
934
|
+
* Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
|
|
935
|
+
* Useful for diagnosing cache pressure and tuning `categoryLimits`.
|
|
936
|
+
*/
|
|
937
|
+
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
938
|
+
/**
|
|
939
|
+
* Human-readable name for this CacheService instance. Added as an `instance` label
|
|
940
|
+
* to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
|
|
941
|
+
* Required when multiple CacheService instances share a process — without it,
|
|
942
|
+
* metric names from different instances collide.
|
|
943
|
+
* Default: `''` (no label).
|
|
944
|
+
*/
|
|
945
|
+
instanceName?: string;
|
|
946
|
+
/**
|
|
947
|
+
* Controls whether writes are propagated to L2 (Redis).
|
|
948
|
+
* - `'read-write'` (default): read from and write to L2.
|
|
949
|
+
* - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
|
|
950
|
+
* Use for shared read replicas or external Redis clusters you do not own.
|
|
951
|
+
*/
|
|
952
|
+
l2WriteMode?: 'read-write' | 'read-only';
|
|
953
|
+
/**
|
|
954
|
+
* Enable Redis Pub/Sub invalidation backplane so every running instance
|
|
955
|
+
* evicts a key from its L1 when any peer calls `set()` or `delete()`.
|
|
956
|
+
*
|
|
957
|
+
* Gives you sub-microsecond in-process cache speed with cluster-wide
|
|
958
|
+
* consistency across all your app servers.
|
|
959
|
+
*
|
|
960
|
+
* Default: `true` (auto-activates when Redis is available).
|
|
961
|
+
* Set to `false` for single-process services or eventual-consistency scenarios.
|
|
962
|
+
*/
|
|
963
|
+
invalidationBackplane?: boolean;
|
|
964
|
+
/**
|
|
965
|
+
* Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
|
|
966
|
+
* a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
|
|
967
|
+
* to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
|
|
968
|
+
*
|
|
969
|
+
* Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
|
|
970
|
+
*/
|
|
971
|
+
useShardedPubSub?: boolean;
|
|
972
|
+
/**
|
|
973
|
+
* If true, await backplane invalidation broadcasts during delete(), set(),
|
|
974
|
+
* clear(), and invalidateTag() operations rather than firing them in the background.
|
|
975
|
+
* Guarantees that remote cluster nodes receive the invalidation before the
|
|
976
|
+
* operation resolves to the caller.
|
|
977
|
+
*
|
|
978
|
+
* Default: `false` (asynchronous fire-and-forget for minimal caller latency).
|
|
979
|
+
*/
|
|
980
|
+
awaitInvalidationBackplane?: boolean;
|
|
981
|
+
/**
|
|
982
|
+
* If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
|
|
983
|
+
* encounters a connection or runtime error during lock acquisition, preventing
|
|
984
|
+
* split-brain concurrent execution across multiple cluster nodes.
|
|
985
|
+
*
|
|
986
|
+
* Default: `false` (falls back to local in-process mutex with a debug log).
|
|
987
|
+
*/
|
|
988
|
+
lockFailClosed?: boolean;
|
|
989
|
+
/**
|
|
990
|
+
* Optional cross-region invalidation relay configuration for geo-distributed deployments.
|
|
991
|
+
* Synchronizes `delete()` and `invalidateTag()` events across separate regional Redis clusters
|
|
992
|
+
* (e.g. `us-east-1` and `eu-central-1`) via HTTP mesh or custom message brokers (SNS, SQS, EventBridge)
|
|
993
|
+
* with automatic origin deduplication to prevent invalidation loops.
|
|
994
|
+
*/
|
|
995
|
+
crossRegion?: CrossRegionRelayOptions;
|
|
996
|
+
/**
|
|
997
|
+
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
998
|
+
* `oomHeapThreshold`, a fraction of the coldest L1 entries are
|
|
999
|
+
* emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
|
|
1000
|
+
* Docker/Kubernetes containers with tight memory limits.
|
|
1001
|
+
*
|
|
1002
|
+
* Default: `true`
|
|
1003
|
+
*/
|
|
1004
|
+
oomProtection?: boolean;
|
|
1005
|
+
/**
|
|
1006
|
+
* Heap-used / heap-total ratio that triggers emergency eviction.
|
|
1007
|
+
* Default: `0.85` (85 %)
|
|
1008
|
+
*/
|
|
1009
|
+
oomHeapThreshold?: number;
|
|
1010
|
+
/** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
|
|
1011
|
+
oomCheckIntervalMs?: number;
|
|
1012
|
+
/** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
|
|
1013
|
+
oomEvictPercent?: number;
|
|
1014
|
+
/**
|
|
1015
|
+
* Callback invoked periodically with a `CacheMetrics` snapshot.
|
|
1016
|
+
* Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
|
|
1017
|
+
*
|
|
1018
|
+
* @example
|
|
1019
|
+
* onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
|
|
1020
|
+
*/
|
|
1021
|
+
onMetrics?: (metrics: CacheMetrics) => void;
|
|
1022
|
+
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
1023
|
+
metricsIntervalMs?: number;
|
|
1024
|
+
/**
|
|
1025
|
+
* Enable local IPC telemetry server (Unix domain socket on POSIX, Windows Named Pipe on win32)
|
|
1026
|
+
* allowing external monitors like `tricache top` to inspect this instance.
|
|
1027
|
+
* Default: `false`.
|
|
1028
|
+
*/
|
|
1029
|
+
enableIpc?: boolean;
|
|
1030
|
+
/**
|
|
1031
|
+
* Custom socket path or Windows named pipe path for the IPC telemetry server.
|
|
1032
|
+
* Default: `/tmp/tricache-<pid>.sock` (POSIX) or `\\.\pipe\tricache-<pid>` (Windows).
|
|
1033
|
+
*/
|
|
1034
|
+
ipcSocketPath?: string;
|
|
1035
|
+
/**
|
|
1036
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
1037
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
1038
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
1039
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
1040
|
+
*
|
|
1041
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
1042
|
+
* dependency required; the interface is structurally compatible.
|
|
1043
|
+
*
|
|
1044
|
+
* @example
|
|
1045
|
+
* import { trace } from '@opentelemetry/api';
|
|
1046
|
+
* tracer: trace.getTracer('tricache')
|
|
1047
|
+
*/
|
|
1048
|
+
tracer?: ICacheTracer;
|
|
1049
|
+
/**
|
|
1050
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
1051
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
1052
|
+
* the same TTL and expire simultaneously.
|
|
1053
|
+
*
|
|
1054
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
1055
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
1056
|
+
*/
|
|
1057
|
+
ttlJitterFactor?: number;
|
|
1058
|
+
/**
|
|
1059
|
+
* Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
|
|
1060
|
+
* Caches negative results so a non-existent key (deleted user, bad ID) does not
|
|
1061
|
+
* hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
|
|
1062
|
+
* Default: `0` (disabled — null/undefined uses the normal TTL).
|
|
1063
|
+
*/
|
|
1064
|
+
notFoundTtl?: number;
|
|
1065
|
+
/**
|
|
1066
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
1067
|
+
* attempting Redis until the cooldown elapses).
|
|
1068
|
+
* Default: `5`.
|
|
1069
|
+
*/
|
|
1070
|
+
l2CircuitBreakerThreshold?: number;
|
|
1071
|
+
/**
|
|
1072
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
1073
|
+
* (allows a single probe request to test recovery).
|
|
1074
|
+
* Default: `30 000` ms (30 s).
|
|
1075
|
+
*/
|
|
1076
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
1077
|
+
/**
|
|
1078
|
+
* Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
|
|
1079
|
+
* `cache.ready()` returns a Promise that resolves once this warm-up completes.
|
|
1080
|
+
* No-op when Redis is disabled or unreachable — safe to set unconditionally.
|
|
1081
|
+
*/
|
|
1082
|
+
warmKeys?: string;
|
|
1083
|
+
/**
|
|
1084
|
+
* Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
|
|
1085
|
+
* namespace prefix) and the tier that served it. Useful for per-route hit-rate
|
|
1086
|
+
* metrics without waiting for the `onMetrics` interval.
|
|
1087
|
+
*
|
|
1088
|
+
* @example
|
|
1089
|
+
* onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
|
|
1090
|
+
*/
|
|
1091
|
+
onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
|
|
1092
|
+
/**
|
|
1093
|
+
* Called on every cache miss (after L1, disk, and L2 are all exhausted).
|
|
1094
|
+
* Receives the caller-facing key (no namespace prefix).
|
|
1095
|
+
*
|
|
1096
|
+
* @example
|
|
1097
|
+
* onMiss: (key) => cloudwatch.putMetricData({ key })
|
|
1098
|
+
*/
|
|
1099
|
+
onMiss?: (key: string) => void;
|
|
1100
|
+
/**
|
|
1101
|
+
* When `true`, every value returned from an L1 cache hit is recursively
|
|
1102
|
+
* frozen with `Object.freeze()` before being handed to the caller.
|
|
1103
|
+
* Any attempt to mutate the returned object throws a `TypeError` immediately,
|
|
1104
|
+
* catching reference-semantic corruption bugs that would otherwise silently
|
|
1105
|
+
* corrupt the cached entry.
|
|
1106
|
+
*
|
|
1107
|
+
* **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
|
|
1108
|
+
* Deep-freezing large objects has measurable overhead per hit.
|
|
1109
|
+
*
|
|
1110
|
+
* @example
|
|
1111
|
+
* frozen: process.env.NODE_ENV !== 'production'
|
|
1112
|
+
*/
|
|
1113
|
+
frozen?: boolean;
|
|
1114
|
+
/**
|
|
1115
|
+
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
1116
|
+
* and automatically derives an optimal TTL from the p95 fetch duration:
|
|
1117
|
+
*
|
|
1118
|
+
* ```
|
|
1119
|
+
* adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
|
|
1120
|
+
* ```
|
|
1121
|
+
*
|
|
1122
|
+
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
1123
|
+
* for a key, then the library takes over TTL management autonomously.
|
|
1124
|
+
*
|
|
1125
|
+
* Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
|
|
1126
|
+
* their base TTL. Callers no longer need to reason about individual TTL values.
|
|
1127
|
+
*
|
|
1128
|
+
* Default: `false`.
|
|
1129
|
+
*/
|
|
1130
|
+
adaptiveTtl?: boolean;
|
|
1131
|
+
/**
|
|
1132
|
+
* Minimum TTL (seconds) the adaptive tuner will ever assign.
|
|
1133
|
+
* Guards against extremely fast fetches producing near-zero TTLs.
|
|
1134
|
+
* Default: `10`.
|
|
1135
|
+
*/
|
|
1136
|
+
adaptiveTtlMin?: number;
|
|
1137
|
+
/**
|
|
1138
|
+
* Maximum TTL (seconds) the adaptive tuner will ever assign.
|
|
1139
|
+
* Guards against pathologically slow fetches producing indefinite caching.
|
|
1140
|
+
* Default: `86400` (24 hours).
|
|
1141
|
+
*/
|
|
1142
|
+
adaptiveTtlMax?: number;
|
|
1143
|
+
/**
|
|
1144
|
+
* `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
|
|
1145
|
+
*
|
|
1146
|
+
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
1147
|
+
* 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
|
|
1148
|
+
* if you want the cache to absorb more upstream pressure.
|
|
1149
|
+
*
|
|
1150
|
+
* Default: `20`.
|
|
1151
|
+
*/
|
|
1152
|
+
adaptiveTtlMultiplier?: number;
|
|
1153
|
+
/**
|
|
1154
|
+
* Number of fetch duration samples kept per key in the ring buffer.
|
|
1155
|
+
* Larger values smooth out latency spikes but use slightly more memory
|
|
1156
|
+
* (~8 bytes × samples per tracked key).
|
|
1157
|
+
* Default: `32`.
|
|
1158
|
+
*/
|
|
1159
|
+
adaptiveTtlSamples?: number;
|
|
1160
|
+
/**
|
|
1161
|
+
* Maximum number of distinct keys tracked by the adaptive TTL system.
|
|
1162
|
+
* When the cap is reached, the oldest-tracked key is evicted from the
|
|
1163
|
+
* ring-buffer store to make room for the new key.
|
|
1164
|
+
* Default: `5000`.
|
|
1165
|
+
*/
|
|
1166
|
+
adaptiveTtlMaxKeys?: number;
|
|
1167
|
+
/**
|
|
1168
|
+
* When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
|
|
1169
|
+
* encryption and decryption for large payloads to those threads, keeping the
|
|
1170
|
+
* V8 main event loop free for concurrent HTTP requests.
|
|
1171
|
+
*
|
|
1172
|
+
* Only takes effect when `encryptionKey` is set — plaintext payloads are never
|
|
1173
|
+
* serialized off-thread because `JSON.stringify/parse` is already fast.
|
|
1174
|
+
*
|
|
1175
|
+
* Default: `false`. Enable in long-running servers that write multi-megabyte
|
|
1176
|
+
* encrypted payloads and observe event-loop latency spikes.
|
|
1177
|
+
*/
|
|
1178
|
+
workerThreads?: boolean;
|
|
1179
|
+
/**
|
|
1180
|
+
* Byte threshold above which an L2 payload is offloaded to a worker thread
|
|
1181
|
+
* for encryption / decryption. Payloads smaller than this are processed
|
|
1182
|
+
* synchronously (IPC overhead would exceed the savings).
|
|
1183
|
+
* Default: `131072` (128 KB).
|
|
1184
|
+
*/
|
|
1185
|
+
workerThresholdBytes?: number;
|
|
1186
|
+
/**
|
|
1187
|
+
* Number of worker threads in the pool.
|
|
1188
|
+
* Default: `Math.min(4, os.availableParallelism())`.
|
|
1189
|
+
*/
|
|
1190
|
+
workerPoolSize?: number;
|
|
1191
|
+
/**
|
|
1192
|
+
* Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
|
|
1193
|
+
* disconnected before tricache considers its L1 entries potentially stale.
|
|
1194
|
+
*
|
|
1195
|
+
* When the subscriber reconnects after a gap longer than this value, all L1
|
|
1196
|
+
* entries that were written *before* the disconnect started are evicted.
|
|
1197
|
+
* This prevents the instance from silently serving data that peers may have
|
|
1198
|
+
* invalidated while the backplane connection was down.
|
|
1199
|
+
*
|
|
1200
|
+
* Set to `0` to disable the fence entirely (accept eventual-consistency drift).
|
|
1201
|
+
* Default: `5000` (5 seconds).
|
|
1202
|
+
*/
|
|
1203
|
+
backplaneMaxStalenessMs?: number;
|
|
1204
|
+
/**
|
|
1205
|
+
* Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
|
|
1206
|
+
*
|
|
1207
|
+
* Tricache auto-detects common serverless / ephemeral-filesystem runtimes
|
|
1208
|
+
* (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
|
|
1209
|
+
* Fly.io) and disables the disk tier automatically. Set this to `false` to
|
|
1210
|
+
* override that detection and force the disk tier on regardless of runtime.
|
|
1211
|
+
*
|
|
1212
|
+
* When disabled:
|
|
1213
|
+
* - L1 evictions are dropped instead of being spilled to disk.
|
|
1214
|
+
* - Cold-start snapshot persistence is skipped.
|
|
1215
|
+
* - The `disk` metrics field still appears but shows zeroed counters.
|
|
1216
|
+
*
|
|
1217
|
+
* Default: `undefined` (auto-detect).
|
|
1218
|
+
*/
|
|
1219
|
+
disableDisk?: boolean;
|
|
1220
|
+
/**
|
|
1221
|
+
* Redis Cluster node list. When provided, tricache connects using ioredis
|
|
1222
|
+
* `Cluster` mode with automatic slot routing and multi-node connection
|
|
1223
|
+
* pooling — no external proxy required.
|
|
1224
|
+
*
|
|
1225
|
+
* Takes precedence over `redisHost`/`redisPort`.
|
|
1226
|
+
*
|
|
1227
|
+
* @example
|
|
1228
|
+
* redisClusterNodes: [
|
|
1229
|
+
* { host: 'redis-1.internal', port: 6379 },
|
|
1230
|
+
* { host: 'redis-2.internal', port: 6379 },
|
|
1231
|
+
* { host: 'redis-3.internal', port: 6379 },
|
|
1232
|
+
* ]
|
|
1233
|
+
*/
|
|
1234
|
+
redisClusterNodes?: Array<{
|
|
1235
|
+
host: string;
|
|
1236
|
+
port: number;
|
|
1237
|
+
}>;
|
|
1238
|
+
/**
|
|
1239
|
+
* Redis Sentinel configuration for high-availability setups.
|
|
1240
|
+
* When provided, tricache connects through Sentinel for automatic
|
|
1241
|
+
* primary failover — no static `redisHost` / `redisPort` needed.
|
|
1242
|
+
*
|
|
1243
|
+
* Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
|
|
1244
|
+
*
|
|
1245
|
+
* @example
|
|
1246
|
+
* redisSentinel: {
|
|
1247
|
+
* name: 'mymaster',
|
|
1248
|
+
* sentinels: [
|
|
1249
|
+
* { host: 'sentinel-1.internal', port: 26379 },
|
|
1250
|
+
* { host: 'sentinel-2.internal', port: 26379 },
|
|
1251
|
+
* ],
|
|
1252
|
+
* }
|
|
1253
|
+
*/
|
|
1254
|
+
redisSentinel?: {
|
|
1255
|
+
/** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
|
|
1256
|
+
name: string;
|
|
1257
|
+
sentinels: Array<{
|
|
1258
|
+
host: string;
|
|
1259
|
+
port: number;
|
|
1260
|
+
}>;
|
|
1261
|
+
};
|
|
1262
|
+
/**
|
|
1263
|
+
* When `true`, a second `CacheService.create()` call for an already-existing
|
|
1264
|
+
* singleton (same namespace) whose options differ from the first call throws
|
|
1265
|
+
* instead of silently returning the existing instance. Use in codebases where
|
|
1266
|
+
* multiple init points could pass conflicting configuration (e.g. different
|
|
1267
|
+
* Redis credentials or TTLs) and you want that class of bug to fail loudly.
|
|
1268
|
+
*
|
|
1269
|
+
* Default: `false` (warn once, return existing instance).
|
|
1270
|
+
*/
|
|
1271
|
+
strictSingleton?: boolean;
|
|
1272
|
+
/**
|
|
1273
|
+
* `cache.increment()` distributed-rate-limit behaviour on a Redis error.
|
|
1274
|
+
*
|
|
1275
|
+
* Default: `false` (fail-open — on a Redis error the method returns `0`, so a
|
|
1276
|
+
* caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
|
|
1277
|
+
* Set to `true` to instead re-throw the Redis error, letting the caller's limit
|
|
1278
|
+
* guard enforce the limit even when Redis is unavailable.
|
|
1279
|
+
*/
|
|
1280
|
+
failClosed?: boolean;
|
|
1281
|
+
/**
|
|
1282
|
+
* Strategy used for tag-based cache invalidation:
|
|
1283
|
+
* - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
|
|
1284
|
+
* sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
|
|
1285
|
+
* - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
|
|
1286
|
+
* increments an atomic integer version counter in Redis and local memory. Entries store their
|
|
1287
|
+
* creation tag versions; stale entries are detected on access and pruned with version-gated
|
|
1288
|
+
* compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
|
|
1289
|
+
*/
|
|
1290
|
+
tagStrategy?: 'set' | 'generational';
|
|
1291
|
+
/**
|
|
1292
|
+
* Milliseconds before an in-memory generational tag version is re-synced from Redis.
|
|
1293
|
+
* Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
|
|
1294
|
+
* Default: `5000` ms (5 seconds).
|
|
1295
|
+
*/
|
|
1296
|
+
tagVersionTtlMs?: number;
|
|
1297
|
+
/**
|
|
1298
|
+
* Automatically expand hierarchical tags into their ancestor namespaces.
|
|
1299
|
+
* For example, tagging an entry with `'org:123:dept:456'` will also associate
|
|
1300
|
+
* it with `'org:123'` and `'org'`, allowing `invalidateTag('org:123')` or
|
|
1301
|
+
* `invalidateTag('org')` to automatically cascade down to this entry.
|
|
1302
|
+
*
|
|
1303
|
+
* Default: `false`.
|
|
1304
|
+
*/
|
|
1305
|
+
hierarchicalTags?: boolean;
|
|
1306
|
+
/**
|
|
1307
|
+
* The delimiter used for splitting hierarchical tags when `hierarchicalTags` is enabled.
|
|
1308
|
+
* Default: `':'`.
|
|
1309
|
+
*/
|
|
1310
|
+
tagHierarchyDelimiter?: string;
|
|
1311
|
+
/**
|
|
1312
|
+
* Read safety strategy for returned cached objects:
|
|
1313
|
+
* - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
|
|
1314
|
+
* - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
|
|
1315
|
+
* and fetch returns, preventing caller mutations from polluting the cached reference.
|
|
1316
|
+
* Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
|
|
1317
|
+
* prototype chains are not preserved.
|
|
1318
|
+
*/
|
|
1319
|
+
cloneStrategy?: 'none' | 'structuredClone';
|
|
1320
|
+
/**
|
|
1321
|
+
* Invalidation backplane transport mode:
|
|
1322
|
+
* - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
|
|
1323
|
+
* - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
|
|
1324
|
+
*/
|
|
1325
|
+
backplaneMode?: 'pubsub' | 'stream';
|
|
1326
|
+
/**
|
|
1327
|
+
* Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
|
|
1328
|
+
* Default: `10000`.
|
|
1329
|
+
*/
|
|
1330
|
+
backplaneStreamMaxLen?: number;
|
|
1331
|
+
/**
|
|
1332
|
+
* Blocking poll timeout in milliseconds for `XREAD BLOCK`.
|
|
1333
|
+
* Default: `2000` ms (2 seconds).
|
|
1334
|
+
*/
|
|
1335
|
+
backplaneStreamBlockMs?: number;
|
|
1336
|
+
/**
|
|
1337
|
+
* Custom Redis Stream key name.
|
|
1338
|
+
* Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
|
|
1339
|
+
*/
|
|
1340
|
+
backplaneStreamKey?: string;
|
|
1341
|
+
/**
|
|
1342
|
+
* OpenTelemetry Meter instance for native metrics publishing.
|
|
1343
|
+
* Compatible with `@opentelemetry/api` Meter.
|
|
1344
|
+
*/
|
|
1345
|
+
meter?: ICacheMeter;
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Options for tag invalidation operations (`cache.invalidateTag()` and `cache.invalidateTags()`).
|
|
1349
|
+
*/
|
|
1350
|
+
interface InvalidateTagOptions {
|
|
1351
|
+
/**
|
|
1352
|
+
* When true, invalidates both the specified tag and any descendant child tags
|
|
1353
|
+
* in the hierarchy (e.g. invalidating 'org:123' also invalidates 'org:123:*').
|
|
1354
|
+
* Default: `false`.
|
|
1355
|
+
*/
|
|
1356
|
+
cascade?: boolean;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
|
|
1360
|
+
*/
|
|
1361
|
+
interface WrapOptions {
|
|
1362
|
+
/** TTL in seconds (default: 300 s). */
|
|
1363
|
+
ttl?: number;
|
|
1364
|
+
/** Stale-While-Revalidate grace period in seconds. */
|
|
1365
|
+
swr?: number;
|
|
1366
|
+
/** Override the auto-inferred eviction priority. */
|
|
1367
|
+
priority?: CachePriority;
|
|
1368
|
+
/** Semantic tags for invalidation. */
|
|
1369
|
+
tags?: string[];
|
|
1370
|
+
/** Dependency cascade patterns (e.g. `['user:*']`). */
|
|
1371
|
+
dependsOn?: string[];
|
|
1372
|
+
/** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
|
|
1373
|
+
refreshAhead?: number;
|
|
1374
|
+
/** XFetch probabilistic early expiration factor (0.5–2.0). */
|
|
1375
|
+
xfetchBeta?: number;
|
|
1376
|
+
/** Override TTL in seconds for null/undefined fetch results (negative caching). */
|
|
1377
|
+
notFoundTtl?: number;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
|
|
1381
|
+
*/
|
|
1382
|
+
interface LockOptions {
|
|
1383
|
+
/**
|
|
1384
|
+
* Lock auto-release TTL in seconds (default: 30 s).
|
|
1385
|
+
* Prevents deadlocks if the holding node crashes or is terminated.
|
|
1386
|
+
*/
|
|
1387
|
+
ttl?: number;
|
|
1388
|
+
/**
|
|
1389
|
+
* Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
|
|
1390
|
+
* Default: `5000` ms.
|
|
1391
|
+
*/
|
|
1392
|
+
acquireTimeout?: number;
|
|
1393
|
+
/**
|
|
1394
|
+
* Polling retry interval in milliseconds when waiting for lock acquisition.
|
|
1395
|
+
* Default: `100` ms.
|
|
1396
|
+
*/
|
|
1397
|
+
retryInterval?: number;
|
|
1398
|
+
/**
|
|
1399
|
+
* If `true`, lock acquisition will throw an error immediately if Redis encounters a
|
|
1400
|
+
* connection or operational error rather than falling back to an in-process mutex.
|
|
1401
|
+
* Overrides `CacheOptions.lockFailClosed`.
|
|
1402
|
+
*/
|
|
1403
|
+
failClosedOnRedisError?: boolean;
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
|
|
1407
|
+
*/
|
|
1408
|
+
interface ICacheCounter {
|
|
1409
|
+
add(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1410
|
+
}
|
|
1411
|
+
type ICacheObservableCallback = (result: {
|
|
1412
|
+
observe(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1413
|
+
}) => void | Promise<void>;
|
|
1414
|
+
interface ICacheObservableGauge {
|
|
1415
|
+
addCallback(callback: ICacheObservableCallback): void;
|
|
1416
|
+
removeCallback(callback: ICacheObservableCallback): void;
|
|
1417
|
+
}
|
|
1418
|
+
interface ICacheBatchObservableCallback {
|
|
1419
|
+
(observableResult: {
|
|
1420
|
+
observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
|
|
1421
|
+
}): void | Promise<void>;
|
|
1422
|
+
}
|
|
1423
|
+
interface ICacheMeter {
|
|
1424
|
+
createCounter(name: string, options?: {
|
|
1425
|
+
description?: string;
|
|
1426
|
+
unit?: string;
|
|
1427
|
+
}): ICacheCounter;
|
|
1428
|
+
createObservableGauge(name: string, options?: {
|
|
1429
|
+
description?: string;
|
|
1430
|
+
unit?: string;
|
|
1431
|
+
}): ICacheObservableGauge;
|
|
1432
|
+
addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1433
|
+
removeBatchObservableCallback?(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Common pipeline / transaction interface matching ioredis and adapted drivers.
|
|
1437
|
+
*/
|
|
1438
|
+
interface IRedisPipeline {
|
|
1439
|
+
get(key: string): this;
|
|
1440
|
+
set(key: string, value: string, ...args: (string | number)[]): this;
|
|
1441
|
+
setex(key: string, seconds: number, value: string): this;
|
|
1442
|
+
del(...keys: string[]): this;
|
|
1443
|
+
expire(key: string, seconds: number): this;
|
|
1444
|
+
incr(key: string): this;
|
|
1445
|
+
sadd(key: string, ...members: string[]): this;
|
|
1446
|
+
smembers(key: string): this;
|
|
1447
|
+
hset(key: string, value: Record<string, string>): this;
|
|
1448
|
+
hgetall?(key: string): this;
|
|
1449
|
+
/** Remaining TTL in milliseconds; enables atomic value + expiry reads. */
|
|
1450
|
+
pttl?(key: string): this;
|
|
1451
|
+
eval?(script: string, numkeys: number, ...args: (string | number)[]): this;
|
|
1452
|
+
exec(): Promise<Array<[Error | null, any]> | null>;
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Pluggable contract for external Redis drivers (e.g. `@redis/client` / `node-redis`,
|
|
1456
|
+
* custom connection pools, or pre-configured `ioredis` instances).
|
|
1457
|
+
*/
|
|
1458
|
+
interface IRedisDriver {
|
|
1459
|
+
get(key: string): Promise<string | null>;
|
|
1460
|
+
set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
|
|
1461
|
+
setex?(key: string, seconds: number, value: string): Promise<unknown>;
|
|
1462
|
+
del(...keys: string[]): Promise<number>;
|
|
1463
|
+
ping(): Promise<string>;
|
|
1464
|
+
pttl?(key: string): Promise<number>;
|
|
1465
|
+
expire(key: string, seconds: number): Promise<number | boolean>;
|
|
1466
|
+
incr(key: string): Promise<number>;
|
|
1467
|
+
eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
1468
|
+
multi(): IRedisPipeline;
|
|
1469
|
+
pipeline?(): IRedisPipeline;
|
|
1470
|
+
smembers?(key: string): Promise<string[]>;
|
|
1471
|
+
sadd?(key: string, ...members: string[]): Promise<number>;
|
|
1472
|
+
scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
|
|
1473
|
+
scanStream?(options?: {
|
|
1474
|
+
match?: string;
|
|
1475
|
+
count?: number;
|
|
1476
|
+
}): any;
|
|
1477
|
+
hset?(key: string, value: Record<string, string>): Promise<unknown>;
|
|
1478
|
+
hgetall?(key: string): Promise<Record<string, string>>;
|
|
1479
|
+
publish?(channel: string, message: string): Promise<number>;
|
|
1480
|
+
subscribe?(...channels: string[]): Promise<unknown>;
|
|
1481
|
+
unsubscribe?(...channels: string[]): Promise<unknown>;
|
|
1482
|
+
removeListener?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1483
|
+
disconnect(): Promise<void> | void;
|
|
1484
|
+
quit?(): Promise<void> | void;
|
|
1485
|
+
duplicate?(): IRedisDriver;
|
|
1486
|
+
on?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1487
|
+
once?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1488
|
+
isOpen?: boolean;
|
|
1489
|
+
connect?(): Promise<unknown>;
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Real-time telemetry and state for the disk tier backpressure queue.
|
|
1493
|
+
*/
|
|
1494
|
+
interface DiskBackpressureStats {
|
|
1495
|
+
activeWrites: number;
|
|
1496
|
+
pendingWrites: number;
|
|
1497
|
+
spillsDropped: number;
|
|
1498
|
+
circuitState: 'closed' | 'open' | 'half-open';
|
|
1499
|
+
lastTripTimestamp: number;
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Telemetry metrics and counters for Window TinyLFU cache admission.
|
|
1503
|
+
*/
|
|
1504
|
+
interface WTinyLfuStats {
|
|
1505
|
+
capacity: number;
|
|
1506
|
+
size: number;
|
|
1507
|
+
windowSize: number;
|
|
1508
|
+
probationSize: number;
|
|
1509
|
+
protectedSize: number;
|
|
1510
|
+
hits: number;
|
|
1511
|
+
misses: number;
|
|
1512
|
+
hitRate: number;
|
|
1513
|
+
admissions: number;
|
|
1514
|
+
rejections: number;
|
|
1515
|
+
demotions: number;
|
|
1516
|
+
promotions: number;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
export { type ICacheObservableGauge as A, type ICacheSpan as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type ICacheSpanLink as F, type ICrossRegionRelay as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, type WebhookRequestLike as J, type WebhookResponseLike as K, type LockOptions as L, consoleLogger as M, createCrossRegionWebhookHandler as N, createCustomCrossRegionRelay as O, createCustomSnapshotAdapter as P, createHttpMeshRelay as Q, type RemoteSnapshotOptions as R, type SmartCacheEntry as S, createHttpSnapshotAdapter as T, createMemoryCrossRegionRelay as U, createMemorySnapshotAdapter as V, type WrapOptions as W, initZstd as X, type InvalidateTagOptions as a, type CacheMetrics as b, type CacheHealthStatus as c, type CachePresetType as d, type CrossRegionInvalidationEvent as e, CachePriority as f, type CachePingResult as g, type WTinyLfuStats as h, type ILogger as i, type IRemoteSnapshotAdapter as j, type CategoryLimit as k, type EvictionReason as l, type CacheHit as m, CacheEncryption as n, type CompressionAlgorithm as o, type DiskCacheEntry as p, type IRedisDriver as q, type IRedisPipeline as r, type CrossRegionRelayOptions as s, type CustomCompressor as t, EnvelopeEncryption as u, type EnvelopeEncryptionOptions as v, type HttpSnapshotAdapterOptions as w, type ICacheBatchObservableCallback as x, type ICacheCounter as y, type ICacheMeter as z };
|