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