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
package/src/disk-tier.ts
CHANGED
|
@@ -1,821 +1,1223 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
3
|
-
*
|
|
4
|
-
* When L1 evicts an entry it is spilled here instead of being discarded.
|
|
5
|
-
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
6
|
-
* vs 10–100 ms DB round-trip).
|
|
7
|
-
*
|
|
8
|
-
* Storage:
|
|
9
|
-
* - Directory: configurable (default os.tmpdir()/tricache-disk)
|
|
10
|
-
* - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
|
|
11
|
-
* - Format: msgpack({ version, key, entry, writtenAt })
|
|
12
|
-
* - Mode: 0o600 — owner read/write only
|
|
13
|
-
*
|
|
14
|
-
* Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import fs from 'fs';
|
|
18
|
-
import path from 'path';
|
|
19
|
-
import crypto from 'crypto';
|
|
20
|
-
import
|
|
21
|
-
import
|
|
22
|
-
import type {
|
|
23
|
-
import {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
private
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
private
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
*
|
|
323
|
-
*
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
this.
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
//
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
try {
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
1
|
+
/**
|
|
2
|
+
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
3
|
+
*
|
|
4
|
+
* When L1 evicts an entry it is spilled here instead of being discarded.
|
|
5
|
+
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
6
|
+
* vs 10–100 ms DB round-trip).
|
|
7
|
+
*
|
|
8
|
+
* Storage:
|
|
9
|
+
* - Directory: configurable (default os.tmpdir()/tricache-disk)
|
|
10
|
+
* - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
|
|
11
|
+
* - Format: msgpack({ version, key, entry, writtenAt })
|
|
12
|
+
* - Mode: 0o600 — owner read/write only
|
|
13
|
+
*
|
|
14
|
+
* Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import fs from 'fs';
|
|
18
|
+
import path from 'path';
|
|
19
|
+
import crypto from 'crypto';
|
|
20
|
+
import os from 'os';
|
|
21
|
+
import { CacheCodec, defaultCodec } from './codec.js';
|
|
22
|
+
import type { DiskCacheEntry, ILogger, DiskBackpressureStats } from './types.js';
|
|
23
|
+
import type { CacheEncryption } from './encryption.js';
|
|
24
|
+
import {
|
|
25
|
+
compressWithHeader,
|
|
26
|
+
decompressWithHeader,
|
|
27
|
+
type CompressionAlgorithm,
|
|
28
|
+
} from './compression.js';
|
|
29
|
+
|
|
30
|
+
export type { DiskBackpressureStats };
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* BoundedDiskQueue — Concurrency-controlled write spooler with circuit breaking.
|
|
34
|
+
*
|
|
35
|
+
* Prevents libuv threadpool (UV_THREADPOOL_SIZE=4) starvation during cloud NVMe / EBS
|
|
36
|
+
* latency spikes (e.g. 450ms multi-tenant throttle) by limiting active async fs operations,
|
|
37
|
+
* bounding in-memory pending queues, and fast-shedding spills via a 3-state circuit breaker
|
|
38
|
+
* (CLOSED -> OPEN -> HALF-OPEN canary).
|
|
39
|
+
*/
|
|
40
|
+
export class BoundedDiskQueue {
|
|
41
|
+
private active = 0;
|
|
42
|
+
private queue: Array<() => void> = [];
|
|
43
|
+
private spillsDropped = 0;
|
|
44
|
+
private consecutiveFailures = 0;
|
|
45
|
+
private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
|
|
46
|
+
private lastStateChangeMonotonic = performance.now();
|
|
47
|
+
|
|
48
|
+
constructor(
|
|
49
|
+
private readonly maxConcurrent: number = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4))),
|
|
50
|
+
private readonly maxPending: number = 512,
|
|
51
|
+
private readonly writeTimeoutMs: number = 500,
|
|
52
|
+
private readonly failureThreshold: number = 5,
|
|
53
|
+
private readonly cooldownMs: number = 5000,
|
|
54
|
+
) {}
|
|
55
|
+
|
|
56
|
+
public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
|
|
57
|
+
const now = performance.now();
|
|
58
|
+
|
|
59
|
+
// Check circuit breaker state
|
|
60
|
+
if (this.circuitState === 'open') {
|
|
61
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
62
|
+
this.circuitState = 'half-open';
|
|
63
|
+
this.lastStateChangeMonotonic = now;
|
|
64
|
+
} else {
|
|
65
|
+
this.spillsDropped++;
|
|
66
|
+
return null; // Fast-drop spill without touching libuv
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (this.circuitState === 'half-open' && this.active > 0) {
|
|
71
|
+
// In half-open mode, only allow 1 canary write
|
|
72
|
+
this.spillsDropped++;
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (this.queue.length >= this.maxPending) {
|
|
77
|
+
this.spillsDropped++;
|
|
78
|
+
return null; // Bounded memory queue: drop spill to preserve main thread
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Wait for slot in concurrency pool
|
|
82
|
+
if (this.active >= this.maxConcurrent) {
|
|
83
|
+
await new Promise<void>((resolve) => this.queue.push(resolve));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
this.active++;
|
|
87
|
+
let timeoutId: NodeJS.Timeout | null = null;
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const result = await Promise.race([
|
|
91
|
+
task(),
|
|
92
|
+
new Promise<never>((_, reject) => {
|
|
93
|
+
timeoutId = setTimeout(
|
|
94
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
95
|
+
this.writeTimeoutMs,
|
|
96
|
+
);
|
|
97
|
+
}),
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
// Success: reset breaker
|
|
101
|
+
this.consecutiveFailures = 0;
|
|
102
|
+
if (this.circuitState === 'half-open') {
|
|
103
|
+
this.circuitState = 'closed';
|
|
104
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return result;
|
|
108
|
+
} catch {
|
|
109
|
+
this.consecutiveFailures++;
|
|
110
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === 'half-open') {
|
|
111
|
+
this.circuitState = 'open';
|
|
112
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
113
|
+
}
|
|
114
|
+
this.spillsDropped++;
|
|
115
|
+
return null;
|
|
116
|
+
} finally {
|
|
117
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
118
|
+
this.active--;
|
|
119
|
+
const next = this.queue.shift();
|
|
120
|
+
if (next) next();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public getStats(): DiskBackpressureStats {
|
|
125
|
+
return {
|
|
126
|
+
activeWrites: this.active,
|
|
127
|
+
pendingWrites: this.queue.length,
|
|
128
|
+
spillsDropped: this.spillsDropped,
|
|
129
|
+
circuitState: this.circuitState,
|
|
130
|
+
lastTripTimestamp: this.lastStateChangeMonotonic,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
public reset(): void {
|
|
135
|
+
this.consecutiveFailures = 0;
|
|
136
|
+
this.circuitState = 'closed';
|
|
137
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
|
|
142
|
+
// Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
|
|
143
|
+
// Falls back to file-only mode silently when unavailable (edge runtimes, etc.).
|
|
144
|
+
type _SqliteRow = Record<string, unknown>;
|
|
145
|
+
type _SqliteStmt = {
|
|
146
|
+
get(...p: unknown[]): _SqliteRow | undefined;
|
|
147
|
+
all(...p: unknown[]): _SqliteRow[];
|
|
148
|
+
run(...p: unknown[]): void;
|
|
149
|
+
};
|
|
150
|
+
type _SqliteDB = {
|
|
151
|
+
prepare(sql: string): _SqliteStmt;
|
|
152
|
+
exec(sql: string): void;
|
|
153
|
+
close(): void;
|
|
154
|
+
};
|
|
155
|
+
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
156
|
+
try {
|
|
157
|
+
// process.getBuiltinModule is available in Node >= 22.3.0.
|
|
158
|
+
// In Node 20 LTS or environments without node:sqlite, this safely falls back to file-only mode.
|
|
159
|
+
const proc = process as unknown as { getBuiltinModule?: (m: string) => unknown };
|
|
160
|
+
if (typeof proc.getBuiltinModule === 'function') {
|
|
161
|
+
const sqlite = proc.getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
|
|
162
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
163
|
+
}
|
|
164
|
+
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
165
|
+
// ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
|
|
166
|
+
// DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
|
|
167
|
+
// delegates the payload cipher to CacheEncryption, which already supports all four
|
|
168
|
+
// modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor) and is the single source of
|
|
169
|
+
// truth for the on-disk binary format. This avoids a hardcoded aes-256-gcm that
|
|
170
|
+
// threw (and silently no-op'd the disk tier) for any non-default mode.
|
|
171
|
+
const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
|
|
172
|
+
/**
|
|
173
|
+
* V2 file format — expiresAt stored in plaintext outside the ciphertext so the
|
|
174
|
+
* janitor can check expiry with a 16-byte header read rather than a full
|
|
175
|
+
* decrypt + unpack. Layout (bytes):
|
|
176
|
+
* 0–7 DISK_MAGIC_V2 ("DTIERV2\0")
|
|
177
|
+
* 8–15 expiresAt, uint64 LE (ms since epoch, outside encryption)
|
|
178
|
+
* 16+ encryptV2(msgpack(DiskPayload)) — IV+TAG+ct if key set, else raw msgpack
|
|
179
|
+
*/
|
|
180
|
+
const DISK_MAGIC_V2 = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x32, 0x00]); // "DTIERV2\0"
|
|
181
|
+
const V2_HEADER_LEN = 16; // magic(8) + expiresAt(8)
|
|
182
|
+
|
|
183
|
+
interface DiskPayload {
|
|
184
|
+
version: number;
|
|
185
|
+
key: string;
|
|
186
|
+
entry: DiskCacheEntry;
|
|
187
|
+
writtenAt: number;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const DISK_TIER_VERSION = 1;
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Resolves the default directory for DiskTier storage.
|
|
194
|
+
*
|
|
195
|
+
* In Linux container environments, checks if `/dev/shm` (POSIX shared memory tmpfs)
|
|
196
|
+
* is writable and has adequate capacity (total >= 256MB AND free >= 128MB).
|
|
197
|
+
* When valid, targets `/dev/shm` to provide an off-heap, zero-GC RAM extension
|
|
198
|
+
* that runs at memory speeds (~20µs) and burns zero cloud/EBS IOPS.
|
|
199
|
+
* If capacity or free space is insufficient, or on non-Linux platforms,
|
|
200
|
+
* gracefully falls back to `os.tmpdir()`.
|
|
201
|
+
*/
|
|
202
|
+
export function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): { dir: string; isShm: boolean } {
|
|
203
|
+
const ns = namespace?.trim() ?? '';
|
|
204
|
+
const nsDir = ns ? `tricache-disk-${ns}` : 'tricache-disk';
|
|
205
|
+
|
|
206
|
+
if (process.platform === 'linux') {
|
|
207
|
+
const shmPath = '/dev/shm';
|
|
208
|
+
try {
|
|
209
|
+
fs.accessSync(shmPath, fs.constants.W_OK | fs.constants.R_OK);
|
|
210
|
+
if (typeof fs.statfsSync === 'function') {
|
|
211
|
+
const stats = fs.statfsSync(shmPath);
|
|
212
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
213
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
214
|
+
|
|
215
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
216
|
+
const targetDir = path.join(shmPath, nsDir);
|
|
217
|
+
logger?.info?.('DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage', {
|
|
218
|
+
path: targetDir,
|
|
219
|
+
totalBytes,
|
|
220
|
+
freeBytes,
|
|
221
|
+
});
|
|
222
|
+
return { dir: targetDir, isShm: true };
|
|
223
|
+
} else {
|
|
224
|
+
logger?.info?.('DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir', {
|
|
225
|
+
totalBytes,
|
|
226
|
+
freeBytes,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch (err) {
|
|
231
|
+
logger?.debug?.('DiskTier: /dev/shm not usable, falling back to tmpdir', {
|
|
232
|
+
error: (err as Error).message,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return { dir: path.join(os.tmpdir(), nsDir), isShm: false };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
export interface DiskTierOptions {
|
|
243
|
+
dir: string;
|
|
244
|
+
maxBytes: number;
|
|
245
|
+
entryMaxBytes: number;
|
|
246
|
+
forbiddenPrefixes?: readonly string[];
|
|
247
|
+
/** Mode-aware encryption instance. When set, disk files are encrypted with the
|
|
248
|
+
* same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
|
|
249
|
+
* When null, files are written unencrypted. Pass `cache.encryption` here. */
|
|
250
|
+
encryption?: CacheEncryption | null;
|
|
251
|
+
compression?: CompressionAlgorithm;
|
|
252
|
+
compressionThresholdBytes?: number;
|
|
253
|
+
logger: ILogger;
|
|
254
|
+
codec?: CacheCodec;
|
|
255
|
+
diskMaxConcurrentWrites?: number;
|
|
256
|
+
diskMaxPendingWrites?: number;
|
|
257
|
+
diskWriteTimeoutMs?: number;
|
|
258
|
+
diskCircuitBreakerThreshold?: number;
|
|
259
|
+
diskCircuitBreakerCooldownMs?: number;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export class DiskTier {
|
|
263
|
+
private readonly opts: DiskTierOptions;
|
|
264
|
+
private readonly codec: CacheCodec;
|
|
265
|
+
private readonly diskQueue: BoundedDiskQueue;
|
|
266
|
+
private dirReady = false;
|
|
267
|
+
private diskUsageBytes = 0;
|
|
268
|
+
private usageCounted = false;
|
|
269
|
+
private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
|
|
270
|
+
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
271
|
+
private _nextJanitorBucket = 0;
|
|
272
|
+
|
|
273
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
274
|
+
private _isPruning = false;
|
|
275
|
+
private _pruneRounds = 0;
|
|
276
|
+
private _entriesPruned = 0;
|
|
277
|
+
private _spillsShedTotal = 0;
|
|
278
|
+
private _hostVolumeLowSpace = false;
|
|
279
|
+
private _hostVolumeLowSpacePauses = 0;
|
|
280
|
+
private _writeCounter = 0;
|
|
281
|
+
|
|
282
|
+
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
283
|
+
private _db: _SqliteDB | null = null;
|
|
284
|
+
private _stmtInsert: _SqliteStmt | null = null; // INSERT OR REPLACE
|
|
285
|
+
private _stmtSelect: _SqliteStmt | null = null; // SELECT by key_hash
|
|
286
|
+
private _stmtDelete: _SqliteStmt | null = null; // DELETE by key_hash
|
|
287
|
+
private _stmtExpire: _SqliteStmt | null = null; // SELECT expired rows
|
|
288
|
+
private _stmtDelExp: _SqliteStmt | null = null; // DELETE expired rows
|
|
289
|
+
private _stmtStats: _SqliteStmt | null = null; // COUNT + SUM(size)
|
|
290
|
+
private _stmtPruneChunk: _SqliteStmt | null = null; // SELECT chunk for watermark pruning
|
|
291
|
+
|
|
292
|
+
constructor(opts: DiskTierOptions) {
|
|
293
|
+
this.opts = opts;
|
|
294
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
295
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4)));
|
|
296
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
297
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
298
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
299
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
300
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
301
|
+
opts.diskCircuitBreakerCooldownMs ?? 5000,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
private ensureDir(): void {
|
|
308
|
+
if (this.dirReady) return;
|
|
309
|
+
try {
|
|
310
|
+
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
311
|
+
this.dirReady = true;
|
|
312
|
+
this._initSqlite();
|
|
313
|
+
} catch (err) {
|
|
314
|
+
this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: (err as Error).message });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
320
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
321
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
322
|
+
*
|
|
323
|
+
* Schema:
|
|
324
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
325
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
326
|
+
*
|
|
327
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
328
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
329
|
+
*/
|
|
330
|
+
private _initSqlite(): void {
|
|
331
|
+
if (!_SqliteDB) return;
|
|
332
|
+
try {
|
|
333
|
+
const dbPath = path.join(this.opts.dir, 'meta.db');
|
|
334
|
+
this._db = new _SqliteDB(dbPath);
|
|
335
|
+
this._db.exec(`
|
|
336
|
+
PRAGMA journal_mode = WAL;
|
|
337
|
+
PRAGMA synchronous = NORMAL;
|
|
338
|
+
PRAGMA temp_store = MEMORY;
|
|
339
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
340
|
+
key_hash TEXT PRIMARY KEY,
|
|
341
|
+
file_path TEXT NOT NULL,
|
|
342
|
+
expires_at INTEGER NOT NULL,
|
|
343
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
344
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
345
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
346
|
+
);
|
|
347
|
+
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
348
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
349
|
+
`);
|
|
350
|
+
|
|
351
|
+
// Migration guards for pre-existing databases without priority or last_accessed_at columns
|
|
352
|
+
try {
|
|
353
|
+
this._db.exec('ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;');
|
|
354
|
+
} catch { /* column already present */ }
|
|
355
|
+
try {
|
|
356
|
+
this._db.exec('ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;');
|
|
357
|
+
} catch { /* column already present */ }
|
|
358
|
+
try {
|
|
359
|
+
this._db.exec('CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);');
|
|
360
|
+
} catch { /* index already present */ }
|
|
361
|
+
|
|
362
|
+
this._stmtInsert = this._db.prepare(
|
|
363
|
+
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)',
|
|
364
|
+
);
|
|
365
|
+
this._stmtSelect = this._db.prepare(
|
|
366
|
+
'SELECT file_path, expires_at FROM meta WHERE key_hash = ?',
|
|
367
|
+
);
|
|
368
|
+
this._stmtDelete = this._db.prepare('DELETE FROM meta WHERE key_hash = ?');
|
|
369
|
+
this._stmtExpire = this._db.prepare(
|
|
370
|
+
'SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?',
|
|
371
|
+
);
|
|
372
|
+
this._stmtDelExp = this._db.prepare('DELETE FROM meta WHERE expires_at <= ?');
|
|
373
|
+
this._stmtStats = this._db.prepare(
|
|
374
|
+
'SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta',
|
|
375
|
+
);
|
|
376
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
377
|
+
'SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500',
|
|
378
|
+
);
|
|
379
|
+
// Seed in-memory counters from the index — avoids startup walkCacheFiles().
|
|
380
|
+
const row = this._stmtStats.get() as { cnt: number; bytes: number };
|
|
381
|
+
this.fileCount = row.cnt;
|
|
382
|
+
this.diskUsageBytes = row.bytes;
|
|
383
|
+
this.usageCounted = true;
|
|
384
|
+
this.opts.logger.debug('DiskTier: SQLite index ready', { entries: row.cnt });
|
|
385
|
+
} catch (err) {
|
|
386
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
387
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
388
|
+
this.opts.logger.warn('DiskTier: SQLite init failed, using file-only mode', {
|
|
389
|
+
error: (err as Error).message,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private ensureUsageCounted(): void {
|
|
395
|
+
if (this.usageCounted) return;
|
|
396
|
+
this.usageCounted = true;
|
|
397
|
+
// SQLite path: counts were already seeded in _initSqlite() — nothing more to do.
|
|
398
|
+
if (this._db) return;
|
|
399
|
+
try {
|
|
400
|
+
this.ensureDir();
|
|
401
|
+
let total = 0;
|
|
402
|
+
const files = this.walkCacheFiles();
|
|
403
|
+
this.fileCount = files.length;
|
|
404
|
+
for (const filePath of files) {
|
|
405
|
+
try { total += fs.statSync(filePath).size; } catch { /* ok */ }
|
|
406
|
+
}
|
|
407
|
+
this.diskUsageBytes = total;
|
|
408
|
+
} catch { this.diskUsageBytes = 0; this.fileCount = 0; }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
413
|
+
* Kept separate from path construction so callers can find files by prefix
|
|
414
|
+
* without knowing which filename generation was used when the file was written.
|
|
415
|
+
*/
|
|
416
|
+
private keyToHash(key: string): string {
|
|
417
|
+
return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Build the write path for a NEW file (V3 generation).
|
|
422
|
+
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
423
|
+
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
424
|
+
*
|
|
425
|
+
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
426
|
+
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
427
|
+
*
|
|
428
|
+
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
429
|
+
*/
|
|
430
|
+
private hashToWritePath(hash: string, expiresAt: number): string {
|
|
431
|
+
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, '0')}`);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Find the on-disk file for a key hash, handling all filename generations:
|
|
436
|
+
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
437
|
+
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
438
|
+
* Returns null when the bucket dir does not exist or the key is absent.
|
|
439
|
+
*/
|
|
440
|
+
private findFilePath(hash: string): string | null {
|
|
441
|
+
const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
|
|
442
|
+
let files: string[];
|
|
443
|
+
try { files = fs.readdirSync(bucketPath); } catch { return null; }
|
|
444
|
+
// Return the lexicographically largest match: V3 filenames are
|
|
445
|
+
// "{hash}_{expiresHex12}", so lex-max = largest timestamp = newest entry.
|
|
446
|
+
// If the same key was evicted to disk twice (different TTLs → different names),
|
|
447
|
+
// this ensures we always serve and delete the freshest copy; the janitor cleans
|
|
448
|
+
// up the stale one when its encoded timestamp expires.
|
|
449
|
+
let match: string | undefined;
|
|
450
|
+
for (const f of files) {
|
|
451
|
+
if ((f === hash || f.startsWith(hash + '_')) && (!match || f > match)) match = f;
|
|
452
|
+
}
|
|
453
|
+
if (!match) return null;
|
|
454
|
+
return path.join(bucketPath, match);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
459
|
+
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
460
|
+
* files written by older versions).
|
|
461
|
+
*/
|
|
462
|
+
private walkCacheFiles(): string[] {
|
|
463
|
+
const results: string[] = [];
|
|
464
|
+
let topEntries: string[];
|
|
465
|
+
try { topEntries = fs.readdirSync(this.opts.dir); } catch { return results; }
|
|
466
|
+
for (const top of topEntries) {
|
|
467
|
+
const topPath = path.join(this.opts.dir, top);
|
|
468
|
+
try {
|
|
469
|
+
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
470
|
+
for (const file of fs.readdirSync(topPath)) {
|
|
471
|
+
results.push(path.join(topPath, file));
|
|
472
|
+
}
|
|
473
|
+
} catch { /* skip locked/gone */ }
|
|
474
|
+
}
|
|
475
|
+
return results;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private isForbidden(key: string): boolean {
|
|
479
|
+
return this.opts.forbiddenPrefixes?.some(p => key.startsWith(p)) ?? false;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
private encrypt(data: Buffer): Buffer {
|
|
483
|
+
if (!this.opts.encryption) return data;
|
|
484
|
+
// V1 envelope: DISK_MAGIC prefix wrapping the mode-aware CacheEncryption blob.
|
|
485
|
+
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private decrypt(data: Buffer): Buffer {
|
|
489
|
+
const mLen = DISK_MAGIC.length;
|
|
490
|
+
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
491
|
+
if (!this.opts.encryption) throw new Error('DiskTier: entry is encrypted but no encryption configured');
|
|
492
|
+
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
497
|
+
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
498
|
+
* Returns the buffer unchanged when no encryption instance is configured.
|
|
499
|
+
*/
|
|
500
|
+
private encryptV2(data: Buffer): Buffer {
|
|
501
|
+
if (!this.opts.encryption) return data;
|
|
502
|
+
return this.opts.encryption.encryptBuffer(data);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
507
|
+
* When an encryption instance is configured the format is the mode-aware
|
|
508
|
+
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
509
|
+
* without one the payload is raw msgpack.
|
|
510
|
+
*/
|
|
511
|
+
private decryptV2(inner: Buffer): Buffer {
|
|
512
|
+
if (!this.opts.encryption) return inner;
|
|
513
|
+
return this.opts.encryption.decryptBuffer(inner);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Spill an evicted L1 entry to disk.
|
|
520
|
+
*
|
|
521
|
+
* Returns a Promise that resolves when the file is durably written. Callers
|
|
522
|
+
* that treat the spill as fire-and-forget should do:
|
|
523
|
+
* `void disk.save(key, entry)`
|
|
524
|
+
*
|
|
525
|
+
* Implementation notes:
|
|
526
|
+
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
527
|
+
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
528
|
+
* on any external resource.
|
|
529
|
+
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
530
|
+
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
531
|
+
*/
|
|
532
|
+
async save(key: string, entry: DiskCacheEntry): Promise<void> {
|
|
533
|
+
if (this.isForbidden(key)) return;
|
|
534
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
535
|
+
|
|
536
|
+
this.ensureDir();
|
|
537
|
+
if (!this.dirReady) return;
|
|
538
|
+
this.ensureUsageCounted();
|
|
539
|
+
|
|
540
|
+
// Periodic host volume check every 2000 writes
|
|
541
|
+
if (++this._writeCounter % 2000 === 0) {
|
|
542
|
+
this.checkHostVolumeHealth();
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// Fast-shed incoming spills while host volume is low (<10%), pruning is active, or quota is reached
|
|
546
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
547
|
+
this._spillsShedTotal++;
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// High-watermark trigger (80%): fire non-blocking chunked prune down to 60%
|
|
552
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
|
|
553
|
+
void this.triggerChunkedPrune();
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
557
|
+
let final: Buffer;
|
|
558
|
+
try {
|
|
559
|
+
const payload: DiskPayload = {
|
|
560
|
+
version: DISK_TIER_VERSION,
|
|
561
|
+
key,
|
|
562
|
+
entry: {
|
|
563
|
+
...entry,
|
|
564
|
+
data: entry.data instanceof Uint8Array
|
|
565
|
+
? Buffer.from(entry.data)
|
|
566
|
+
: entry.data,
|
|
567
|
+
},
|
|
568
|
+
writtenAt: Date.now(),
|
|
569
|
+
};
|
|
570
|
+
const packed = this.codec.encode(payload);
|
|
571
|
+
if (packed.length > this.opts.entryMaxBytes) return;
|
|
572
|
+
let toEncrypt = packed;
|
|
573
|
+
if (this.opts.compression && this.opts.compression !== 'none' && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
574
|
+
toEncrypt = compressWithHeader(packed, this.opts.compression);
|
|
575
|
+
}
|
|
576
|
+
// V2 format: 16-byte plaintext header (magic + expiresAt) followed by the
|
|
577
|
+
// encrypted-or-raw payload. The plaintext expiresAt allows purgeNextBucket()
|
|
578
|
+
// to check expiry with a 16-byte partial read — no decrypt or unpack needed.
|
|
579
|
+
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
580
|
+
DISK_MAGIC_V2.copy(header, 0);
|
|
581
|
+
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
582
|
+
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
583
|
+
} catch (err) {
|
|
584
|
+
this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
|
|
589
|
+
const hash = this.keyToHash(key);
|
|
590
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
591
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
592
|
+
|
|
593
|
+
// Optimistically reserve quota before queuing so concurrent spills respect the cap
|
|
594
|
+
this.diskUsageBytes += final.length;
|
|
595
|
+
this.fileCount++;
|
|
596
|
+
|
|
597
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
|
|
598
|
+
void this.triggerChunkedPrune();
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
602
|
+
try {
|
|
603
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
604
|
+
await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
|
|
605
|
+
|
|
606
|
+
// Atomic rename with micro-retry loop for Windows NTFS handle release
|
|
607
|
+
try {
|
|
608
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
609
|
+
} catch (renameErr: unknown) {
|
|
610
|
+
const code = (renameErr as { code?: string })?.code;
|
|
611
|
+
if (code === 'EBUSY' || code === 'EPERM') {
|
|
612
|
+
await new Promise<void>(resolve => setTimeout(resolve, 5));
|
|
613
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
614
|
+
} else {
|
|
615
|
+
throw renameErr;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (this._db) {
|
|
620
|
+
const priority = typeof entry.priority === 'number' ? entry.priority : 2;
|
|
621
|
+
const lastAccess = typeof entry.lastAccess === 'number' ? entry.lastAccess : Date.now();
|
|
622
|
+
this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
623
|
+
}
|
|
624
|
+
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
625
|
+
return true;
|
|
626
|
+
} catch (err) {
|
|
627
|
+
try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
|
|
628
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
629
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
630
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
631
|
+
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
632
|
+
throw err;
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
if (result === null) {
|
|
637
|
+
// Fast-dropped by BoundedDiskQueue backpressure / circuit breaker: rollback reservation
|
|
638
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
639
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
644
|
+
load(key: string): DiskCacheEntry | null {
|
|
645
|
+
if (this.isForbidden(key)) return null;
|
|
646
|
+
this.ensureDir();
|
|
647
|
+
if (!this.dirReady) return null;
|
|
648
|
+
|
|
649
|
+
const hash = this.keyToHash(key);
|
|
650
|
+
let filePath: string | null;
|
|
651
|
+
|
|
652
|
+
if (this._db) {
|
|
653
|
+
// SQLite fast path: single B-tree lookup replaces readdirSync + filename scan.
|
|
654
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
|
|
655
|
+
if (!row) return null;
|
|
656
|
+
if (row.expires_at <= Date.now()) {
|
|
657
|
+
this._stmtDelete!.run(hash);
|
|
658
|
+
try {
|
|
659
|
+
const sz = fs.statSync(row.file_path).size;
|
|
660
|
+
fs.unlinkSync(row.file_path);
|
|
661
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
662
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
663
|
+
} catch { /* ok */ }
|
|
664
|
+
return null;
|
|
665
|
+
}
|
|
666
|
+
filePath = row.file_path;
|
|
667
|
+
} else {
|
|
668
|
+
filePath = this.findFilePath(hash);
|
|
669
|
+
if (!filePath) return null;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
try {
|
|
673
|
+
// V3 filename fast-path (file-only mode): expiresAt encoded in name avoids
|
|
674
|
+
// opening the file when the entry is already stale.
|
|
675
|
+
if (!this._db) {
|
|
676
|
+
const filename = path.basename(filePath);
|
|
677
|
+
if (filename.length === 77 && filename[64] === '_') {
|
|
678
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
679
|
+
if (expiresAt <= Date.now()) {
|
|
680
|
+
try {
|
|
681
|
+
const sz = fs.statSync(filePath).size;
|
|
682
|
+
fs.unlinkSync(filePath);
|
|
683
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
684
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
685
|
+
} catch { /* ok */ }
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const stat = fs.statSync(filePath);
|
|
692
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
693
|
+
fs.unlinkSync(filePath);
|
|
694
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
695
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const raw = fs.readFileSync(filePath);
|
|
700
|
+
// Delete immediately — entry will be promoted back to L1
|
|
701
|
+
try {
|
|
702
|
+
fs.unlinkSync(filePath);
|
|
703
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
704
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
705
|
+
} catch { /* ok */ }
|
|
706
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
707
|
+
|
|
708
|
+
let decrypted: Buffer;
|
|
709
|
+
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
710
|
+
// V2/V3: quick expiry guard from plaintext header before paying decrypt cost
|
|
711
|
+
const expiresAt = Number(raw.readBigUInt64LE(8));
|
|
712
|
+
if (expiresAt <= Date.now()) return null;
|
|
713
|
+
try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
|
|
714
|
+
} else {
|
|
715
|
+
// V1 / legacy unencrypted — backward compat
|
|
716
|
+
try { decrypted = this.decrypt(raw); } catch { return null; }
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
|
|
720
|
+
const payload = this.codec.decode(uncompressed) as DiskPayload;
|
|
721
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
722
|
+
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
723
|
+
|
|
724
|
+
const entry = payload.entry;
|
|
725
|
+
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
726
|
+
|
|
727
|
+
this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
728
|
+
return entry;
|
|
729
|
+
} catch (err) {
|
|
730
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
731
|
+
this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Explicitly delete a key from disk (cache invalidation). */
|
|
737
|
+
delete(key: string): void {
|
|
738
|
+
const hash = this.keyToHash(key);
|
|
739
|
+
let filePath: string | null;
|
|
740
|
+
if (this._db) {
|
|
741
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
|
|
742
|
+
filePath = row?.file_path ?? null;
|
|
743
|
+
this._stmtDelete!.run(hash);
|
|
744
|
+
} else {
|
|
745
|
+
filePath = this.findFilePath(hash);
|
|
746
|
+
}
|
|
747
|
+
if (!filePath) return;
|
|
748
|
+
try {
|
|
749
|
+
const stat = fs.statSync(filePath);
|
|
750
|
+
fs.unlinkSync(filePath);
|
|
751
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
752
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
753
|
+
} catch { /* ok */ }
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Purge all expired entries. Returns number deleted. */
|
|
757
|
+
purgeExpired(): number {
|
|
758
|
+
this.ensureDir();
|
|
759
|
+
if (!this.dirReady) return 0;
|
|
760
|
+
|
|
761
|
+
if (this._db) {
|
|
762
|
+
// SQLite fast path: one indexed query finds all expired rows.
|
|
763
|
+
const now = Date.now();
|
|
764
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
765
|
+
for (const row of expired) {
|
|
766
|
+
try {
|
|
767
|
+
fs.unlinkSync(row.file_path);
|
|
768
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
769
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
770
|
+
} catch { /* already gone */ }
|
|
771
|
+
}
|
|
772
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
773
|
+
return expired.length;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const now = Date.now();
|
|
777
|
+
let purged = 0;
|
|
778
|
+
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
779
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
780
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
781
|
+
const filename = path.basename(filePath);
|
|
782
|
+
|
|
783
|
+
// Clean up orphaned .tmp files older than 5 minutes
|
|
784
|
+
if (filename.endsWith('.tmp')) {
|
|
785
|
+
try {
|
|
786
|
+
const stat = fs.statSync(filePath);
|
|
787
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
788
|
+
fs.unlinkSync(filePath);
|
|
789
|
+
purged++;
|
|
790
|
+
}
|
|
791
|
+
} catch { /* already gone */ }
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
796
|
+
if (filename.length === 77 && filename[64] === '_') {
|
|
797
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
798
|
+
if (expiresAt <= now) {
|
|
799
|
+
try {
|
|
800
|
+
const sz = fs.statSync(filePath).size;
|
|
801
|
+
fs.unlinkSync(filePath);
|
|
802
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
803
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
804
|
+
purged++;
|
|
805
|
+
} catch { /* already gone */ }
|
|
806
|
+
}
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// ── V2 header fast path: read only the 16-byte plaintext header ────────
|
|
811
|
+
// NOTE: Modern TriCache disk files never read full payload data during eviction.
|
|
812
|
+
// The 16-byte plaintext header (magic + expiresAt) allows checking TTL and unlinking
|
|
813
|
+
// expired files with near-zero I/O overhead. Full readFileSync below is exclusively
|
|
814
|
+
// for backward compatibility with ancient V1 files lacking the magic header.
|
|
815
|
+
let fd = -1;
|
|
816
|
+
try {
|
|
817
|
+
fd = fs.openSync(filePath, 'r');
|
|
818
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
819
|
+
fs.closeSync(fd); fd = -1;
|
|
820
|
+
|
|
821
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
822
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
823
|
+
if (expiresAt <= now) {
|
|
824
|
+
try {
|
|
825
|
+
const sz = fs.statSync(filePath).size;
|
|
826
|
+
fs.unlinkSync(filePath);
|
|
827
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
828
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
829
|
+
purged++;
|
|
830
|
+
} catch { /* already gone */ }
|
|
831
|
+
}
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// ── Legacy fallback path: V1 encrypted or pre-magic unencrypted ────────
|
|
836
|
+
const stat = fs.statSync(filePath);
|
|
837
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
838
|
+
fs.unlinkSync(filePath);
|
|
839
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
840
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
841
|
+
purged++;
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
const raw = fs.readFileSync(filePath);
|
|
845
|
+
let dec: Buffer;
|
|
846
|
+
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
847
|
+
const payload = this.codec.decode(dec) as DiskPayload;
|
|
848
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
849
|
+
fs.unlinkSync(filePath);
|
|
850
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
851
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
852
|
+
purged++;
|
|
853
|
+
}
|
|
854
|
+
} catch { /* skip locked/gone */ } finally {
|
|
855
|
+
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return purged;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
863
|
+
*
|
|
864
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
865
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
866
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
867
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
868
|
+
* incremented so tests that inspect the counter continue to work.
|
|
869
|
+
*
|
|
870
|
+
* File-only fallback:
|
|
871
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
872
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
873
|
+
*
|
|
874
|
+
* Returns the number of entries deleted in this tick.
|
|
875
|
+
*/
|
|
876
|
+
purgeNextBucket(): number {
|
|
877
|
+
this.ensureDir();
|
|
878
|
+
if (!this.dirReady) return 0;
|
|
879
|
+
// Always advance the pointer — preserves observable state for tests and
|
|
880
|
+
// metrics regardless of which code path runs below.
|
|
881
|
+
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
882
|
+
|
|
883
|
+
if (this._db) {
|
|
884
|
+
const now = Date.now();
|
|
885
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
886
|
+
for (const row of expired) {
|
|
887
|
+
try {
|
|
888
|
+
fs.unlinkSync(row.file_path);
|
|
889
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
890
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
891
|
+
} catch { /* already gone */ }
|
|
892
|
+
}
|
|
893
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
894
|
+
|
|
895
|
+
// Belt-and-suspenders: scan one filesystem bucket for orphan files — files
|
|
896
|
+
// written to disk before a crash between writeFile() and the SQLite INSERT.
|
|
897
|
+
// V3 fast path: no file I/O for live entries (expiry is in the filename).
|
|
898
|
+
// Expired orphans are unlinked here; they are invisible to the SQLite query.
|
|
899
|
+
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
900
|
+
const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, '0'));
|
|
901
|
+
let orphanFiles: string[];
|
|
902
|
+
try { orphanFiles = fs.readdirSync(orphanBucketP); } catch { return expired.length; }
|
|
903
|
+
for (const file of orphanFiles) {
|
|
904
|
+
if (file.endsWith('.tmp')) {
|
|
905
|
+
const fp = path.join(orphanBucketP, file);
|
|
906
|
+
try {
|
|
907
|
+
const stat = fs.statSync(fp);
|
|
908
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
909
|
+
fs.unlinkSync(fp);
|
|
910
|
+
}
|
|
911
|
+
} catch { /* already gone */ }
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (file.length === 77 && file[64] === '_') {
|
|
916
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
917
|
+
if (expiresAt <= now) {
|
|
918
|
+
const fp = path.join(orphanBucketP, file);
|
|
919
|
+
try {
|
|
920
|
+
const sz = fs.statSync(fp).size;
|
|
921
|
+
fs.unlinkSync(fp);
|
|
922
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
923
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
924
|
+
} catch { /* already gone */ }
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
return expired.length;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// ── File-only fallback: one-bucket scan ───────────────────────────────
|
|
932
|
+
const bucket = (this._nextJanitorBucket - 1 + 256) % 256; // use the bucket we just advanced past
|
|
933
|
+
const bucketHex = bucket.toString(16).padStart(2, '0');
|
|
934
|
+
const bucketPath = path.join(this.opts.dir, bucketHex);
|
|
935
|
+
let files: string[];
|
|
936
|
+
try { files = fs.readdirSync(bucketPath); } catch { return 0; }
|
|
937
|
+
const now = Date.now();
|
|
938
|
+
let purged = 0;
|
|
939
|
+
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
940
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
941
|
+
for (const file of files) {
|
|
942
|
+
// Clean up orphaned .tmp files older than 5 minutes
|
|
943
|
+
if (file.endsWith('.tmp')) {
|
|
944
|
+
const fp = path.join(bucketPath, file);
|
|
945
|
+
try {
|
|
946
|
+
const stat = fs.statSync(fp);
|
|
947
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
948
|
+
fs.unlinkSync(fp);
|
|
949
|
+
purged++;
|
|
950
|
+
}
|
|
951
|
+
} catch { /* already gone */ }
|
|
952
|
+
continue;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
956
|
+
// Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
|
|
957
|
+
if (file.length === 77 && file[64] === '_') {
|
|
958
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
959
|
+
if (expiresAt <= now) {
|
|
960
|
+
const filePath = path.join(bucketPath, file);
|
|
961
|
+
try {
|
|
962
|
+
const sz = fs.statSync(filePath).size;
|
|
963
|
+
fs.unlinkSync(filePath);
|
|
964
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
965
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
966
|
+
purged++;
|
|
967
|
+
} catch { /* already gone */ }
|
|
968
|
+
}
|
|
969
|
+
continue; // live or just deleted — no further work
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// ── V2 header path: open+read(16)+close ───────────────────────────────
|
|
973
|
+
const filePath = path.join(bucketPath, file);
|
|
974
|
+
let fd = -1;
|
|
975
|
+
try {
|
|
976
|
+
fd = fs.openSync(filePath, 'r');
|
|
977
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
978
|
+
fs.closeSync(fd); fd = -1;
|
|
979
|
+
|
|
980
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
981
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
982
|
+
if (expiresAt <= now) {
|
|
983
|
+
try {
|
|
984
|
+
const sz = fs.statSync(filePath).size;
|
|
985
|
+
fs.unlinkSync(filePath);
|
|
986
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
987
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
988
|
+
purged++;
|
|
989
|
+
} catch { /* already gone */ }
|
|
990
|
+
}
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
// ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
|
|
995
|
+
const stat = fs.statSync(filePath);
|
|
996
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
997
|
+
fs.unlinkSync(filePath);
|
|
998
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
999
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1000
|
+
purged++;
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
const raw = fs.readFileSync(filePath);
|
|
1004
|
+
let dec: Buffer;
|
|
1005
|
+
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
1006
|
+
const payload = this.codec.decode(dec) as DiskPayload;
|
|
1007
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1008
|
+
fs.unlinkSync(filePath);
|
|
1009
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1010
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1011
|
+
purged++;
|
|
1012
|
+
}
|
|
1013
|
+
} catch { /* skip locked/gone */ } finally {
|
|
1014
|
+
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
return purged;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1021
|
+
clear(): number {
|
|
1022
|
+
this.ensureDir();
|
|
1023
|
+
if (!this.dirReady) return 0;
|
|
1024
|
+
let cleared = 0;
|
|
1025
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
1026
|
+
try {
|
|
1027
|
+
const stat = fs.statSync(filePath);
|
|
1028
|
+
fs.unlinkSync(filePath);
|
|
1029
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1030
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1031
|
+
cleared++;
|
|
1032
|
+
} catch { /* skip locked/gone */ }
|
|
1033
|
+
}
|
|
1034
|
+
if (this._db) {
|
|
1035
|
+
this._db.exec('DELETE FROM meta');
|
|
1036
|
+
this.diskUsageBytes = 0;
|
|
1037
|
+
this.fileCount = 0;
|
|
1038
|
+
}
|
|
1039
|
+
return cleared;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* Proactively checks host volume free space via statfsSync.
|
|
1044
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
1045
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
1046
|
+
*/
|
|
1047
|
+
public checkHostVolumeHealth(): boolean {
|
|
1048
|
+
try {
|
|
1049
|
+
if (typeof fs.statfsSync === 'function') {
|
|
1050
|
+
const stats = fs.statfsSync(this.opts.dir);
|
|
1051
|
+
const total = Number(stats.blocks);
|
|
1052
|
+
const avail = Number(stats.bavail);
|
|
1053
|
+
if (total > 0) {
|
|
1054
|
+
const freeRatio = avail / total;
|
|
1055
|
+
if (freeRatio < 0.10) {
|
|
1056
|
+
if (!this._hostVolumeLowSpace) {
|
|
1057
|
+
this._hostVolumeLowSpace = true;
|
|
1058
|
+
this._hostVolumeLowSpacePauses++;
|
|
1059
|
+
this.opts.logger.warn(
|
|
1060
|
+
'DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.',
|
|
1061
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) },
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
return false;
|
|
1065
|
+
} else if (this._hostVolumeLowSpace) {
|
|
1066
|
+
this._hostVolumeLowSpace = false;
|
|
1067
|
+
this.opts.logger.info(
|
|
1068
|
+
'DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.',
|
|
1069
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) },
|
|
1070
|
+
);
|
|
1071
|
+
return true;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
} catch {
|
|
1076
|
+
// statfs may fail if directory does not yet exist or is unmounted
|
|
1077
|
+
}
|
|
1078
|
+
return true;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/**
|
|
1082
|
+
* Non-blocking chunked pruning:
|
|
1083
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
1084
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
1085
|
+
*/
|
|
1086
|
+
public async triggerChunkedPrune(): Promise<number> {
|
|
1087
|
+
if (this._isPruning) return 0;
|
|
1088
|
+
this._isPruning = true;
|
|
1089
|
+
this._pruneRounds++;
|
|
1090
|
+
let prunedInThisRound = 0;
|
|
1091
|
+
|
|
1092
|
+
try {
|
|
1093
|
+
this.ensureUsageCounted();
|
|
1094
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.60);
|
|
1095
|
+
|
|
1096
|
+
if (this._db && this._stmtPruneChunk) {
|
|
1097
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
1098
|
+
const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
1099
|
+
if (!rows || rows.length === 0) break;
|
|
1100
|
+
|
|
1101
|
+
for (const row of rows) {
|
|
1102
|
+
try {
|
|
1103
|
+
fs.unlinkSync(row.file_path);
|
|
1104
|
+
} catch { /* already gone */ }
|
|
1105
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1106
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1107
|
+
this._entriesPruned++;
|
|
1108
|
+
prunedInThisRound++;
|
|
1109
|
+
try { this._stmtDelete!.run(row.key_hash); } catch { /* ok */ }
|
|
1110
|
+
|
|
1111
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
1115
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
} else {
|
|
1119
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
1120
|
+
const files = this.walkCacheFiles();
|
|
1121
|
+
if (files.length === 0) break;
|
|
1122
|
+
const chunk = files.slice(0, 500);
|
|
1123
|
+
|
|
1124
|
+
for (const filePath of chunk) {
|
|
1125
|
+
try {
|
|
1126
|
+
const stat = fs.statSync(filePath);
|
|
1127
|
+
fs.unlinkSync(filePath);
|
|
1128
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1129
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1130
|
+
this._entriesPruned++;
|
|
1131
|
+
prunedInThisRound++;
|
|
1132
|
+
} catch { /* already gone */ }
|
|
1133
|
+
|
|
1134
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
1138
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
} finally {
|
|
1143
|
+
this._isPruning = false;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
return prunedInThisRound;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
get isPruning(): boolean {
|
|
1150
|
+
return this._isPruning;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
get hostVolumeLowSpace(): boolean {
|
|
1154
|
+
return this._hostVolumeLowSpace;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
get spillsShedTotal(): number {
|
|
1158
|
+
return this._spillsShedTotal;
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
getPruningStats(): {
|
|
1162
|
+
active: boolean;
|
|
1163
|
+
pruneRounds: number;
|
|
1164
|
+
entriesPruned: number;
|
|
1165
|
+
spillsShedTotal: number;
|
|
1166
|
+
hostVolumeLowSpacePauses: number;
|
|
1167
|
+
} {
|
|
1168
|
+
return {
|
|
1169
|
+
active: this._isPruning,
|
|
1170
|
+
pruneRounds: this._pruneRounds,
|
|
1171
|
+
entriesPruned: this._entriesPruned,
|
|
1172
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
1173
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses,
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
get stats(): {
|
|
1178
|
+
files: number;
|
|
1179
|
+
sizeKB: number;
|
|
1180
|
+
maxKB: number;
|
|
1181
|
+
backpressure?: DiskBackpressureStats;
|
|
1182
|
+
pruning?: {
|
|
1183
|
+
active: boolean;
|
|
1184
|
+
pruneRounds: number;
|
|
1185
|
+
entriesPruned: number;
|
|
1186
|
+
spillsShedTotal: number;
|
|
1187
|
+
hostVolumeLowSpacePauses: number;
|
|
1188
|
+
};
|
|
1189
|
+
} {
|
|
1190
|
+
if (this._db) {
|
|
1191
|
+
// Query the index for authoritative counts — O(1) SQLite aggregate.
|
|
1192
|
+
const row = this._stmtStats!.get() as { cnt: number; bytes: number };
|
|
1193
|
+
this.fileCount = row.cnt;
|
|
1194
|
+
this.diskUsageBytes = row.bytes;
|
|
1195
|
+
}
|
|
1196
|
+
return {
|
|
1197
|
+
files: this.fileCount,
|
|
1198
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
1199
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
1200
|
+
backpressure: this.diskQueue.getStats(),
|
|
1201
|
+
pruning: this.getPruningStats(),
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
1206
|
+
get backpressure(): BoundedDiskQueue {
|
|
1207
|
+
return this.diskQueue;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
1211
|
+
get indexMode(): 'sqlite' | 'file-only' {
|
|
1212
|
+
return this._db ? 'sqlite' : 'file-only';
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1216
|
+
close(): void {
|
|
1217
|
+
if (this._db) {
|
|
1218
|
+
try { this._db.close(); } catch { /* ok */ }
|
|
1219
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
1220
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|