tricache 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +144 -1428
- package/bin/tricache.js +8 -8
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2894 -518
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2648 -508
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +3038 -589
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +238 -62
- package/dist/index.cjs +6962 -2487
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2586 -498
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2633 -519
- package/dist/next/index.d.ts +13 -7
- package/dist/next/index.js +45 -18
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +3 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +31 -19
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
- package/package.json +37 -7
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +4231 -3226
- package/src/cli.ts +261 -143
- package/src/codec.ts +72 -0
- package/src/compression.ts +56 -63
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +1223 -821
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +635 -493
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +46 -223
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +271 -244
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/prisma/index.ts +154 -151
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +1109 -1024
- package/src/types.ts +1199 -902
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-AJASH5FX.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
|
|
3
|
+
*
|
|
4
|
+
* Prevents EBS/cloud NVMe latency degradation from impacting application p95 response times.
|
|
5
|
+
* Incorporates control-theory safeguards:
|
|
6
|
+
* - Amortized zero-allocation p95 calculation (fires every 32 samples on pre-allocated typed arrays).
|
|
7
|
+
* - Graduated probabilistic shedding (Stage 0: 0% -> Stage 1: 25% -> Stage 2: 75% -> Stage 3: 100%).
|
|
8
|
+
* - Asymmetric hysteresis on Redis circuit (cuts diversion at 15ms, requires recovery below 10ms).
|
|
9
|
+
* - Anti-synchronicity cooldown jitter (±30%) to eliminate fleet-wide failover shockwaves.
|
|
10
|
+
* - Single-canary half-open recovery probing.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export interface LatencyWatchdogOptions {
|
|
14
|
+
enabled?: boolean;
|
|
15
|
+
minDiskBypassMs?: number;
|
|
16
|
+
bypassRatio?: number;
|
|
17
|
+
cooldownMs?: number;
|
|
18
|
+
redisCutoffMs?: number;
|
|
19
|
+
redisRecoveryFloorMs?: number;
|
|
20
|
+
minSamples?: number;
|
|
21
|
+
disableRedis?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface LatencyWatchdogTelemetry {
|
|
25
|
+
bypassActive: boolean;
|
|
26
|
+
bypassStage: 0 | 1 | 2 | 3;
|
|
27
|
+
diskP95Ms: number;
|
|
28
|
+
redisP95Ms: number;
|
|
29
|
+
redisDampened: boolean;
|
|
30
|
+
bypassedTotal: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class TierLatencyWatchdog {
|
|
34
|
+
private readonly enabled: boolean;
|
|
35
|
+
private readonly minDiskBypassMs: number;
|
|
36
|
+
private readonly bypassRatio: number;
|
|
37
|
+
private readonly cooldownMs: number;
|
|
38
|
+
private readonly redisCutoffMs: number;
|
|
39
|
+
private readonly redisRecoveryFloorMs: number;
|
|
40
|
+
private readonly minSamples: number;
|
|
41
|
+
private disableRedis: boolean;
|
|
42
|
+
|
|
43
|
+
// Zero-allocation rolling ring buffers
|
|
44
|
+
private readonly diskRing = new Float32Array(32);
|
|
45
|
+
private readonly redisRing = new Float32Array(32);
|
|
46
|
+
private readonly scratch = new Float32Array(32);
|
|
47
|
+
|
|
48
|
+
private diskIdx = 0;
|
|
49
|
+
private redisIdx = 0;
|
|
50
|
+
private diskCount = 0;
|
|
51
|
+
private redisCount = 0;
|
|
52
|
+
|
|
53
|
+
// Cached amortized p95 values
|
|
54
|
+
private cachedDiskP95 = 0;
|
|
55
|
+
private cachedRedisP95 = 0;
|
|
56
|
+
|
|
57
|
+
// State machine & control-theory flags
|
|
58
|
+
private stage: 0 | 1 | 2 | 3 = 0;
|
|
59
|
+
private redisDampened = false; // Asymmetric hysteresis latch
|
|
60
|
+
private redisRecoveryConsecutiveSamples = 0;
|
|
61
|
+
private bypassedUntilMonotonic = 0;
|
|
62
|
+
private canaryInFlight = false;
|
|
63
|
+
private bypassedTotal = 0;
|
|
64
|
+
|
|
65
|
+
constructor(options: LatencyWatchdogOptions = {}) {
|
|
66
|
+
this.enabled = options.enabled ?? true;
|
|
67
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
68
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
69
|
+
this.cooldownMs = options.cooldownMs ?? 30_000;
|
|
70
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
71
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
72
|
+
this.minSamples = options.minSamples ?? 16;
|
|
73
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
public setDisableRedis(disabled: boolean): void {
|
|
77
|
+
this.disableRedis = disabled;
|
|
78
|
+
if (disabled) {
|
|
79
|
+
this.stage = 0;
|
|
80
|
+
this.bypassedUntilMonotonic = 0;
|
|
81
|
+
this.canaryInFlight = false;
|
|
82
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
88
|
+
*/
|
|
89
|
+
public recordDisk(ms: number): void {
|
|
90
|
+
if (!this.enabled) return;
|
|
91
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
92
|
+
this.diskCount++;
|
|
93
|
+
|
|
94
|
+
// Amortized: recalculate only every 32 samples
|
|
95
|
+
if ((this.diskIdx & 31) === 0) {
|
|
96
|
+
this.recalculateP95();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
102
|
+
*/
|
|
103
|
+
public recordRedis(ms: number): void {
|
|
104
|
+
if (!this.enabled || this.disableRedis) return;
|
|
105
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
106
|
+
this.redisCount++;
|
|
107
|
+
|
|
108
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
109
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
110
|
+
} else {
|
|
111
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Amortized: recalculate only every 32 samples
|
|
115
|
+
if ((this.redisIdx & 31) === 0) {
|
|
116
|
+
this.recalculateP95();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private recalculateP95(): void {
|
|
121
|
+
if (this.diskCount >= this.minSamples) {
|
|
122
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
123
|
+
}
|
|
124
|
+
if (this.redisCount >= this.minSamples) {
|
|
125
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
this.evaluateControlLoop();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private computeP95(ring: Float32Array, count: number): number {
|
|
132
|
+
for (let i = 0; i < count; i++) {
|
|
133
|
+
this.scratch[i] = ring[i];
|
|
134
|
+
}
|
|
135
|
+
this.scratch.subarray(0, count).sort();
|
|
136
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
137
|
+
return this.scratch[rank];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Core Control Loop:
|
|
142
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
143
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
144
|
+
*/
|
|
145
|
+
private evaluateControlLoop(): void {
|
|
146
|
+
if (this.disableRedis) {
|
|
147
|
+
this.stage = 0;
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// 1. Asymmetric Hysteresis on Redis:
|
|
152
|
+
// If Redis is struggling (>15ms), latch dampening ON to protect fleet
|
|
153
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
154
|
+
this.redisDampened = true;
|
|
155
|
+
} else if (
|
|
156
|
+
this.redisDampened &&
|
|
157
|
+
this.cachedRedisP95 <= this.redisRecoveryFloorMs &&
|
|
158
|
+
this.redisRecoveryConsecutiveSamples >= this.minSamples
|
|
159
|
+
) {
|
|
160
|
+
// Only release dampening once Redis stabilizes firmly below 10ms across at least 16 consecutive samples
|
|
161
|
+
this.redisDampened = false;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// If Redis is dampened, refuse to divert additional traffic to Redis
|
|
165
|
+
if (this.redisDampened) {
|
|
166
|
+
this.stage = 0;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Require adequate samples on both tiers before making diversion decisions
|
|
171
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const diskP95 = this.cachedDiskP95;
|
|
176
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
177
|
+
|
|
178
|
+
// 2. Graduated Stage Evaluation
|
|
179
|
+
if (diskP95 >= 50) {
|
|
180
|
+
// Hard stall: Stage 3 (100% bypass)
|
|
181
|
+
if (this.stage !== 3) {
|
|
182
|
+
this.stage = 3;
|
|
183
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
184
|
+
this.bypassedTotal++;
|
|
185
|
+
}
|
|
186
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
187
|
+
// Severe contention: Stage 2 (75% bypass)
|
|
188
|
+
if (this.stage !== 2) {
|
|
189
|
+
this.stage = 2;
|
|
190
|
+
this.bypassedTotal++;
|
|
191
|
+
}
|
|
192
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
193
|
+
// Moderate contention: Stage 1 (25% bypass)
|
|
194
|
+
if (this.stage !== 1) {
|
|
195
|
+
this.stage = 1;
|
|
196
|
+
this.bypassedTotal++;
|
|
197
|
+
}
|
|
198
|
+
} else {
|
|
199
|
+
// Normal operating conditions
|
|
200
|
+
this.stage = 0;
|
|
201
|
+
this.bypassedUntilMonotonic = 0;
|
|
202
|
+
this.canaryInFlight = false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private calculateJitteredCooldown(): number {
|
|
207
|
+
// ±30% anti-synchronicity jitter
|
|
208
|
+
const jitterFactor = 0.7 + Math.random() * 0.6; // [0.7, 1.3]
|
|
209
|
+
return this.cooldownMs * jitterFactor;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
214
|
+
*
|
|
215
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
216
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
217
|
+
*
|
|
218
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
219
|
+
*/
|
|
220
|
+
public isDiskAllowed(randomOverride?: number): boolean {
|
|
221
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
222
|
+
|
|
223
|
+
if (this.stage === 0) return true;
|
|
224
|
+
|
|
225
|
+
const rand = randomOverride !== undefined ? randomOverride : Math.random();
|
|
226
|
+
|
|
227
|
+
// Stage 1: Probabilistic 25% diversion (75% hit disk)
|
|
228
|
+
if (this.stage === 1) {
|
|
229
|
+
return rand > 0.25;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Stage 2: Probabilistic 75% diversion (25% hit disk)
|
|
233
|
+
if (this.stage === 2) {
|
|
234
|
+
return rand > 0.75;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Stage 3: 100% bypass with half-open single canary probe
|
|
238
|
+
const now = performance.now();
|
|
239
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
240
|
+
return false; // Cooldown active, 100% diverted to Redis
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Cooldown elapsed: Permit exactly ONE canary probe in half-open state
|
|
244
|
+
if (!this.canaryInFlight) {
|
|
245
|
+
this.canaryInFlight = true;
|
|
246
|
+
return true; // Canary allowed
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Other concurrent requests wait for canary result
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Callback invoked when the single canary read probe completes.
|
|
255
|
+
*/
|
|
256
|
+
public onCanaryResult(success: boolean, elapsedMs: number): void {
|
|
257
|
+
if (!this.canaryInFlight) return;
|
|
258
|
+
this.canaryInFlight = false;
|
|
259
|
+
|
|
260
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
261
|
+
// Canary succeeded and was fast: Recover cleanly
|
|
262
|
+
this.stage = 0;
|
|
263
|
+
this.bypassedUntilMonotonic = 0;
|
|
264
|
+
this.recordDisk(elapsedMs);
|
|
265
|
+
} else {
|
|
266
|
+
// Canary failed or was still slow: Extend cooldown with fresh jitter
|
|
267
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
268
|
+
this.bypassedTotal++;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
public getTelemetry(): LatencyWatchdogTelemetry {
|
|
273
|
+
return {
|
|
274
|
+
bypassActive: this.stage > 0,
|
|
275
|
+
bypassStage: this.stage,
|
|
276
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
277
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
278
|
+
redisDampened: this.redisDampened,
|
|
279
|
+
bypassedTotal: this.bypassedTotal,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
}
|
package/src/nestjs/decorators.ts
CHANGED
|
@@ -1,161 +1,161 @@
|
|
|
1
|
-
import { CacheService } from '../cache-service.js';
|
|
2
|
-
import type { CachePriority } from '../types.js';
|
|
3
|
-
|
|
4
|
-
export interface CacheableOptions {
|
|
5
|
-
/**
|
|
6
|
-
* Static key string or dynamic key generator function.
|
|
7
|
-
* Example: (id: string) => `user:${id}`
|
|
8
|
-
*/
|
|
9
|
-
key?: string | ((...args: any[]) => string);
|
|
10
|
-
/** TTL in seconds (or milliseconds if specified / detected). Default: 300 s. */
|
|
11
|
-
ttl?: number;
|
|
12
|
-
/** Explicit time unit for the ttl option. Default: 'seconds'. */
|
|
13
|
-
ttlUnit?: 'seconds' | 'milliseconds';
|
|
14
|
-
/** Stale-While-Revalidate grace period in seconds. */
|
|
15
|
-
swr?: number;
|
|
16
|
-
/** Semantic tags for invalidation. */
|
|
17
|
-
tags?: string[] | ((...args: any[]) => string[]);
|
|
18
|
-
/** Dependency cascade patterns. */
|
|
19
|
-
dependsOn?: string[] | ((...args: any[]) => string[]);
|
|
20
|
-
/** Cache eviction priority. */
|
|
21
|
-
priority?: CachePriority;
|
|
22
|
-
/** 0–1 fraction of TTL elapsed for background recompute. */
|
|
23
|
-
refreshAhead?: number;
|
|
24
|
-
/** XFetch probabilistic early expiration factor (0.5–2.0). */
|
|
25
|
-
xfetchBeta?: number;
|
|
26
|
-
/** Condition predicate to determine whether caching should occur. */
|
|
27
|
-
condition?: (...args: any[]) => boolean;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface CacheEvictOptions {
|
|
31
|
-
/** Key or pattern to delete. */
|
|
32
|
-
key?: string | ((...args: any[]) => string);
|
|
33
|
-
/** Tags to invalidate. */
|
|
34
|
-
tags?: string[] | ((...args: any[]) => string[]);
|
|
35
|
-
/** Invalidate before method execution (default: false = after successful execution). */
|
|
36
|
-
beforeInvocation?: boolean;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function resolveCacheInstance(ctx: any): CacheService {
|
|
40
|
-
return ctx?.cacheService || ctx?.cache || ctx?.cacheStore?.cache || CacheService.create();
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Declarative method decorator that caches the return value of an async method.
|
|
45
|
-
*
|
|
46
|
-
* Automatically intercepts calls, checks TriCache (L1 -> L1.5 -> L2), and falls
|
|
47
|
-
* back to executing the decorated method on cache miss with thundering-herd protection.
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* ```typescript
|
|
51
|
-
* @Injectable()
|
|
52
|
-
* export class UserService {
|
|
53
|
-
* @Cacheable({ key: (id) => `user:${id}`, ttl: 300, tags: ['users'] })
|
|
54
|
-
* async findById(id: string) {
|
|
55
|
-
* return this.db.find(id);
|
|
56
|
-
* }
|
|
57
|
-
* }
|
|
58
|
-
* ```
|
|
59
|
-
*/
|
|
60
|
-
export function Cacheable(options: CacheableOptions = {}): MethodDecorator {
|
|
61
|
-
return function (
|
|
62
|
-
target: any,
|
|
63
|
-
propertyKey: string | symbol,
|
|
64
|
-
descriptor: TypedPropertyDescriptor<any>,
|
|
65
|
-
) {
|
|
66
|
-
const originalMethod = descriptor.value;
|
|
67
|
-
const methodName = String(propertyKey);
|
|
68
|
-
const className = target?.constructor?.name || 'Service';
|
|
69
|
-
|
|
70
|
-
descriptor.value = async function (...args: any[]) {
|
|
71
|
-
if (options.condition && !options.condition(...args)) {
|
|
72
|
-
return originalMethod.apply(this, args);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const cache = resolveCacheInstance(this);
|
|
76
|
-
const key = typeof options.key === 'function'
|
|
77
|
-
? options.key(...args)
|
|
78
|
-
: (typeof options.key === 'string' ? options.key : `${className}:${methodName}:${JSON.stringify(args)}`);
|
|
79
|
-
|
|
80
|
-
let ttlSeconds = options.ttl ?? 300;
|
|
81
|
-
const rawTtl = options.ttl;
|
|
82
|
-
if (typeof rawTtl === 'number') {
|
|
83
|
-
if (options.ttlUnit === 'milliseconds' || (rawTtl >= 1000 && rawTtl % 1000 === 0 && options.ttlUnit !== 'seconds')) {
|
|
84
|
-
ttlSeconds = Math.round(rawTtl / 1000);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const tags = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
89
|
-
const dependsOn = typeof options.dependsOn === 'function' ? options.dependsOn(...args) : options.dependsOn;
|
|
90
|
-
|
|
91
|
-
return cache.wrap(
|
|
92
|
-
key,
|
|
93
|
-
() => originalMethod.apply(this, args),
|
|
94
|
-
{
|
|
95
|
-
ttl: ttlSeconds,
|
|
96
|
-
swr: options.swr,
|
|
97
|
-
tags,
|
|
98
|
-
dependsOn,
|
|
99
|
-
priority: options.priority,
|
|
100
|
-
refreshAhead: options.refreshAhead,
|
|
101
|
-
xfetchBeta: options.xfetchBeta,
|
|
102
|
-
},
|
|
103
|
-
);
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
return descriptor;
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Declarative method decorator that invalidates cache keys or tags upon method execution.
|
|
112
|
-
*
|
|
113
|
-
* @example
|
|
114
|
-
* ```typescript
|
|
115
|
-
* @Injectable()
|
|
116
|
-
* export class UserService {
|
|
117
|
-
* @CacheEvict({ tags: ['users'] })
|
|
118
|
-
* async update(id: string, dto: UpdateUserDto) {
|
|
119
|
-
* return this.db.update(id, dto);
|
|
120
|
-
* }
|
|
121
|
-
* }
|
|
122
|
-
* ```
|
|
123
|
-
*/
|
|
124
|
-
export function CacheEvict(options: CacheEvictOptions = {}): MethodDecorator {
|
|
125
|
-
return function (
|
|
126
|
-
_target: any,
|
|
127
|
-
_propertyKey: string | symbol,
|
|
128
|
-
descriptor: TypedPropertyDescriptor<any>,
|
|
129
|
-
) {
|
|
130
|
-
const originalMethod = descriptor.value;
|
|
131
|
-
|
|
132
|
-
descriptor.value = async function (...args: any[]) {
|
|
133
|
-
const cache = resolveCacheInstance(this);
|
|
134
|
-
|
|
135
|
-
const performEviction = async () => {
|
|
136
|
-
if (options.key) {
|
|
137
|
-
const k = typeof options.key === 'function' ? options.key(...args) : options.key;
|
|
138
|
-
await cache.delete(k);
|
|
139
|
-
}
|
|
140
|
-
if (options.tags) {
|
|
141
|
-
const t = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
142
|
-
await cache.invalidateTags(t);
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
if (options.beforeInvocation) {
|
|
147
|
-
await performEviction();
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const result = await originalMethod.apply(this, args);
|
|
151
|
-
|
|
152
|
-
if (!options.beforeInvocation) {
|
|
153
|
-
await performEviction();
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
return result;
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
return descriptor;
|
|
160
|
-
};
|
|
161
|
-
}
|
|
1
|
+
import { CacheService } from '../cache-service.js';
|
|
2
|
+
import type { CachePriority } from '../types.js';
|
|
3
|
+
|
|
4
|
+
export interface CacheableOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Static key string or dynamic key generator function.
|
|
7
|
+
* Example: (id: string) => `user:${id}`
|
|
8
|
+
*/
|
|
9
|
+
key?: string | ((...args: any[]) => string);
|
|
10
|
+
/** TTL in seconds (or milliseconds if specified / detected). Default: 300 s. */
|
|
11
|
+
ttl?: number;
|
|
12
|
+
/** Explicit time unit for the ttl option. Default: 'seconds'. */
|
|
13
|
+
ttlUnit?: 'seconds' | 'milliseconds';
|
|
14
|
+
/** Stale-While-Revalidate grace period in seconds. */
|
|
15
|
+
swr?: number;
|
|
16
|
+
/** Semantic tags for invalidation. */
|
|
17
|
+
tags?: string[] | ((...args: any[]) => string[]);
|
|
18
|
+
/** Dependency cascade patterns. */
|
|
19
|
+
dependsOn?: string[] | ((...args: any[]) => string[]);
|
|
20
|
+
/** Cache eviction priority. */
|
|
21
|
+
priority?: CachePriority;
|
|
22
|
+
/** 0–1 fraction of TTL elapsed for background recompute. */
|
|
23
|
+
refreshAhead?: number;
|
|
24
|
+
/** XFetch probabilistic early expiration factor (0.5–2.0). */
|
|
25
|
+
xfetchBeta?: number;
|
|
26
|
+
/** Condition predicate to determine whether caching should occur. */
|
|
27
|
+
condition?: (...args: any[]) => boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CacheEvictOptions {
|
|
31
|
+
/** Key or pattern to delete. */
|
|
32
|
+
key?: string | ((...args: any[]) => string);
|
|
33
|
+
/** Tags to invalidate. */
|
|
34
|
+
tags?: string[] | ((...args: any[]) => string[]);
|
|
35
|
+
/** Invalidate before method execution (default: false = after successful execution). */
|
|
36
|
+
beforeInvocation?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function resolveCacheInstance(ctx: any): CacheService {
|
|
40
|
+
return ctx?.cacheService || ctx?.cache || ctx?.cacheStore?.cache || CacheService.create();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Declarative method decorator that caches the return value of an async method.
|
|
45
|
+
*
|
|
46
|
+
* Automatically intercepts calls, checks TriCache (L1 -> L1.5 -> L2), and falls
|
|
47
|
+
* back to executing the decorated method on cache miss with thundering-herd protection.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* @Injectable()
|
|
52
|
+
* export class UserService {
|
|
53
|
+
* @Cacheable({ key: (id) => `user:${id}`, ttl: 300, tags: ['users'] })
|
|
54
|
+
* async findById(id: string) {
|
|
55
|
+
* return this.db.find(id);
|
|
56
|
+
* }
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export function Cacheable(options: CacheableOptions = {}): MethodDecorator {
|
|
61
|
+
return function (
|
|
62
|
+
target: any,
|
|
63
|
+
propertyKey: string | symbol,
|
|
64
|
+
descriptor: TypedPropertyDescriptor<any>,
|
|
65
|
+
) {
|
|
66
|
+
const originalMethod = descriptor.value;
|
|
67
|
+
const methodName = String(propertyKey);
|
|
68
|
+
const className = target?.constructor?.name || 'Service';
|
|
69
|
+
|
|
70
|
+
descriptor.value = async function (...args: any[]) {
|
|
71
|
+
if (options.condition && !options.condition(...args)) {
|
|
72
|
+
return originalMethod.apply(this, args);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const cache = resolveCacheInstance(this);
|
|
76
|
+
const key = typeof options.key === 'function'
|
|
77
|
+
? options.key(...args)
|
|
78
|
+
: (typeof options.key === 'string' ? options.key : `${className}:${methodName}:${JSON.stringify(args)}`);
|
|
79
|
+
|
|
80
|
+
let ttlSeconds = options.ttl ?? 300;
|
|
81
|
+
const rawTtl = options.ttl;
|
|
82
|
+
if (typeof rawTtl === 'number') {
|
|
83
|
+
if (options.ttlUnit === 'milliseconds' || (rawTtl >= 1000 && rawTtl % 1000 === 0 && options.ttlUnit !== 'seconds')) {
|
|
84
|
+
ttlSeconds = Math.round(rawTtl / 1000);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const tags = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
89
|
+
const dependsOn = typeof options.dependsOn === 'function' ? options.dependsOn(...args) : options.dependsOn;
|
|
90
|
+
|
|
91
|
+
return cache.wrap(
|
|
92
|
+
key,
|
|
93
|
+
() => originalMethod.apply(this, args),
|
|
94
|
+
{
|
|
95
|
+
ttl: ttlSeconds,
|
|
96
|
+
swr: options.swr,
|
|
97
|
+
tags,
|
|
98
|
+
dependsOn,
|
|
99
|
+
priority: options.priority,
|
|
100
|
+
refreshAhead: options.refreshAhead,
|
|
101
|
+
xfetchBeta: options.xfetchBeta,
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return descriptor;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Declarative method decorator that invalidates cache keys or tags upon method execution.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```typescript
|
|
115
|
+
* @Injectable()
|
|
116
|
+
* export class UserService {
|
|
117
|
+
* @CacheEvict({ tags: ['users'] })
|
|
118
|
+
* async update(id: string, dto: UpdateUserDto) {
|
|
119
|
+
* return this.db.update(id, dto);
|
|
120
|
+
* }
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export function CacheEvict(options: CacheEvictOptions = {}): MethodDecorator {
|
|
125
|
+
return function (
|
|
126
|
+
_target: any,
|
|
127
|
+
_propertyKey: string | symbol,
|
|
128
|
+
descriptor: TypedPropertyDescriptor<any>,
|
|
129
|
+
) {
|
|
130
|
+
const originalMethod = descriptor.value;
|
|
131
|
+
|
|
132
|
+
descriptor.value = async function (...args: any[]) {
|
|
133
|
+
const cache = resolveCacheInstance(this);
|
|
134
|
+
|
|
135
|
+
const performEviction = async () => {
|
|
136
|
+
if (options.key) {
|
|
137
|
+
const k = typeof options.key === 'function' ? options.key(...args) : options.key;
|
|
138
|
+
await cache.delete(k);
|
|
139
|
+
}
|
|
140
|
+
if (options.tags) {
|
|
141
|
+
const t = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
142
|
+
await cache.invalidateTags(t);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
if (options.beforeInvocation) {
|
|
147
|
+
await performEviction();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const result = await originalMethod.apply(this, args);
|
|
151
|
+
|
|
152
|
+
if (!options.beforeInvocation) {
|
|
153
|
+
await performEviction();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return result;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
return descriptor;
|
|
160
|
+
};
|
|
161
|
+
}
|
package/src/nestjs/index.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import { TriCacheModule } from './tricache.module.js';
|
|
2
|
-
|
|
3
|
-
export { TriCacheModule };
|
|
4
|
-
export { TriCacheStore } from './tricache.store.js';
|
|
5
|
-
export {
|
|
6
|
-
Cacheable,
|
|
7
|
-
CacheEvict,
|
|
8
|
-
type CacheableOptions,
|
|
9
|
-
type CacheEvictOptions,
|
|
10
|
-
} from './decorators.js';
|
|
11
|
-
export {
|
|
12
|
-
TRICACHE_SERVICE,
|
|
13
|
-
CACHE_MANAGER,
|
|
14
|
-
type DynamicModule,
|
|
15
|
-
type Provider,
|
|
16
|
-
type InjectionToken,
|
|
17
|
-
type Type,
|
|
18
|
-
type TriCacheAsyncOptions,
|
|
19
|
-
type TriCacheOptionsFactory,
|
|
20
|
-
type NestCacheStore,
|
|
21
|
-
} from './types.js';
|
|
22
|
-
|
|
23
|
-
export default TriCacheModule;
|
|
1
|
+
import { TriCacheModule } from './tricache.module.js';
|
|
2
|
+
|
|
3
|
+
export { TriCacheModule };
|
|
4
|
+
export { TriCacheStore } from './tricache.store.js';
|
|
5
|
+
export {
|
|
6
|
+
Cacheable,
|
|
7
|
+
CacheEvict,
|
|
8
|
+
type CacheableOptions,
|
|
9
|
+
type CacheEvictOptions,
|
|
10
|
+
} from './decorators.js';
|
|
11
|
+
export {
|
|
12
|
+
TRICACHE_SERVICE,
|
|
13
|
+
CACHE_MANAGER,
|
|
14
|
+
type DynamicModule,
|
|
15
|
+
type Provider,
|
|
16
|
+
type InjectionToken,
|
|
17
|
+
type Type,
|
|
18
|
+
type TriCacheAsyncOptions,
|
|
19
|
+
type TriCacheOptionsFactory,
|
|
20
|
+
type NestCacheStore,
|
|
21
|
+
} from './types.js';
|
|
22
|
+
|
|
23
|
+
export default TriCacheModule;
|