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.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,624 @@
1
+ /**
2
+ * tricache — Native Window TinyLFU (W-TinyLFU) Admission Engine
3
+ *
4
+ * Implements the state-of-the-art W-TinyLFU cache architecture popularized by Caffeine:
5
+ *
6
+ * [Incoming Entry]
7
+ * │
8
+ * ▼
9
+ * ┌───────────────────────────┐
10
+ * │ Window Cache (LRU) │ ~1% of Total Capacity
11
+ * │ (Absorbs Burst Recency) │
12
+ * └─────────────┬─────────────┘
13
+ * │ Evicted from Window
14
+ * ▼
15
+ * [TinyLFU Admission]
16
+ * Freq(Candidate) > Freq(Victim)?
17
+ * │
18
+ * ┌───────────────┴───────────────┐
19
+ * │ YES │ NO
20
+ * ▼ ▼
21
+ * ┌──────────────────────┐ [Drop Candidate]
22
+ * │ Probationary SLRU │ ~20% of Main
23
+ * └──────────┬───────────┘
24
+ * │ On 2nd Hit
25
+ * ▼
26
+ * ┌──────────────────────┐
27
+ * │ Protected SLRU │ ~80% of Main
28
+ * └──────────────────────┘
29
+ *
30
+ * Characteristics:
31
+ * - Pure TypeScript with zero external dependencies
32
+ * - Mathematical scan resistance: large sequential scans never pollute the main cache
33
+ * - Burst recency absorption: short-lived temporal spikes hit in the Window without eviction churn
34
+ * - Near-optimal theoretical hit ratios on Zipfian distributions
35
+ */
36
+
37
+ export interface WTinyLfuOptions {
38
+ /** Total maximum number of entries across all segments (Window + Probation + Protected). Default: 10,000 */
39
+ capacity: number;
40
+ /** Fraction of total capacity dedicated to Window Cache for burst recency absorption. Default: 0.01 (1%) */
41
+ windowPercent?: number;
42
+ /** Fraction of main SLRU space allocated to Protected segment. Default: 0.80 (80%) */
43
+ protectedPercent?: number;
44
+ /** Width of Count-Min Sketch rows (power of 2). Default: 1024 */
45
+ sketchWidth?: number;
46
+ }
47
+
48
+ export interface WTinyLfuStats {
49
+ capacity: number;
50
+ size: number;
51
+ windowSize: number;
52
+ probationSize: number;
53
+ protectedSize: number;
54
+ hits: number;
55
+ misses: number;
56
+ hitRate: number;
57
+ admissions: number;
58
+ rejections: number;
59
+ demotions: number;
60
+ promotions: number;
61
+ }
62
+
63
+ export interface EvictionResult<K, V> {
64
+ evicted?: { key: K; value: V; segment: 'window' | 'probation' | 'protected' };
65
+ rejected?: { key: K; value: V; segment: 'window' };
66
+ }
67
+
68
+ /**
69
+ * 4-row Count-Min Sketch for TinyLFU frequency estimation.
70
+ * Uses Murmur3-style bit-mixes of FNV-1a digests with periodic halving decay.
71
+ */
72
+ export class TinyLfuSketch {
73
+ private readonly rows = 4;
74
+ private readonly width: number;
75
+ private readonly mask: number;
76
+ private readonly table: Uint16Array;
77
+ private insertions = 0;
78
+ private readonly decayThreshold: number;
79
+
80
+ constructor(width = 1024, decayThreshold?: number) {
81
+ // Ensure power of 2
82
+ let w = 1;
83
+ while (w < width) w <<= 1;
84
+ this.width = w;
85
+ this.mask = w - 1;
86
+ this.table = new Uint16Array(this.rows * this.width);
87
+ this.decayThreshold = decayThreshold ?? (width * 16);
88
+ }
89
+
90
+ private hash(key: string): number {
91
+ let h = 0x811c9dc5;
92
+ for (let i = 0; i < key.length; i++) {
93
+ h ^= key.charCodeAt(i);
94
+ h = (Math.imul(h, 0x01000193) >>> 0);
95
+ }
96
+ return h;
97
+ }
98
+
99
+ increment(key: string): void {
100
+ const h = this.hash(key);
101
+ const h1 = (h ^ (h >>> 16)) >>> 0;
102
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
103
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
104
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
105
+
106
+ const t = this.table;
107
+ const w = this.width;
108
+
109
+ const i0 = h1 & this.mask;
110
+ const i1 = w + (h2 & this.mask);
111
+ const i2 = (2 * w) + (h3 & this.mask);
112
+ const i3 = (3 * w) + (h4 & this.mask);
113
+
114
+ if (t[i0] < 0xffff) t[i0]++;
115
+ if (t[i1] < 0xffff) t[i1]++;
116
+ if (t[i2] < 0xffff) t[i2]++;
117
+ if (t[i3] < 0xffff) t[i3]++;
118
+
119
+ if (++this.insertions >= this.decayThreshold) {
120
+ this.decay();
121
+ }
122
+ }
123
+
124
+ estimate(key: string): number {
125
+ const h = this.hash(key);
126
+ const h1 = (h ^ (h >>> 16)) >>> 0;
127
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
128
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
129
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
130
+
131
+ const t = this.table;
132
+ const w = this.width;
133
+
134
+ return Math.min(
135
+ t[h1 & this.mask],
136
+ t[w + (h2 & this.mask)],
137
+ t[(2 * w) + (h3 & this.mask)],
138
+ t[(3 * w) + (h4 & this.mask)],
139
+ );
140
+ }
141
+
142
+ decay(): void {
143
+ for (let i = 0; i < this.table.length; i++) {
144
+ this.table[i] >>>= 1;
145
+ }
146
+ this.insertions = 0;
147
+ }
148
+
149
+ clear(): void {
150
+ this.table.fill(0);
151
+ this.insertions = 0;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Window TinyLFU (W-TinyLFU) Segmented Cache.
157
+ */
158
+ export class WTinyLfuCache<K = string, V = unknown> {
159
+ private readonly maxTotal: number;
160
+ private readonly maxWindow: number;
161
+ private readonly maxProtected: number;
162
+ private readonly maxProbation: number;
163
+
164
+ // Segments (Map preserves insertion order: oldest is first key, MRU is last key)
165
+ private readonly window = new Map<K, V>();
166
+ private readonly probation = new Map<K, V>();
167
+ private readonly protected_ = new Map<K, V>();
168
+
169
+ // TinyLFU Frequency Sketch
170
+ private readonly sketch: TinyLfuSketch;
171
+
172
+ // Telemetry metrics
173
+ private hitCount = 0;
174
+ private missCount = 0;
175
+ private admissionCount = 0;
176
+ private rejectionCount = 0;
177
+ private promotionCount = 0;
178
+ private demotionCount = 0;
179
+
180
+ constructor(options: WTinyLfuOptions) {
181
+ this.maxTotal = Math.max(2, options.capacity);
182
+
183
+ const winPercent = options.windowPercent ?? 0.01;
184
+ this.maxWindow = Math.max(1, Math.floor(this.maxTotal * winPercent));
185
+
186
+ const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
187
+ const protPercent = options.protectedPercent ?? 0.80;
188
+ this.maxProtected = Math.max(1, Math.floor(mainCapacity * protPercent));
189
+ this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
190
+
191
+ this.sketch = new TinyLfuSketch(options.sketchWidth ?? 1024);
192
+ }
193
+
194
+ get capacity(): number {
195
+ return this.maxTotal;
196
+ }
197
+
198
+ get size(): number {
199
+ return this.window.size + this.probation.size + this.protected_.size;
200
+ }
201
+
202
+ private keyToString(key: K): string {
203
+ return typeof key === 'string' ? key : String(key);
204
+ }
205
+
206
+ /**
207
+ * Retrieves an entry and performs W-TinyLFU access promotion.
208
+ */
209
+ get(key: K): V | undefined {
210
+ const keyStr = this.keyToString(key);
211
+ this.sketch.increment(keyStr);
212
+
213
+ // 1. Check Window Cache
214
+ if (this.window.has(key)) {
215
+ const val = this.window.get(key)!;
216
+ // Refresh MRU in Window
217
+ this.window.delete(key);
218
+ this.window.set(key, val);
219
+ this.hitCount++;
220
+ return val;
221
+ }
222
+
223
+ // 2. Check Protected Segment
224
+ if (this.protected_.has(key)) {
225
+ const val = this.protected_.get(key)!;
226
+ // Refresh MRU in Protected
227
+ this.protected_.delete(key);
228
+ this.protected_.set(key, val);
229
+ this.hitCount++;
230
+ return val;
231
+ }
232
+
233
+ // 3. Check Probationary Segment
234
+ if (this.probation.has(key)) {
235
+ const val = this.probation.get(key)!;
236
+ this.probation.delete(key);
237
+
238
+ // Promote to Protected on 2nd hit
239
+ this.promotionCount++;
240
+ this.protected_.set(key, val);
241
+
242
+ // Handle Protected overflow: demote LRU of Protected back to Probation
243
+ if (this.protected_.size > this.maxProtected) {
244
+ const oldestProtKey = this.protected_.keys().next().value!;
245
+ const oldestProtVal = this.protected_.get(oldestProtKey)!;
246
+ this.protected_.delete(oldestProtKey);
247
+ this.probation.set(oldestProtKey, oldestProtVal);
248
+ this.demotionCount++;
249
+ }
250
+
251
+ this.hitCount++;
252
+ return val;
253
+ }
254
+
255
+ this.missCount++;
256
+ return undefined;
257
+ }
258
+
259
+ /**
260
+ * Returns true if key exists in any segment without updating access frequency.
261
+ */
262
+ has(key: K): boolean {
263
+ return this.window.has(key) || this.probation.has(key) || this.protected_.has(key);
264
+ }
265
+
266
+ /**
267
+ * Puts an entry into the cache using W-TinyLFU admission policies.
268
+ */
269
+ set(key: K, value: V): EvictionResult<K, V> {
270
+ const keyStr = this.keyToString(key);
271
+ this.sketch.increment(keyStr);
272
+
273
+ const result: EvictionResult<K, V> = {};
274
+
275
+ // ── 1. Update existing key if present in any segment ────────────────────
276
+ if (this.window.has(key)) {
277
+ this.window.delete(key);
278
+ this.window.set(key, value);
279
+ return result;
280
+ }
281
+
282
+ if (this.protected_.has(key)) {
283
+ this.protected_.delete(key);
284
+ this.protected_.set(key, value);
285
+ return result;
286
+ }
287
+
288
+ if (this.probation.has(key)) {
289
+ this.probation.delete(key);
290
+ this.probation.set(key, value);
291
+ return result;
292
+ }
293
+
294
+ // ── 2. New key: Admit into Window Cache ─────────────────────────────────
295
+ this.window.set(key, value);
296
+
297
+ // If Window does not exceed capacity, admission complete
298
+ if (this.window.size <= this.maxWindow) {
299
+ this.admissionCount++;
300
+ return result;
301
+ }
302
+
303
+ // ── 3. Window Overflow: Candidate evicts from Window to TinyLFU Gate ────
304
+ const candKey = this.window.keys().next().value!;
305
+ const candVal = this.window.get(candKey)!;
306
+ this.window.delete(candKey);
307
+
308
+ // If Main cache has headroom, admit candidate directly to Probation
309
+ if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
310
+ this.probation.set(candKey, candVal);
311
+ this.admissionCount++;
312
+ return result;
313
+ }
314
+
315
+ // ── 4. TinyLFU Admission Gate: Candidate vs Probation Victim ────────────
316
+ // Find victim: LRU of Probationary segment (or LRU of Protected if Probation empty)
317
+ let victimKey: K;
318
+ let victimVal: V;
319
+ let victimSegment: 'probation' | 'protected';
320
+
321
+ if (this.probation.size > 0) {
322
+ victimKey = this.probation.keys().next().value!;
323
+ victimVal = this.probation.get(victimKey)!;
324
+ victimSegment = 'probation';
325
+ } else {
326
+ victimKey = this.protected_.keys().next().value!;
327
+ victimVal = this.protected_.get(victimKey)!;
328
+ victimSegment = 'protected';
329
+ }
330
+
331
+ const candFreq = this.sketch.estimate(this.keyToString(candKey));
332
+ const victimFreq = this.sketch.estimate(this.keyToString(victimKey));
333
+
334
+ if (candFreq > victimFreq) {
335
+ // Candidate WINS admission: evict victim, admit candidate to Probation
336
+ if (victimSegment === 'probation') {
337
+ this.probation.delete(victimKey);
338
+ } else {
339
+ this.protected_.delete(victimKey);
340
+ }
341
+
342
+ this.probation.set(candKey, candVal);
343
+ this.admissionCount++;
344
+ result.evicted = { key: victimKey, value: victimVal, segment: victimSegment };
345
+ } else {
346
+ // Candidate LOSES admission: candidate is rejected/dropped
347
+ this.rejectionCount++;
348
+ result.rejected = { key: candKey, value: candVal, segment: 'window' };
349
+ }
350
+
351
+ return result;
352
+ }
353
+
354
+ /**
355
+ * Removes a key from whichever segment it resides in.
356
+ */
357
+ delete(key: K): boolean {
358
+ return this.window.delete(key) || this.probation.delete(key) || this.protected_.delete(key);
359
+ }
360
+
361
+ /**
362
+ * Resets all segments, sketch, and metrics.
363
+ */
364
+ clear(): void {
365
+ this.window.clear();
366
+ this.probation.clear();
367
+ this.protected_.clear();
368
+ this.sketch.clear();
369
+ this.hitCount = 0;
370
+ this.missCount = 0;
371
+ this.admissionCount = 0;
372
+ this.rejectionCount = 0;
373
+ this.promotionCount = 0;
374
+ this.demotionCount = 0;
375
+ }
376
+
377
+ /**
378
+ * Returns current telemetry and hit-ratio stats.
379
+ */
380
+ stats(): WTinyLfuStats {
381
+ const totalRequests = this.hitCount + this.missCount;
382
+ return {
383
+ capacity: this.maxTotal,
384
+ size: this.size,
385
+ windowSize: this.window.size,
386
+ probationSize: this.probation.size,
387
+ protectedSize: this.protected_.size,
388
+ hits: this.hitCount,
389
+ misses: this.missCount,
390
+ hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
391
+ admissions: this.admissionCount,
392
+ rejections: this.rejectionCount,
393
+ promotions: this.promotionCount,
394
+ demotions: this.demotionCount,
395
+ };
396
+ }
397
+
398
+ getStats(): WTinyLfuStats {
399
+ return this.stats();
400
+ }
401
+
402
+ /**
403
+ * Returns an iterator of all keys currently in the cache.
404
+ */
405
+ *keys(): IterableIterator<K> {
406
+ yield* this.window.keys();
407
+ yield* this.probation.keys();
408
+ yield* this.protected_.keys();
409
+ }
410
+
411
+ /**
412
+ * Returns an iterator of all entries currently in the cache.
413
+ */
414
+ *entries(): IterableIterator<[K, V]> {
415
+ yield* this.window.entries();
416
+ yield* this.probation.entries();
417
+ yield* this.protected_.entries();
418
+ }
419
+
420
+ /**
421
+ * Returns segment membership for a key ('window', 'probation', 'protected', or null).
422
+ */
423
+ getSegment(key: K): 'window' | 'probation' | 'protected' | null {
424
+ if (this.window.has(key)) return 'window';
425
+ if (this.probation.has(key)) return 'probation';
426
+ if (this.protected_.has(key)) return 'protected';
427
+ return null;
428
+ }
429
+ }
430
+
431
+ export interface WTinyLfuAdmissionDecision {
432
+ admit: boolean;
433
+ evictKey?: string;
434
+ candidateKey?: string;
435
+ }
436
+
437
+ /**
438
+ * Lightweight W-TinyLFU policy controller for existing tiered caches like SmartMemoryCache.
439
+ */
440
+ export class WTinyLfuPolicy {
441
+ private readonly maxTotal: number;
442
+ private readonly maxWindow: number;
443
+ private readonly maxProtected: number;
444
+ private readonly maxProbation: number;
445
+
446
+ private readonly window = new Set<string>();
447
+ private readonly probation = new Set<string>();
448
+ private readonly protected_ = new Set<string>();
449
+
450
+ // Telemetry metrics
451
+ private hitCount = 0;
452
+ private missCount = 0;
453
+ private admissionCount = 0;
454
+ private rejectionCount = 0;
455
+ private promotionCount = 0;
456
+ private demotionCount = 0;
457
+
458
+ constructor(
459
+ capacity: number,
460
+ private readonly sketch: { estimate(key: string): number; increment(key: string): void },
461
+ windowPercent = 0.01,
462
+ protectedPercent = 0.80,
463
+ ) {
464
+ this.maxTotal = Math.max(2, capacity);
465
+ this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
466
+ const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
467
+ this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
468
+ this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
469
+ }
470
+
471
+ get windowSize(): number {
472
+ return this.window.size;
473
+ }
474
+
475
+ get probationSize(): number {
476
+ return this.probation.size;
477
+ }
478
+
479
+ get protectedSize(): number {
480
+ return this.protected_.size;
481
+ }
482
+
483
+ onAccess(key: string): void {
484
+ if (this.window.has(key)) {
485
+ this.window.delete(key);
486
+ this.window.add(key); // MRU
487
+ this.hitCount++;
488
+ return;
489
+ }
490
+
491
+ if (this.protected_.has(key)) {
492
+ this.protected_.delete(key);
493
+ this.protected_.add(key); // MRU
494
+ this.hitCount++;
495
+ return;
496
+ }
497
+
498
+ if (this.probation.has(key)) {
499
+ this.probation.delete(key);
500
+ this.protected_.add(key); // Promote to Protected on 2nd hit
501
+ this.promotionCount++;
502
+ this.hitCount++;
503
+
504
+ // Protected overflow -> demote oldest to Probation
505
+ if (this.protected_.size > this.maxProtected) {
506
+ const oldestProtKey = this.protected_.values().next().value!;
507
+ this.protected_.delete(oldestProtKey);
508
+ this.probation.add(oldestProtKey);
509
+ this.demotionCount++;
510
+ }
511
+ return;
512
+ }
513
+
514
+ this.missCount++;
515
+ }
516
+
517
+ onSet(key: string, isUpdate: boolean): WTinyLfuAdmissionDecision {
518
+ if (isUpdate) {
519
+ if (this.window.has(key)) {
520
+ this.window.delete(key);
521
+ this.window.add(key);
522
+ } else if (this.protected_.has(key)) {
523
+ this.protected_.delete(key);
524
+ this.protected_.add(key);
525
+ } else if (this.probation.has(key)) {
526
+ this.probation.delete(key);
527
+ this.probation.add(key);
528
+ }
529
+ return { admit: true };
530
+ }
531
+
532
+ // New key: admit to Window
533
+ this.window.add(key);
534
+
535
+ if (this.window.size <= this.maxWindow) {
536
+ this.admissionCount++;
537
+ return { admit: true };
538
+ }
539
+
540
+ // Window overflow: pop candidate from Window
541
+ const candKey = this.window.values().next().value!;
542
+ this.window.delete(candKey);
543
+
544
+ // If main cache has headroom, admit to Probation
545
+ if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
546
+ this.probation.add(candKey);
547
+ this.admissionCount++;
548
+ return { admit: true };
549
+ }
550
+
551
+ // Main space full: TinyLFU gate
552
+ let victimKey: string;
553
+ let victimIsProbation = true;
554
+
555
+ if (this.probation.size > 0) {
556
+ victimKey = this.probation.values().next().value!;
557
+ } else {
558
+ victimKey = this.protected_.values().next().value!;
559
+ victimIsProbation = false;
560
+ }
561
+
562
+ const candFreq = this.sketch.estimate(candKey);
563
+ const victimFreq = this.sketch.estimate(victimKey);
564
+
565
+ if (candFreq > victimFreq) {
566
+ // Candidate wins: evict victim, admit candidate to Probation
567
+ if (victimIsProbation) {
568
+ this.probation.delete(victimKey);
569
+ } else {
570
+ this.protected_.delete(victimKey);
571
+ }
572
+ this.probation.add(candKey);
573
+ this.admissionCount++;
574
+ return { admit: true, evictKey: victimKey, candidateKey: candKey };
575
+ } else {
576
+ // Candidate loses: rejected
577
+ this.rejectionCount++;
578
+ return { admit: false, candidateKey: candKey };
579
+ }
580
+ }
581
+
582
+ onDelete(key: string): void {
583
+ this.window.delete(key);
584
+ this.probation.delete(key);
585
+ this.protected_.delete(key);
586
+ }
587
+
588
+ clear(): void {
589
+ this.window.clear();
590
+ this.probation.clear();
591
+ this.protected_.clear();
592
+ this.hitCount = 0;
593
+ this.missCount = 0;
594
+ this.admissionCount = 0;
595
+ this.rejectionCount = 0;
596
+ this.promotionCount = 0;
597
+ this.demotionCount = 0;
598
+ }
599
+
600
+ getStats(): WTinyLfuStats {
601
+ const totalRequests = this.hitCount + this.missCount;
602
+ return {
603
+ capacity: this.maxTotal,
604
+ size: this.window.size + this.probation.size + this.protected_.size,
605
+ windowSize: this.window.size,
606
+ probationSize: this.probation.size,
607
+ protectedSize: this.protected_.size,
608
+ hits: this.hitCount,
609
+ misses: this.missCount,
610
+ hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
611
+ admissions: this.admissionCount,
612
+ rejections: this.rejectionCount,
613
+ promotions: this.promotionCount,
614
+ demotions: this.demotionCount,
615
+ };
616
+ }
617
+
618
+ getSegment(key: string): 'window' | 'probation' | 'protected' | null {
619
+ if (this.window.has(key)) return 'window';
620
+ if (this.probation.has(key)) return 'probation';
621
+ if (this.protected_.has(key)) return 'protected';
622
+ return null;
623
+ }
624
+ }
@@ -1,7 +0,0 @@
1
- import {
2
- CacheService
3
- } from "./chunk-3XQUQBOZ.js";
4
- import "./chunk-PFB5FMEY.js";
5
- export {
6
- CacheService
7
- };
File without changes