tricache 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -28
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
- package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
- package/dist/cli.cjs +1367 -625
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1370 -624
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +227 -123
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +201 -117
- package/dist/hono/index.cjs +1418 -644
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1514 -679
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +1671 -790
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +39 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1454 -649
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1512 -718
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +172 -99
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +802 -502
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +145 -97
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +131 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +63 -26
- package/src/types.ts +25 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
package/src/disk-tier.ts
CHANGED
|
@@ -39,7 +39,7 @@ export type { DiskBackpressureStats };
|
|
|
39
39
|
*/
|
|
40
40
|
export class BoundedDiskQueue {
|
|
41
41
|
private active = 0;
|
|
42
|
-
private queue: Array<() => void> = [];
|
|
42
|
+
private queue: Array<(admitted: boolean) => void> = [];
|
|
43
43
|
private spillsDropped = 0;
|
|
44
44
|
private consecutiveFailures = 0;
|
|
45
45
|
private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
|
|
@@ -51,7 +51,27 @@ export class BoundedDiskQueue {
|
|
|
51
51
|
private readonly writeTimeoutMs: number = 500,
|
|
52
52
|
private readonly failureThreshold: number = 5,
|
|
53
53
|
private readonly cooldownMs: number = 5000,
|
|
54
|
-
) {
|
|
54
|
+
) {
|
|
55
|
+
if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1 || !Number.isInteger(maxPending) || maxPending < 0 ||
|
|
56
|
+
!Number.isFinite(writeTimeoutMs) || writeTimeoutMs <= 0 || !Number.isInteger(failureThreshold) || failureThreshold < 1 ||
|
|
57
|
+
!Number.isFinite(cooldownMs) || cooldownMs < 0) {
|
|
58
|
+
throw new Error('Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get isSaturated(): boolean {
|
|
63
|
+
return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private releaseSlot(): void {
|
|
67
|
+
if (this.circuitState === 'open') {
|
|
68
|
+
for (const next of this.queue.splice(0)) next(false);
|
|
69
|
+
}
|
|
70
|
+
const next = this.queue.shift();
|
|
71
|
+
// Transfer the reservation so newly arriving calls cannot steal a queued slot.
|
|
72
|
+
if (next) next(true);
|
|
73
|
+
else this.active--;
|
|
74
|
+
}
|
|
55
75
|
|
|
56
76
|
public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
|
|
57
77
|
const now = performance.now();
|
|
@@ -73,22 +93,30 @@ export class BoundedDiskQueue {
|
|
|
73
93
|
return null;
|
|
74
94
|
}
|
|
75
95
|
|
|
76
|
-
if (this.
|
|
96
|
+
if (this.isSaturated) {
|
|
77
97
|
this.spillsDropped++;
|
|
78
98
|
return null; // Bounded memory queue: drop spill to preserve main thread
|
|
79
99
|
}
|
|
80
100
|
|
|
81
101
|
// Wait for slot in concurrency pool
|
|
82
102
|
if (this.active >= this.maxConcurrent) {
|
|
83
|
-
await new Promise<
|
|
103
|
+
const admitted = await new Promise<boolean>((resolve) => this.queue.push(resolve));
|
|
104
|
+
if (!admitted) {
|
|
105
|
+
this.spillsDropped++;
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
this.active++;
|
|
84
110
|
}
|
|
85
|
-
|
|
86
|
-
this.active++;
|
|
87
111
|
let timeoutId: NodeJS.Timeout | null = null;
|
|
112
|
+
const work = Promise.resolve().then(task);
|
|
113
|
+
// A caller timeout does not cancel filesystem I/O. Release its physical slot
|
|
114
|
+
// only when the underlying operation settles, including on late failure.
|
|
115
|
+
void work.then(() => this.releaseSlot(), () => this.releaseSlot());
|
|
88
116
|
|
|
89
117
|
try {
|
|
90
118
|
const result = await Promise.race([
|
|
91
|
-
|
|
119
|
+
work,
|
|
92
120
|
new Promise<never>((_, reject) => {
|
|
93
121
|
timeoutId = setTimeout(
|
|
94
122
|
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
@@ -110,14 +138,12 @@ export class BoundedDiskQueue {
|
|
|
110
138
|
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === 'half-open') {
|
|
111
139
|
this.circuitState = 'open';
|
|
112
140
|
this.lastStateChangeMonotonic = performance.now();
|
|
141
|
+
for (const next of this.queue.splice(0)) next(false);
|
|
113
142
|
}
|
|
114
143
|
this.spillsDropped++;
|
|
115
144
|
return null;
|
|
116
145
|
} finally {
|
|
117
146
|
if (timeoutId) clearTimeout(timeoutId);
|
|
118
|
-
this.active--;
|
|
119
|
-
const next = this.queue.shift();
|
|
120
|
-
if (next) next();
|
|
121
147
|
}
|
|
122
148
|
}
|
|
123
149
|
|
|
@@ -267,6 +293,13 @@ export class DiskTier {
|
|
|
267
293
|
private diskUsageBytes = 0;
|
|
268
294
|
private usageCounted = false;
|
|
269
295
|
private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
|
|
296
|
+
private reservedBytes = 0;
|
|
297
|
+
private reservedFiles = 0;
|
|
298
|
+
private saveSequence = 0;
|
|
299
|
+
private epoch = 0;
|
|
300
|
+
private readonly pendingSaves = new Map<string, { token: symbol; setAt: number }>();
|
|
301
|
+
private closed = false;
|
|
302
|
+
private readonly invalidatedKeys = new Set<string>();
|
|
270
303
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
271
304
|
private _nextJanitorBucket = 0;
|
|
272
305
|
|
|
@@ -305,6 +338,7 @@ export class DiskTier {
|
|
|
305
338
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
306
339
|
|
|
307
340
|
private ensureDir(): void {
|
|
341
|
+
if (this.closed) return;
|
|
308
342
|
if (this.dirReady) return;
|
|
309
343
|
try {
|
|
310
344
|
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
@@ -427,8 +461,25 @@ export class DiskTier {
|
|
|
427
461
|
*
|
|
428
462
|
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
429
463
|
*/
|
|
430
|
-
private hashToWritePath(hash: string, expiresAt: number): string {
|
|
431
|
-
|
|
464
|
+
private hashToWritePath(hash: string, expiresAt: number, setAt?: number): string {
|
|
465
|
+
const expiry = Math.floor(expiresAt).toString(16).padStart(12, '0');
|
|
466
|
+
if (setAt === undefined) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
|
|
467
|
+
const written = Math.floor(setAt).toString(16).padStart(12, '0');
|
|
468
|
+
const sequence = (++this.saveSequence).toString(16).padStart(12, '0');
|
|
469
|
+
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString('hex')}`);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private findFilePaths(hash: string): string[] {
|
|
473
|
+
const bucket = path.join(this.opts.dir, hash.slice(0, 2));
|
|
474
|
+
try {
|
|
475
|
+
return fs.readdirSync(bucket).filter(file => !file.endsWith('.tmp') && (file === hash || file.startsWith(hash + '_')))
|
|
476
|
+
.map(file => path.join(bucket, file));
|
|
477
|
+
} catch { return []; }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
private fileWrittenAt(file: string): number {
|
|
481
|
+
const parts = path.basename(file).split('_');
|
|
482
|
+
return parts.length >= 4 ? parseInt(parts[2], 16) : fs.statSync(file).mtimeMs;
|
|
432
483
|
}
|
|
433
484
|
|
|
434
485
|
/**
|
|
@@ -438,20 +489,30 @@ export class DiskTier {
|
|
|
438
489
|
* Returns null when the bucket dir does not exist or the key is absent.
|
|
439
490
|
*/
|
|
440
491
|
private findFilePath(hash: string): string | null {
|
|
441
|
-
|
|
442
|
-
let
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
492
|
+
let match: string | null = null;
|
|
493
|
+
let newest = -Infinity;
|
|
494
|
+
let sequence = -1;
|
|
495
|
+
for (const file of this.findFilePaths(hash)) {
|
|
496
|
+
try {
|
|
497
|
+
const written = this.fileWrittenAt(file);
|
|
498
|
+
const order = parseInt(path.basename(file).split('_')[3] ?? '0', 16);
|
|
499
|
+
if (written > newest || (written === newest && order > sequence)) {
|
|
500
|
+
match = file;
|
|
501
|
+
newest = written;
|
|
502
|
+
sequence = order;
|
|
503
|
+
}
|
|
504
|
+
} catch { /* raced with deletion */ }
|
|
452
505
|
}
|
|
453
|
-
|
|
454
|
-
|
|
506
|
+
return match;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
private removeFile(filePath: string): void {
|
|
510
|
+
try {
|
|
511
|
+
const size = fs.statSync(filePath).size;
|
|
512
|
+
fs.unlinkSync(filePath);
|
|
513
|
+
this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
|
|
514
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
515
|
+
} catch { /* already gone or locked */ }
|
|
455
516
|
}
|
|
456
517
|
|
|
457
518
|
/**
|
|
@@ -530,6 +591,7 @@ export class DiskTier {
|
|
|
530
591
|
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
531
592
|
*/
|
|
532
593
|
async save(key: string, entry: DiskCacheEntry): Promise<void> {
|
|
594
|
+
if (this.closed || this.diskQueue.isSaturated) return;
|
|
533
595
|
if (this.isForbidden(key)) return;
|
|
534
596
|
if (entry.expiresAt <= Date.now()) return;
|
|
535
597
|
|
|
@@ -543,7 +605,7 @@ export class DiskTier {
|
|
|
543
605
|
}
|
|
544
606
|
|
|
545
607
|
// 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) {
|
|
608
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
|
|
547
609
|
this._spillsShedTotal++;
|
|
548
610
|
return;
|
|
549
611
|
}
|
|
@@ -556,11 +618,12 @@ export class DiskTier {
|
|
|
556
618
|
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
557
619
|
let final: Buffer;
|
|
558
620
|
try {
|
|
621
|
+
const { value: _value, ...storedEntry } = entry as DiskCacheEntry & { value?: unknown };
|
|
559
622
|
const payload: DiskPayload = {
|
|
560
623
|
version: DISK_TIER_VERSION,
|
|
561
624
|
key,
|
|
562
625
|
entry: {
|
|
563
|
-
...
|
|
626
|
+
...storedEntry,
|
|
564
627
|
data: entry.data instanceof Uint8Array
|
|
565
628
|
? Buffer.from(entry.data)
|
|
566
629
|
: entry.data,
|
|
@@ -578,8 +641,9 @@ export class DiskTier {
|
|
|
578
641
|
// to check expiry with a 16-byte partial read — no decrypt or unpack needed.
|
|
579
642
|
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
580
643
|
DISK_MAGIC_V2.copy(header, 0);
|
|
581
|
-
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
644
|
+
header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
|
|
582
645
|
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
646
|
+
if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
|
|
583
647
|
} catch (err) {
|
|
584
648
|
this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
585
649
|
return;
|
|
@@ -587,21 +651,42 @@ export class DiskTier {
|
|
|
587
651
|
|
|
588
652
|
// ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
|
|
589
653
|
const hash = this.keyToHash(key);
|
|
590
|
-
const
|
|
654
|
+
const setAt = entry.setAt ?? Date.now();
|
|
655
|
+
if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
|
|
656
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
|
|
591
657
|
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
658
|
+
const token = Symbol(key);
|
|
659
|
+
const epoch = this.epoch;
|
|
660
|
+
this.pendingSaves.set(key, { token, setAt });
|
|
661
|
+
const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
|
|
662
|
+
let started = false;
|
|
663
|
+
let released = false;
|
|
664
|
+
let accounted = false;
|
|
665
|
+
const releaseReservation = () => {
|
|
666
|
+
if (released) return;
|
|
667
|
+
released = true;
|
|
668
|
+
this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
|
|
669
|
+
this.reservedFiles = Math.max(0, this.reservedFiles - 1);
|
|
670
|
+
if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
|
|
671
|
+
};
|
|
592
672
|
|
|
593
673
|
// Optimistically reserve quota before queuing so concurrent spills respect the cap
|
|
594
|
-
this.
|
|
595
|
-
this.
|
|
674
|
+
this.reservedBytes += final.length;
|
|
675
|
+
this.reservedFiles++;
|
|
596
676
|
|
|
597
677
|
if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
|
|
598
678
|
void this.triggerChunkedPrune();
|
|
599
679
|
}
|
|
600
680
|
|
|
601
681
|
const result = await this.diskQueue.schedule(async () => {
|
|
682
|
+
started = true;
|
|
602
683
|
try {
|
|
684
|
+
if (!current()) return false;
|
|
685
|
+
const previous = this.findFilePath(hash);
|
|
686
|
+
if (previous && this.fileWrittenAt(previous) > setAt) return false;
|
|
603
687
|
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
604
688
|
await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
|
|
689
|
+
if (!current()) return false;
|
|
605
690
|
|
|
606
691
|
// Atomic rename with micro-retry loop for Windows NTFS handle release
|
|
607
692
|
try {
|
|
@@ -616,6 +701,20 @@ export class DiskTier {
|
|
|
616
701
|
}
|
|
617
702
|
}
|
|
618
703
|
|
|
704
|
+
if (!current()) {
|
|
705
|
+
try { await fs.promises.unlink(filePath); } catch { /* already removed */ }
|
|
706
|
+
return false;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// Remove all superseded versions, not just the one with the largest TTL.
|
|
710
|
+
for (const previousPath of this.findFilePaths(hash)) {
|
|
711
|
+
if (previousPath !== filePath) this.removeFile(previousPath);
|
|
712
|
+
}
|
|
713
|
+
this.diskUsageBytes += final.length;
|
|
714
|
+
this.fileCount++;
|
|
715
|
+
accounted = true;
|
|
716
|
+
this.invalidatedKeys.delete(key);
|
|
717
|
+
|
|
619
718
|
if (this._db) {
|
|
620
719
|
const priority = typeof entry.priority === 'number' ? entry.priority : 2;
|
|
621
720
|
const lastAccess = typeof entry.lastAccess === 'number' ? entry.lastAccess : Date.now();
|
|
@@ -625,23 +724,25 @@ export class DiskTier {
|
|
|
625
724
|
return true;
|
|
626
725
|
} catch (err) {
|
|
627
726
|
try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
|
|
628
|
-
|
|
629
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
630
|
-
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
727
|
+
if (accounted) this.removeFile(filePath);
|
|
631
728
|
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
632
729
|
throw err;
|
|
730
|
+
} finally {
|
|
731
|
+
try { await fs.promises.unlink(tmpPath); } catch { /* renamed, removed, or never created */ }
|
|
732
|
+
releaseReservation();
|
|
733
|
+
if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
|
|
633
734
|
}
|
|
634
735
|
});
|
|
635
736
|
|
|
636
|
-
if (result === null) {
|
|
737
|
+
if (result === null && !started) {
|
|
637
738
|
// Fast-dropped by BoundedDiskQueue backpressure / circuit breaker: rollback reservation
|
|
638
|
-
|
|
639
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
739
|
+
releaseReservation();
|
|
640
740
|
}
|
|
641
741
|
}
|
|
642
742
|
|
|
643
743
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
644
744
|
load(key: string): DiskCacheEntry | null {
|
|
745
|
+
if (this.invalidatedKeys.has(key) || this.closed) return null;
|
|
645
746
|
if (this.isForbidden(key)) return null;
|
|
646
747
|
this.ensureDir();
|
|
647
748
|
if (!this.dirReady) return null;
|
|
@@ -674,8 +775,8 @@ export class DiskTier {
|
|
|
674
775
|
// opening the file when the entry is already stale.
|
|
675
776
|
if (!this._db) {
|
|
676
777
|
const filename = path.basename(filePath);
|
|
677
|
-
if (filename.length
|
|
678
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
778
|
+
if (filename.length >= 77 && filename[64] === '_') {
|
|
779
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
679
780
|
if (expiresAt <= Date.now()) {
|
|
680
781
|
try {
|
|
681
782
|
const sz = fs.statSync(filePath).size;
|
|
@@ -698,11 +799,7 @@ export class DiskTier {
|
|
|
698
799
|
|
|
699
800
|
const raw = fs.readFileSync(filePath);
|
|
700
801
|
// Delete immediately — entry will be promoted back to L1
|
|
701
|
-
|
|
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 */ }
|
|
802
|
+
for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
|
|
706
803
|
if (this._db) this._stmtDelete!.run(hash);
|
|
707
804
|
|
|
708
805
|
let decrypted: Buffer;
|
|
@@ -733,24 +830,25 @@ export class DiskTier {
|
|
|
733
830
|
}
|
|
734
831
|
}
|
|
735
832
|
|
|
736
|
-
/**
|
|
737
|
-
|
|
833
|
+
/** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
|
|
834
|
+
invalidate(key: string): void {
|
|
835
|
+
this.pendingSaves.delete(key);
|
|
836
|
+
this.invalidatedKeys.add(key);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** Delete all versions; deferred cleanup must not cancel a newer save. */
|
|
840
|
+
delete(key: string, invalidatedOnly = false): void {
|
|
841
|
+
if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
|
|
842
|
+
if (!invalidatedOnly) this.pendingSaves.delete(key);
|
|
738
843
|
const hash = this.keyToHash(key);
|
|
739
|
-
|
|
844
|
+
const files = new Set(this.findFilePaths(hash));
|
|
740
845
|
if (this._db) {
|
|
741
846
|
const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
|
|
742
|
-
|
|
847
|
+
if (row?.file_path) files.add(row.file_path);
|
|
743
848
|
this._stmtDelete!.run(hash);
|
|
744
|
-
} else {
|
|
745
|
-
filePath = this.findFilePath(hash);
|
|
746
849
|
}
|
|
747
|
-
|
|
748
|
-
|
|
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 */ }
|
|
850
|
+
for (const file of files) this.removeFile(file);
|
|
851
|
+
this.invalidatedKeys.delete(key);
|
|
754
852
|
}
|
|
755
853
|
|
|
756
854
|
/** Purge all expired entries. Returns number deleted. */
|
|
@@ -793,8 +891,8 @@ export class DiskTier {
|
|
|
793
891
|
}
|
|
794
892
|
|
|
795
893
|
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
796
|
-
if (filename.length
|
|
797
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
894
|
+
if (filename.length >= 77 && filename[64] === '_') {
|
|
895
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
798
896
|
if (expiresAt <= now) {
|
|
799
897
|
try {
|
|
800
898
|
const sz = fs.statSync(filePath).size;
|
|
@@ -912,8 +1010,8 @@ export class DiskTier {
|
|
|
912
1010
|
continue;
|
|
913
1011
|
}
|
|
914
1012
|
|
|
915
|
-
if (file.length
|
|
916
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
1013
|
+
if (file.length >= 77 && file[64] === '_') {
|
|
1014
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
917
1015
|
if (expiresAt <= now) {
|
|
918
1016
|
const fp = path.join(orphanBucketP, file);
|
|
919
1017
|
try {
|
|
@@ -954,8 +1052,8 @@ export class DiskTier {
|
|
|
954
1052
|
|
|
955
1053
|
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
956
1054
|
// Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
|
|
957
|
-
if (file.length
|
|
958
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
1055
|
+
if (file.length >= 77 && file[64] === '_') {
|
|
1056
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
959
1057
|
if (expiresAt <= now) {
|
|
960
1058
|
const filePath = path.join(bucketPath, file);
|
|
961
1059
|
try {
|
|
@@ -1019,6 +1117,9 @@ export class DiskTier {
|
|
|
1019
1117
|
|
|
1020
1118
|
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1021
1119
|
clear(): number {
|
|
1120
|
+
this.epoch++;
|
|
1121
|
+
this.pendingSaves.clear();
|
|
1122
|
+
this.invalidatedKeys.clear();
|
|
1022
1123
|
this.ensureDir();
|
|
1023
1124
|
if (!this.dirReady) return 0;
|
|
1024
1125
|
let cleared = 0;
|
|
@@ -1084,6 +1185,7 @@ export class DiskTier {
|
|
|
1084
1185
|
* yielding to the event loop via setImmediate between chunks.
|
|
1085
1186
|
*/
|
|
1086
1187
|
public async triggerChunkedPrune(): Promise<number> {
|
|
1188
|
+
if (this.closed) return 0;
|
|
1087
1189
|
if (this._isPruning) return 0;
|
|
1088
1190
|
this._isPruning = true;
|
|
1089
1191
|
this._pruneRounds++;
|
|
@@ -1094,7 +1196,7 @@ export class DiskTier {
|
|
|
1094
1196
|
const targetBytes = Math.floor(this.opts.maxBytes * 0.60);
|
|
1095
1197
|
|
|
1096
1198
|
if (this._db && this._stmtPruneChunk) {
|
|
1097
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
1199
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
1098
1200
|
const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
1099
1201
|
if (!rows || rows.length === 0) break;
|
|
1100
1202
|
|
|
@@ -1116,7 +1218,7 @@ export class DiskTier {
|
|
|
1116
1218
|
}
|
|
1117
1219
|
}
|
|
1118
1220
|
} else {
|
|
1119
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
1221
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
1120
1222
|
const files = this.walkCacheFiles();
|
|
1121
1223
|
if (files.length === 0) break;
|
|
1122
1224
|
const chunk = files.slice(0, 500);
|
|
@@ -1214,6 +1316,10 @@ export class DiskTier {
|
|
|
1214
1316
|
|
|
1215
1317
|
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1216
1318
|
close(): void {
|
|
1319
|
+
this.closed = true;
|
|
1320
|
+
this.epoch++;
|
|
1321
|
+
this.pendingSaves.clear();
|
|
1322
|
+
this.invalidatedKeys.clear();
|
|
1217
1323
|
if (this._db) {
|
|
1218
1324
|
try { this._db.close(); } catch { /* ok */ }
|
|
1219
1325
|
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|