tricache 0.7.0 → 0.7.1
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 +1428 -1428
- package/bin/tricache.js +8 -8
- package/dist/cache-service-5GATUYAK.js +7 -0
- package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
- package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
- package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
- package/dist/cli.cjs +113 -56
- package/dist/cli.js +3 -3
- package/dist/drizzle/index.cjs +114 -57
- package/dist/drizzle/index.d.ts +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/http/index.cjs +149 -64
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.js +38 -10
- package/dist/index.cjs +112 -55
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/nestjs/index.cjs +112 -55
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +2 -2
- package/dist/next/index.cjs +143 -63
- package/dist/next/index.d.ts +10 -6
- package/dist/next/index.js +33 -10
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +1 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +26 -15
- package/dist/serialize-worker.js +1 -1
- package/package.json +4 -2
- package/src/cache-service.ts +3294 -3226
- package/src/cli.ts +143 -143
- package/src/compression.ts +56 -63
- package/src/disk-tier.ts +821 -821
- package/src/encryption.ts +513 -493
- package/src/http/index.ts +265 -223
- package/src/next/cache-handler.ts +268 -244
- package/src/prisma/index.ts +154 -151
- package/src/smart-memory-cache.ts +1026 -1024
- package/src/types.ts +911 -902
- package/dist/cache-service-AJASH5FX.js +0 -7
package/src/disk-tier.ts
CHANGED
|
@@ -1,821 +1,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 { pack, unpack } from 'msgpackr';
|
|
21
|
-
import type { DiskCacheEntry, ILogger } from './types.js';
|
|
22
|
-
import type { CacheEncryption } from './encryption.js';
|
|
23
|
-
import {
|
|
24
|
-
compressWithHeader,
|
|
25
|
-
decompressWithHeader,
|
|
26
|
-
type CompressionAlgorithm,
|
|
27
|
-
} from './compression.js';
|
|
28
|
-
|
|
29
|
-
// ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
|
|
30
|
-
// Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
|
|
31
|
-
// Falls back to file-only mode silently when unavailable (edge runtimes, etc.).
|
|
32
|
-
type _SqliteRow = Record<string, unknown>;
|
|
33
|
-
type _SqliteStmt = {
|
|
34
|
-
get(...p: unknown[]): _SqliteRow | undefined;
|
|
35
|
-
all(...p: unknown[]): _SqliteRow[];
|
|
36
|
-
run(...p: unknown[]): void;
|
|
37
|
-
};
|
|
38
|
-
type _SqliteDB = {
|
|
39
|
-
prepare(sql: string): _SqliteStmt;
|
|
40
|
-
exec(sql: string): void;
|
|
41
|
-
close(): void;
|
|
42
|
-
};
|
|
43
|
-
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
44
|
-
try {
|
|
45
|
-
// process.getBuiltinModule is available in Node >= 22.3.0 (within our >=22.13.0 engine
|
|
46
|
-
// requirement). It's synchronous and does not require the esbuild __require shim.
|
|
47
|
-
const sqlite = (process as unknown as { getBuiltinModule(m: string): unknown })
|
|
48
|
-
.getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
|
|
49
|
-
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
50
|
-
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
51
|
-
// ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
|
|
52
|
-
// DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
|
|
53
|
-
// delegates the payload cipher to CacheEncryption, which already supports all four
|
|
54
|
-
// modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor) and is the single source of
|
|
55
|
-
// truth for the on-disk binary format. This avoids a hardcoded aes-256-gcm that
|
|
56
|
-
// threw (and silently no-op'd the disk tier) for any non-default mode.
|
|
57
|
-
const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
|
|
58
|
-
/**
|
|
59
|
-
* V2 file format — expiresAt stored in plaintext outside the ciphertext so the
|
|
60
|
-
* janitor can check expiry with a 16-byte header read rather than a full
|
|
61
|
-
* decrypt + unpack. Layout (bytes):
|
|
62
|
-
* 0–7 DISK_MAGIC_V2 ("DTIERV2\0")
|
|
63
|
-
* 8–15 expiresAt, uint64 LE (ms since epoch, outside encryption)
|
|
64
|
-
* 16+ encryptV2(msgpack(DiskPayload)) — IV+TAG+ct if key set, else raw msgpack
|
|
65
|
-
*/
|
|
66
|
-
const DISK_MAGIC_V2 = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x32, 0x00]); // "DTIERV2\0"
|
|
67
|
-
const V2_HEADER_LEN = 16; // magic(8) + expiresAt(8)
|
|
68
|
-
|
|
69
|
-
interface DiskPayload {
|
|
70
|
-
version: number;
|
|
71
|
-
key: string;
|
|
72
|
-
entry: DiskCacheEntry;
|
|
73
|
-
writtenAt: number;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const DISK_TIER_VERSION = 1;
|
|
77
|
-
|
|
78
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
79
|
-
|
|
80
|
-
export interface DiskTierOptions {
|
|
81
|
-
dir: string;
|
|
82
|
-
maxBytes: number;
|
|
83
|
-
entryMaxBytes: number;
|
|
84
|
-
forbiddenPrefixes: readonly string[];
|
|
85
|
-
/** Mode-aware encryption instance. When set, disk files are encrypted with the
|
|
86
|
-
* same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
|
|
87
|
-
* When null, files are written unencrypted. Pass `cache.encryption` here. */
|
|
88
|
-
encryption?: CacheEncryption | null;
|
|
89
|
-
compression?: CompressionAlgorithm;
|
|
90
|
-
compressionThresholdBytes?: number;
|
|
91
|
-
logger: ILogger;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export class DiskTier {
|
|
95
|
-
private readonly opts: DiskTierOptions;
|
|
96
|
-
private dirReady = false;
|
|
97
|
-
private diskUsageBytes = 0;
|
|
98
|
-
private usageCounted = false;
|
|
99
|
-
private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
|
|
100
|
-
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
101
|
-
private _nextJanitorBucket = 0;
|
|
102
|
-
|
|
103
|
-
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
104
|
-
private _db: _SqliteDB | null = null;
|
|
105
|
-
private _stmtInsert: _SqliteStmt | null = null; // INSERT OR REPLACE
|
|
106
|
-
private _stmtSelect: _SqliteStmt | null = null; // SELECT by key_hash
|
|
107
|
-
private _stmtDelete: _SqliteStmt | null = null; // DELETE by key_hash
|
|
108
|
-
private _stmtExpire: _SqliteStmt | null = null; // SELECT expired rows
|
|
109
|
-
private _stmtDelExp: _SqliteStmt | null = null; // DELETE expired rows
|
|
110
|
-
private _stmtStats: _SqliteStmt | null = null; // COUNT + SUM(size)
|
|
111
|
-
|
|
112
|
-
constructor(opts: DiskTierOptions) {
|
|
113
|
-
this.opts = opts;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
117
|
-
|
|
118
|
-
private ensureDir(): void {
|
|
119
|
-
if (this.dirReady) return;
|
|
120
|
-
try {
|
|
121
|
-
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
122
|
-
this.dirReady = true;
|
|
123
|
-
this._initSqlite();
|
|
124
|
-
} catch (err) {
|
|
125
|
-
this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: (err as Error).message });
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
131
|
-
* is confirmed to exist. On any failure the instance silently falls back to
|
|
132
|
-
* file-only mode — all public methods handle `this._db === null`.
|
|
133
|
-
*
|
|
134
|
-
* Schema:
|
|
135
|
-
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
136
|
-
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
137
|
-
*
|
|
138
|
-
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
139
|
-
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
140
|
-
*/
|
|
141
|
-
private _initSqlite(): void {
|
|
142
|
-
if (!_SqliteDB) return;
|
|
143
|
-
try {
|
|
144
|
-
const dbPath = path.join(this.opts.dir, 'meta.db');
|
|
145
|
-
this._db = new _SqliteDB(dbPath);
|
|
146
|
-
this._db.exec(`
|
|
147
|
-
PRAGMA journal_mode = WAL;
|
|
148
|
-
PRAGMA synchronous = NORMAL;
|
|
149
|
-
PRAGMA temp_store = MEMORY;
|
|
150
|
-
CREATE TABLE IF NOT EXISTS meta (
|
|
151
|
-
key_hash TEXT PRIMARY KEY,
|
|
152
|
-
file_path TEXT NOT NULL,
|
|
153
|
-
expires_at INTEGER NOT NULL,
|
|
154
|
-
size INTEGER NOT NULL DEFAULT 0
|
|
155
|
-
);
|
|
156
|
-
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
157
|
-
`);
|
|
158
|
-
this._stmtInsert = this._db.prepare(
|
|
159
|
-
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)',
|
|
160
|
-
);
|
|
161
|
-
this._stmtSelect = this._db.prepare(
|
|
162
|
-
'SELECT file_path, expires_at FROM meta WHERE key_hash = ?',
|
|
163
|
-
);
|
|
164
|
-
this._stmtDelete = this._db.prepare('DELETE FROM meta WHERE key_hash = ?');
|
|
165
|
-
this._stmtExpire = this._db.prepare(
|
|
166
|
-
'SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?',
|
|
167
|
-
);
|
|
168
|
-
this._stmtDelExp = this._db.prepare('DELETE FROM meta WHERE expires_at <= ?');
|
|
169
|
-
this._stmtStats = this._db.prepare(
|
|
170
|
-
'SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta',
|
|
171
|
-
);
|
|
172
|
-
// Seed in-memory counters from the index — avoids startup walkCacheFiles().
|
|
173
|
-
const row = this._stmtStats.get() as { cnt: number; bytes: number };
|
|
174
|
-
this.fileCount = row.cnt;
|
|
175
|
-
this.diskUsageBytes = row.bytes;
|
|
176
|
-
this.usageCounted = true;
|
|
177
|
-
this.opts.logger.debug('DiskTier: SQLite index ready', { entries: row.cnt });
|
|
178
|
-
} catch (err) {
|
|
179
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
180
|
-
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
181
|
-
this.opts.logger.warn('DiskTier: SQLite init failed, using file-only mode', {
|
|
182
|
-
error: (err as Error).message,
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
private ensureUsageCounted(): void {
|
|
188
|
-
if (this.usageCounted) return;
|
|
189
|
-
this.usageCounted = true;
|
|
190
|
-
// SQLite path: counts were already seeded in _initSqlite() — nothing more to do.
|
|
191
|
-
if (this._db) return;
|
|
192
|
-
try {
|
|
193
|
-
this.ensureDir();
|
|
194
|
-
let total = 0;
|
|
195
|
-
const files = this.walkCacheFiles();
|
|
196
|
-
this.fileCount = files.length;
|
|
197
|
-
for (const filePath of files) {
|
|
198
|
-
try { total += fs.statSync(filePath).size; } catch { /* ok */ }
|
|
199
|
-
}
|
|
200
|
-
this.diskUsageBytes = total;
|
|
201
|
-
} catch { this.diskUsageBytes = 0; this.fileCount = 0; }
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
206
|
-
* Kept separate from path construction so callers can find files by prefix
|
|
207
|
-
* without knowing which filename generation was used when the file was written.
|
|
208
|
-
*/
|
|
209
|
-
private keyToHash(key: string): string {
|
|
210
|
-
return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Build the write path for a NEW file (V3 generation).
|
|
215
|
-
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
216
|
-
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
217
|
-
*
|
|
218
|
-
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
219
|
-
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
220
|
-
*
|
|
221
|
-
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
222
|
-
*/
|
|
223
|
-
private hashToWritePath(hash: string, expiresAt: number): string {
|
|
224
|
-
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, '0')}`);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Find the on-disk file for a key hash, handling all filename generations:
|
|
229
|
-
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
230
|
-
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
231
|
-
* Returns null when the bucket dir does not exist or the key is absent.
|
|
232
|
-
*/
|
|
233
|
-
private findFilePath(hash: string): string | null {
|
|
234
|
-
const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
|
|
235
|
-
let files: string[];
|
|
236
|
-
try { files = fs.readdirSync(bucketPath); } catch { return null; }
|
|
237
|
-
// Return the lexicographically largest match: V3 filenames are
|
|
238
|
-
// "{hash}_{expiresHex12}", so lex-max = largest timestamp = newest entry.
|
|
239
|
-
// If the same key was evicted to disk twice (different TTLs → different names),
|
|
240
|
-
// this ensures we always serve and delete the freshest copy; the janitor cleans
|
|
241
|
-
// up the stale one when its encoded timestamp expires.
|
|
242
|
-
let match: string | undefined;
|
|
243
|
-
for (const f of files) {
|
|
244
|
-
if ((f === hash || f.startsWith(hash + '_')) && (!match || f > match)) match = f;
|
|
245
|
-
}
|
|
246
|
-
if (!match) return null;
|
|
247
|
-
return path.join(bucketPath, match);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
252
|
-
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
253
|
-
* files written by older versions).
|
|
254
|
-
*/
|
|
255
|
-
private walkCacheFiles(): string[] {
|
|
256
|
-
const results: string[] = [];
|
|
257
|
-
let topEntries: string[];
|
|
258
|
-
try { topEntries = fs.readdirSync(this.opts.dir); } catch { return results; }
|
|
259
|
-
for (const top of topEntries) {
|
|
260
|
-
const topPath = path.join(this.opts.dir, top);
|
|
261
|
-
try {
|
|
262
|
-
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
263
|
-
for (const file of fs.readdirSync(topPath)) {
|
|
264
|
-
results.push(path.join(topPath, file));
|
|
265
|
-
}
|
|
266
|
-
} catch { /* skip locked/gone */ }
|
|
267
|
-
}
|
|
268
|
-
return results;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private isForbidden(key: string): boolean {
|
|
272
|
-
return this.opts.forbiddenPrefixes.some(p => key.startsWith(p));
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
private encrypt(data: Buffer): Buffer {
|
|
276
|
-
if (!this.opts.encryption) return data;
|
|
277
|
-
// V1 envelope: DISK_MAGIC prefix wrapping the mode-aware CacheEncryption blob.
|
|
278
|
-
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
private decrypt(data: Buffer): Buffer {
|
|
282
|
-
const mLen = DISK_MAGIC.length;
|
|
283
|
-
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
284
|
-
if (!this.opts.encryption) throw new Error('DiskTier: entry is encrypted but no encryption configured');
|
|
285
|
-
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
290
|
-
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
291
|
-
* Returns the buffer unchanged when no encryption instance is configured.
|
|
292
|
-
*/
|
|
293
|
-
private encryptV2(data: Buffer): Buffer {
|
|
294
|
-
if (!this.opts.encryption) return data;
|
|
295
|
-
return this.opts.encryption.encryptBuffer(data);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
300
|
-
* When an encryption instance is configured the format is the mode-aware
|
|
301
|
-
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
302
|
-
* without one the payload is raw msgpack.
|
|
303
|
-
*/
|
|
304
|
-
private decryptV2(inner: Buffer): Buffer {
|
|
305
|
-
if (!this.opts.encryption) return inner;
|
|
306
|
-
return this.opts.encryption.decryptBuffer(inner);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// ── Public API ────────────────────────────────────────────────────────────
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Spill an evicted L1 entry to disk.
|
|
313
|
-
*
|
|
314
|
-
* Returns a Promise that resolves when the file is durably written. Callers
|
|
315
|
-
* that treat the spill as fire-and-forget should do:
|
|
316
|
-
* `void disk.save(key, entry)`
|
|
317
|
-
*
|
|
318
|
-
* Implementation notes:
|
|
319
|
-
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
320
|
-
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
321
|
-
* on any external resource.
|
|
322
|
-
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
323
|
-
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
324
|
-
*/
|
|
325
|
-
async save(key: string, entry: DiskCacheEntry): Promise<void> {
|
|
326
|
-
if (this.isForbidden(key)) return;
|
|
327
|
-
if (entry.expiresAt <= Date.now()) return;
|
|
328
|
-
|
|
329
|
-
this.ensureDir();
|
|
330
|
-
if (!this.dirReady) return;
|
|
331
|
-
this.ensureUsageCounted();
|
|
332
|
-
if (this.diskUsageBytes >= this.opts.maxBytes) return; // disk cap hit
|
|
333
|
-
|
|
334
|
-
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
335
|
-
let final: Buffer;
|
|
336
|
-
try {
|
|
337
|
-
const payload: DiskPayload = {
|
|
338
|
-
version: DISK_TIER_VERSION,
|
|
339
|
-
key,
|
|
340
|
-
entry: {
|
|
341
|
-
...entry,
|
|
342
|
-
data: entry.data instanceof Uint8Array
|
|
343
|
-
? Buffer.from(entry.data)
|
|
344
|
-
: entry.data,
|
|
345
|
-
},
|
|
346
|
-
writtenAt: Date.now(),
|
|
347
|
-
};
|
|
348
|
-
const packed = pack(payload);
|
|
349
|
-
if (packed.length > this.opts.entryMaxBytes) return;
|
|
350
|
-
let toEncrypt = packed;
|
|
351
|
-
if (this.opts.compression && this.opts.compression !== 'none' && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
352
|
-
toEncrypt = compressWithHeader(packed, this.opts.compression);
|
|
353
|
-
}
|
|
354
|
-
// V2 format: 16-byte plaintext header (magic + expiresAt) followed by the
|
|
355
|
-
// encrypted-or-raw payload. The plaintext expiresAt allows purgeNextBucket()
|
|
356
|
-
// to check expiry with a 16-byte partial read — no decrypt or unpack needed.
|
|
357
|
-
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
358
|
-
DISK_MAGIC_V2.copy(header, 0);
|
|
359
|
-
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
360
|
-
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
361
|
-
} catch (err) {
|
|
362
|
-
this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
|
|
367
|
-
const hash = this.keyToHash(key);
|
|
368
|
-
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
369
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
370
|
-
this.diskUsageBytes += final.length; // optimistic — rolled back on error
|
|
371
|
-
this.fileCount++;
|
|
372
|
-
|
|
373
|
-
try {
|
|
374
|
-
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
375
|
-
await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
|
|
376
|
-
|
|
377
|
-
// Atomic rename with micro-retry loop for Windows NTFS handle release
|
|
378
|
-
try {
|
|
379
|
-
await fs.promises.rename(tmpPath, filePath);
|
|
380
|
-
} catch (renameErr: unknown) {
|
|
381
|
-
const code = (renameErr as { code?: string })?.code;
|
|
382
|
-
if (code === 'EBUSY' || code === 'EPERM') {
|
|
383
|
-
await new Promise<void>(resolve => setTimeout(resolve, 5));
|
|
384
|
-
await fs.promises.rename(tmpPath, filePath);
|
|
385
|
-
} else {
|
|
386
|
-
throw renameErr;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
if (this._db) {
|
|
391
|
-
this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length);
|
|
392
|
-
}
|
|
393
|
-
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
394
|
-
} catch (err) {
|
|
395
|
-
try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
|
|
396
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
397
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
398
|
-
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
399
|
-
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
404
|
-
load(key: string): DiskCacheEntry | null {
|
|
405
|
-
if (this.isForbidden(key)) return null;
|
|
406
|
-
this.ensureDir();
|
|
407
|
-
if (!this.dirReady) return null;
|
|
408
|
-
|
|
409
|
-
const hash = this.keyToHash(key);
|
|
410
|
-
let filePath: string | null;
|
|
411
|
-
|
|
412
|
-
if (this._db) {
|
|
413
|
-
// SQLite fast path: single B-tree lookup replaces readdirSync + filename scan.
|
|
414
|
-
const row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
|
|
415
|
-
if (!row) return null;
|
|
416
|
-
if (row.expires_at <= Date.now()) {
|
|
417
|
-
this._stmtDelete!.run(hash);
|
|
418
|
-
try {
|
|
419
|
-
const sz = fs.statSync(row.file_path).size;
|
|
420
|
-
fs.unlinkSync(row.file_path);
|
|
421
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
422
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
423
|
-
} catch { /* ok */ }
|
|
424
|
-
return null;
|
|
425
|
-
}
|
|
426
|
-
filePath = row.file_path;
|
|
427
|
-
} else {
|
|
428
|
-
filePath = this.findFilePath(hash);
|
|
429
|
-
if (!filePath) return null;
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
try {
|
|
433
|
-
// V3 filename fast-path (file-only mode): expiresAt encoded in name avoids
|
|
434
|
-
// opening the file when the entry is already stale.
|
|
435
|
-
if (!this._db) {
|
|
436
|
-
const filename = path.basename(filePath);
|
|
437
|
-
if (filename.length === 77 && filename[64] === '_') {
|
|
438
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
439
|
-
if (expiresAt <= Date.now()) {
|
|
440
|
-
try {
|
|
441
|
-
const sz = fs.statSync(filePath).size;
|
|
442
|
-
fs.unlinkSync(filePath);
|
|
443
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
444
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
445
|
-
} catch { /* ok */ }
|
|
446
|
-
return null;
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const stat = fs.statSync(filePath);
|
|
452
|
-
if (stat.size > this.opts.entryMaxBytes) {
|
|
453
|
-
fs.unlinkSync(filePath);
|
|
454
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
455
|
-
if (this._db) this._stmtDelete!.run(hash);
|
|
456
|
-
return null;
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
const raw = fs.readFileSync(filePath);
|
|
460
|
-
// Delete immediately — entry will be promoted back to L1
|
|
461
|
-
try {
|
|
462
|
-
fs.unlinkSync(filePath);
|
|
463
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
464
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
465
|
-
} catch { /* ok */ }
|
|
466
|
-
if (this._db) this._stmtDelete!.run(hash);
|
|
467
|
-
|
|
468
|
-
let decrypted: Buffer;
|
|
469
|
-
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
470
|
-
// V2/V3: quick expiry guard from plaintext header before paying decrypt cost
|
|
471
|
-
const expiresAt = Number(raw.readBigUInt64LE(8));
|
|
472
|
-
if (expiresAt <= Date.now()) return null;
|
|
473
|
-
try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
|
|
474
|
-
} else {
|
|
475
|
-
// V1 / legacy unencrypted — backward compat
|
|
476
|
-
try { decrypted = this.decrypt(raw); } catch { return null; }
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
|
|
480
|
-
const payload = unpack(uncompressed) as DiskPayload;
|
|
481
|
-
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
482
|
-
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
483
|
-
|
|
484
|
-
const entry = payload.entry;
|
|
485
|
-
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
486
|
-
|
|
487
|
-
this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
488
|
-
return entry;
|
|
489
|
-
} catch (err) {
|
|
490
|
-
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
491
|
-
this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
492
|
-
return null;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
/** Explicitly delete a key from disk (cache invalidation). */
|
|
497
|
-
delete(key: string): void {
|
|
498
|
-
const hash = this.keyToHash(key);
|
|
499
|
-
let filePath: string | null;
|
|
500
|
-
if (this._db) {
|
|
501
|
-
const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
|
|
502
|
-
filePath = row?.file_path ?? null;
|
|
503
|
-
this._stmtDelete!.run(hash);
|
|
504
|
-
} else {
|
|
505
|
-
filePath = this.findFilePath(hash);
|
|
506
|
-
}
|
|
507
|
-
if (!filePath) return;
|
|
508
|
-
try {
|
|
509
|
-
const stat = fs.statSync(filePath);
|
|
510
|
-
fs.unlinkSync(filePath);
|
|
511
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
512
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
513
|
-
} catch { /* ok */ }
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
/** Purge all expired entries. Returns number deleted. */
|
|
517
|
-
purgeExpired(): number {
|
|
518
|
-
this.ensureDir();
|
|
519
|
-
if (!this.dirReady) return 0;
|
|
520
|
-
|
|
521
|
-
if (this._db) {
|
|
522
|
-
// SQLite fast path: one indexed query finds all expired rows.
|
|
523
|
-
const now = Date.now();
|
|
524
|
-
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
525
|
-
for (const row of expired) {
|
|
526
|
-
try {
|
|
527
|
-
fs.unlinkSync(row.file_path);
|
|
528
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
529
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
530
|
-
} catch { /* already gone */ }
|
|
531
|
-
}
|
|
532
|
-
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
533
|
-
return expired.length;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
const now = Date.now();
|
|
537
|
-
let purged = 0;
|
|
538
|
-
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
539
|
-
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
540
|
-
for (const filePath of this.walkCacheFiles()) {
|
|
541
|
-
const filename = path.basename(filePath);
|
|
542
|
-
|
|
543
|
-
// Clean up orphaned .tmp files older than 5 minutes
|
|
544
|
-
if (filename.endsWith('.tmp')) {
|
|
545
|
-
try {
|
|
546
|
-
const stat = fs.statSync(filePath);
|
|
547
|
-
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
548
|
-
fs.unlinkSync(filePath);
|
|
549
|
-
purged++;
|
|
550
|
-
}
|
|
551
|
-
} catch { /* already gone */ }
|
|
552
|
-
continue;
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
556
|
-
if (filename.length === 77 && filename[64] === '_') {
|
|
557
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
558
|
-
if (expiresAt <= now) {
|
|
559
|
-
try {
|
|
560
|
-
const sz = fs.statSync(filePath).size;
|
|
561
|
-
fs.unlinkSync(filePath);
|
|
562
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
563
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
564
|
-
purged++;
|
|
565
|
-
} catch { /* already gone */ }
|
|
566
|
-
}
|
|
567
|
-
continue;
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
// ── V2 header fast path: read only the 16-byte plaintext header ────────
|
|
571
|
-
let fd = -1;
|
|
572
|
-
try {
|
|
573
|
-
fd = fs.openSync(filePath, 'r');
|
|
574
|
-
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
575
|
-
fs.closeSync(fd); fd = -1;
|
|
576
|
-
|
|
577
|
-
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
578
|
-
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
579
|
-
if (expiresAt <= now) {
|
|
580
|
-
try {
|
|
581
|
-
const sz = fs.statSync(filePath).size;
|
|
582
|
-
fs.unlinkSync(filePath);
|
|
583
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
584
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
585
|
-
purged++;
|
|
586
|
-
} catch { /* already gone */ }
|
|
587
|
-
}
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
// ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
|
|
592
|
-
const stat = fs.statSync(filePath);
|
|
593
|
-
if (stat.size > this.opts.entryMaxBytes) {
|
|
594
|
-
fs.unlinkSync(filePath);
|
|
595
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
596
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
597
|
-
purged++;
|
|
598
|
-
continue;
|
|
599
|
-
}
|
|
600
|
-
const raw = fs.readFileSync(filePath);
|
|
601
|
-
let dec: Buffer;
|
|
602
|
-
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
603
|
-
const payload = unpack(dec) as DiskPayload;
|
|
604
|
-
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
605
|
-
fs.unlinkSync(filePath);
|
|
606
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
607
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
608
|
-
purged++;
|
|
609
|
-
}
|
|
610
|
-
} catch { /* skip locked/gone */ } finally {
|
|
611
|
-
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
return purged;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
/**
|
|
618
|
-
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
619
|
-
*
|
|
620
|
-
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
621
|
-
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
622
|
-
* wheel. All expired entries are found and deleted in a single pass — the
|
|
623
|
-
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
624
|
-
* incremented so tests that inspect the counter continue to work.
|
|
625
|
-
*
|
|
626
|
-
* File-only fallback:
|
|
627
|
-
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
628
|
-
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
629
|
-
*
|
|
630
|
-
* Returns the number of entries deleted in this tick.
|
|
631
|
-
*/
|
|
632
|
-
purgeNextBucket(): number {
|
|
633
|
-
this.ensureDir();
|
|
634
|
-
if (!this.dirReady) return 0;
|
|
635
|
-
// Always advance the pointer — preserves observable state for tests and
|
|
636
|
-
// metrics regardless of which code path runs below.
|
|
637
|
-
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
638
|
-
|
|
639
|
-
if (this._db) {
|
|
640
|
-
const now = Date.now();
|
|
641
|
-
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
642
|
-
for (const row of expired) {
|
|
643
|
-
try {
|
|
644
|
-
fs.unlinkSync(row.file_path);
|
|
645
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
646
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
647
|
-
} catch { /* already gone */ }
|
|
648
|
-
}
|
|
649
|
-
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
650
|
-
|
|
651
|
-
// Belt-and-suspenders: scan one filesystem bucket for orphan files — files
|
|
652
|
-
// written to disk before a crash between writeFile() and the SQLite INSERT.
|
|
653
|
-
// V3 fast path: no file I/O for live entries (expiry is in the filename).
|
|
654
|
-
// Expired orphans are unlinked here; they are invisible to the SQLite query.
|
|
655
|
-
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
656
|
-
const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, '0'));
|
|
657
|
-
let orphanFiles: string[];
|
|
658
|
-
try { orphanFiles = fs.readdirSync(orphanBucketP); } catch { return expired.length; }
|
|
659
|
-
for (const file of orphanFiles) {
|
|
660
|
-
if (file.endsWith('.tmp')) {
|
|
661
|
-
const fp = path.join(orphanBucketP, file);
|
|
662
|
-
try {
|
|
663
|
-
const stat = fs.statSync(fp);
|
|
664
|
-
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
665
|
-
fs.unlinkSync(fp);
|
|
666
|
-
}
|
|
667
|
-
} catch { /* already gone */ }
|
|
668
|
-
continue;
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
if (file.length === 77 && file[64] === '_') {
|
|
672
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
673
|
-
if (expiresAt <= now) {
|
|
674
|
-
const fp = path.join(orphanBucketP, file);
|
|
675
|
-
try {
|
|
676
|
-
const sz = fs.statSync(fp).size;
|
|
677
|
-
fs.unlinkSync(fp);
|
|
678
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
679
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
680
|
-
} catch { /* already gone */ }
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
return expired.length;
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
// ── File-only fallback: one-bucket scan ───────────────────────────────
|
|
688
|
-
const bucket = (this._nextJanitorBucket - 1 + 256) % 256; // use the bucket we just advanced past
|
|
689
|
-
const bucketHex = bucket.toString(16).padStart(2, '0');
|
|
690
|
-
const bucketPath = path.join(this.opts.dir, bucketHex);
|
|
691
|
-
let files: string[];
|
|
692
|
-
try { files = fs.readdirSync(bucketPath); } catch { return 0; }
|
|
693
|
-
const now = Date.now();
|
|
694
|
-
let purged = 0;
|
|
695
|
-
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
696
|
-
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
697
|
-
for (const file of files) {
|
|
698
|
-
// Clean up orphaned .tmp files older than 5 minutes
|
|
699
|
-
if (file.endsWith('.tmp')) {
|
|
700
|
-
const fp = path.join(bucketPath, file);
|
|
701
|
-
try {
|
|
702
|
-
const stat = fs.statSync(fp);
|
|
703
|
-
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
704
|
-
fs.unlinkSync(fp);
|
|
705
|
-
purged++;
|
|
706
|
-
}
|
|
707
|
-
} catch { /* already gone */ }
|
|
708
|
-
continue;
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
712
|
-
// Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
|
|
713
|
-
if (file.length === 77 && file[64] === '_') {
|
|
714
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
715
|
-
if (expiresAt <= now) {
|
|
716
|
-
const filePath = path.join(bucketPath, file);
|
|
717
|
-
try {
|
|
718
|
-
const sz = fs.statSync(filePath).size;
|
|
719
|
-
fs.unlinkSync(filePath);
|
|
720
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
721
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
722
|
-
purged++;
|
|
723
|
-
} catch { /* already gone */ }
|
|
724
|
-
}
|
|
725
|
-
continue; // live or just deleted — no further work
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
// ── V2 header path: open+read(16)+close ───────────────────────────────
|
|
729
|
-
const filePath = path.join(bucketPath, file);
|
|
730
|
-
let fd = -1;
|
|
731
|
-
try {
|
|
732
|
-
fd = fs.openSync(filePath, 'r');
|
|
733
|
-
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
734
|
-
fs.closeSync(fd); fd = -1;
|
|
735
|
-
|
|
736
|
-
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
737
|
-
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
738
|
-
if (expiresAt <= now) {
|
|
739
|
-
try {
|
|
740
|
-
const sz = fs.statSync(filePath).size;
|
|
741
|
-
fs.unlinkSync(filePath);
|
|
742
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
743
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
744
|
-
purged++;
|
|
745
|
-
} catch { /* already gone */ }
|
|
746
|
-
}
|
|
747
|
-
continue;
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
// ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
|
|
751
|
-
const stat = fs.statSync(filePath);
|
|
752
|
-
if (stat.size > this.opts.entryMaxBytes) {
|
|
753
|
-
fs.unlinkSync(filePath);
|
|
754
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
755
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
756
|
-
purged++;
|
|
757
|
-
continue;
|
|
758
|
-
}
|
|
759
|
-
const raw = fs.readFileSync(filePath);
|
|
760
|
-
let dec: Buffer;
|
|
761
|
-
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
762
|
-
const payload = unpack(dec) as DiskPayload;
|
|
763
|
-
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
764
|
-
fs.unlinkSync(filePath);
|
|
765
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
766
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
767
|
-
purged++;
|
|
768
|
-
}
|
|
769
|
-
} catch { /* skip locked/gone */ } finally {
|
|
770
|
-
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
return purged;
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
777
|
-
clear(): number {
|
|
778
|
-
this.ensureDir();
|
|
779
|
-
if (!this.dirReady) return 0;
|
|
780
|
-
let cleared = 0;
|
|
781
|
-
for (const filePath of this.walkCacheFiles()) {
|
|
782
|
-
try {
|
|
783
|
-
const stat = fs.statSync(filePath);
|
|
784
|
-
fs.unlinkSync(filePath);
|
|
785
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
786
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
787
|
-
cleared++;
|
|
788
|
-
} catch { /* skip locked/gone */ }
|
|
789
|
-
}
|
|
790
|
-
if (this._db) {
|
|
791
|
-
this._db.exec('DELETE FROM meta');
|
|
792
|
-
this.diskUsageBytes = 0;
|
|
793
|
-
this.fileCount = 0;
|
|
794
|
-
}
|
|
795
|
-
return cleared;
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
get stats(): { files: number; sizeKB: number; maxKB: number } {
|
|
799
|
-
if (this._db) {
|
|
800
|
-
// Query the index for authoritative counts — O(1) SQLite aggregate.
|
|
801
|
-
const row = this._stmtStats!.get() as { cnt: number; bytes: number };
|
|
802
|
-
this.fileCount = row.cnt;
|
|
803
|
-
this.diskUsageBytes = row.bytes;
|
|
804
|
-
}
|
|
805
|
-
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
809
|
-
get indexMode(): 'sqlite' | 'file-only' {
|
|
810
|
-
return this._db ? 'sqlite' : 'file-only';
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
814
|
-
close(): void {
|
|
815
|
-
if (this._db) {
|
|
816
|
-
try { this._db.close(); } catch { /* ok */ }
|
|
817
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
818
|
-
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
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 { pack, unpack } from 'msgpackr';
|
|
21
|
+
import type { DiskCacheEntry, ILogger } from './types.js';
|
|
22
|
+
import type { CacheEncryption } from './encryption.js';
|
|
23
|
+
import {
|
|
24
|
+
compressWithHeader,
|
|
25
|
+
decompressWithHeader,
|
|
26
|
+
type CompressionAlgorithm,
|
|
27
|
+
} from './compression.js';
|
|
28
|
+
|
|
29
|
+
// ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
|
|
30
|
+
// Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
|
|
31
|
+
// Falls back to file-only mode silently when unavailable (edge runtimes, etc.).
|
|
32
|
+
type _SqliteRow = Record<string, unknown>;
|
|
33
|
+
type _SqliteStmt = {
|
|
34
|
+
get(...p: unknown[]): _SqliteRow | undefined;
|
|
35
|
+
all(...p: unknown[]): _SqliteRow[];
|
|
36
|
+
run(...p: unknown[]): void;
|
|
37
|
+
};
|
|
38
|
+
type _SqliteDB = {
|
|
39
|
+
prepare(sql: string): _SqliteStmt;
|
|
40
|
+
exec(sql: string): void;
|
|
41
|
+
close(): void;
|
|
42
|
+
};
|
|
43
|
+
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
44
|
+
try {
|
|
45
|
+
// process.getBuiltinModule is available in Node >= 22.3.0 (within our >=22.13.0 engine
|
|
46
|
+
// requirement). It's synchronous and does not require the esbuild __require shim.
|
|
47
|
+
const sqlite = (process as unknown as { getBuiltinModule(m: string): unknown })
|
|
48
|
+
.getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
|
|
49
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
50
|
+
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
51
|
+
// ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
|
|
52
|
+
// DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
|
|
53
|
+
// delegates the payload cipher to CacheEncryption, which already supports all four
|
|
54
|
+
// modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor) and is the single source of
|
|
55
|
+
// truth for the on-disk binary format. This avoids a hardcoded aes-256-gcm that
|
|
56
|
+
// threw (and silently no-op'd the disk tier) for any non-default mode.
|
|
57
|
+
const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
|
|
58
|
+
/**
|
|
59
|
+
* V2 file format — expiresAt stored in plaintext outside the ciphertext so the
|
|
60
|
+
* janitor can check expiry with a 16-byte header read rather than a full
|
|
61
|
+
* decrypt + unpack. Layout (bytes):
|
|
62
|
+
* 0–7 DISK_MAGIC_V2 ("DTIERV2\0")
|
|
63
|
+
* 8–15 expiresAt, uint64 LE (ms since epoch, outside encryption)
|
|
64
|
+
* 16+ encryptV2(msgpack(DiskPayload)) — IV+TAG+ct if key set, else raw msgpack
|
|
65
|
+
*/
|
|
66
|
+
const DISK_MAGIC_V2 = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x32, 0x00]); // "DTIERV2\0"
|
|
67
|
+
const V2_HEADER_LEN = 16; // magic(8) + expiresAt(8)
|
|
68
|
+
|
|
69
|
+
interface DiskPayload {
|
|
70
|
+
version: number;
|
|
71
|
+
key: string;
|
|
72
|
+
entry: DiskCacheEntry;
|
|
73
|
+
writtenAt: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const DISK_TIER_VERSION = 1;
|
|
77
|
+
|
|
78
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
export interface DiskTierOptions {
|
|
81
|
+
dir: string;
|
|
82
|
+
maxBytes: number;
|
|
83
|
+
entryMaxBytes: number;
|
|
84
|
+
forbiddenPrefixes: readonly string[];
|
|
85
|
+
/** Mode-aware encryption instance. When set, disk files are encrypted with the
|
|
86
|
+
* same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
|
|
87
|
+
* When null, files are written unencrypted. Pass `cache.encryption` here. */
|
|
88
|
+
encryption?: CacheEncryption | null;
|
|
89
|
+
compression?: CompressionAlgorithm;
|
|
90
|
+
compressionThresholdBytes?: number;
|
|
91
|
+
logger: ILogger;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class DiskTier {
|
|
95
|
+
private readonly opts: DiskTierOptions;
|
|
96
|
+
private dirReady = false;
|
|
97
|
+
private diskUsageBytes = 0;
|
|
98
|
+
private usageCounted = false;
|
|
99
|
+
private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
|
|
100
|
+
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
101
|
+
private _nextJanitorBucket = 0;
|
|
102
|
+
|
|
103
|
+
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
104
|
+
private _db: _SqliteDB | null = null;
|
|
105
|
+
private _stmtInsert: _SqliteStmt | null = null; // INSERT OR REPLACE
|
|
106
|
+
private _stmtSelect: _SqliteStmt | null = null; // SELECT by key_hash
|
|
107
|
+
private _stmtDelete: _SqliteStmt | null = null; // DELETE by key_hash
|
|
108
|
+
private _stmtExpire: _SqliteStmt | null = null; // SELECT expired rows
|
|
109
|
+
private _stmtDelExp: _SqliteStmt | null = null; // DELETE expired rows
|
|
110
|
+
private _stmtStats: _SqliteStmt | null = null; // COUNT + SUM(size)
|
|
111
|
+
|
|
112
|
+
constructor(opts: DiskTierOptions) {
|
|
113
|
+
this.opts = opts;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
private ensureDir(): void {
|
|
119
|
+
if (this.dirReady) return;
|
|
120
|
+
try {
|
|
121
|
+
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
122
|
+
this.dirReady = true;
|
|
123
|
+
this._initSqlite();
|
|
124
|
+
} catch (err) {
|
|
125
|
+
this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: (err as Error).message });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
131
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
132
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
133
|
+
*
|
|
134
|
+
* Schema:
|
|
135
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
136
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
137
|
+
*
|
|
138
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
139
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
140
|
+
*/
|
|
141
|
+
private _initSqlite(): void {
|
|
142
|
+
if (!_SqliteDB) return;
|
|
143
|
+
try {
|
|
144
|
+
const dbPath = path.join(this.opts.dir, 'meta.db');
|
|
145
|
+
this._db = new _SqliteDB(dbPath);
|
|
146
|
+
this._db.exec(`
|
|
147
|
+
PRAGMA journal_mode = WAL;
|
|
148
|
+
PRAGMA synchronous = NORMAL;
|
|
149
|
+
PRAGMA temp_store = MEMORY;
|
|
150
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
151
|
+
key_hash TEXT PRIMARY KEY,
|
|
152
|
+
file_path TEXT NOT NULL,
|
|
153
|
+
expires_at INTEGER NOT NULL,
|
|
154
|
+
size INTEGER NOT NULL DEFAULT 0
|
|
155
|
+
);
|
|
156
|
+
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
157
|
+
`);
|
|
158
|
+
this._stmtInsert = this._db.prepare(
|
|
159
|
+
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)',
|
|
160
|
+
);
|
|
161
|
+
this._stmtSelect = this._db.prepare(
|
|
162
|
+
'SELECT file_path, expires_at FROM meta WHERE key_hash = ?',
|
|
163
|
+
);
|
|
164
|
+
this._stmtDelete = this._db.prepare('DELETE FROM meta WHERE key_hash = ?');
|
|
165
|
+
this._stmtExpire = this._db.prepare(
|
|
166
|
+
'SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?',
|
|
167
|
+
);
|
|
168
|
+
this._stmtDelExp = this._db.prepare('DELETE FROM meta WHERE expires_at <= ?');
|
|
169
|
+
this._stmtStats = this._db.prepare(
|
|
170
|
+
'SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta',
|
|
171
|
+
);
|
|
172
|
+
// Seed in-memory counters from the index — avoids startup walkCacheFiles().
|
|
173
|
+
const row = this._stmtStats.get() as { cnt: number; bytes: number };
|
|
174
|
+
this.fileCount = row.cnt;
|
|
175
|
+
this.diskUsageBytes = row.bytes;
|
|
176
|
+
this.usageCounted = true;
|
|
177
|
+
this.opts.logger.debug('DiskTier: SQLite index ready', { entries: row.cnt });
|
|
178
|
+
} catch (err) {
|
|
179
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
180
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
181
|
+
this.opts.logger.warn('DiskTier: SQLite init failed, using file-only mode', {
|
|
182
|
+
error: (err as Error).message,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private ensureUsageCounted(): void {
|
|
188
|
+
if (this.usageCounted) return;
|
|
189
|
+
this.usageCounted = true;
|
|
190
|
+
// SQLite path: counts were already seeded in _initSqlite() — nothing more to do.
|
|
191
|
+
if (this._db) return;
|
|
192
|
+
try {
|
|
193
|
+
this.ensureDir();
|
|
194
|
+
let total = 0;
|
|
195
|
+
const files = this.walkCacheFiles();
|
|
196
|
+
this.fileCount = files.length;
|
|
197
|
+
for (const filePath of files) {
|
|
198
|
+
try { total += fs.statSync(filePath).size; } catch { /* ok */ }
|
|
199
|
+
}
|
|
200
|
+
this.diskUsageBytes = total;
|
|
201
|
+
} catch { this.diskUsageBytes = 0; this.fileCount = 0; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
206
|
+
* Kept separate from path construction so callers can find files by prefix
|
|
207
|
+
* without knowing which filename generation was used when the file was written.
|
|
208
|
+
*/
|
|
209
|
+
private keyToHash(key: string): string {
|
|
210
|
+
return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Build the write path for a NEW file (V3 generation).
|
|
215
|
+
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
216
|
+
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
217
|
+
*
|
|
218
|
+
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
219
|
+
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
220
|
+
*
|
|
221
|
+
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
222
|
+
*/
|
|
223
|
+
private hashToWritePath(hash: string, expiresAt: number): string {
|
|
224
|
+
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, '0')}`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Find the on-disk file for a key hash, handling all filename generations:
|
|
229
|
+
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
230
|
+
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
231
|
+
* Returns null when the bucket dir does not exist or the key is absent.
|
|
232
|
+
*/
|
|
233
|
+
private findFilePath(hash: string): string | null {
|
|
234
|
+
const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
|
|
235
|
+
let files: string[];
|
|
236
|
+
try { files = fs.readdirSync(bucketPath); } catch { return null; }
|
|
237
|
+
// Return the lexicographically largest match: V3 filenames are
|
|
238
|
+
// "{hash}_{expiresHex12}", so lex-max = largest timestamp = newest entry.
|
|
239
|
+
// If the same key was evicted to disk twice (different TTLs → different names),
|
|
240
|
+
// this ensures we always serve and delete the freshest copy; the janitor cleans
|
|
241
|
+
// up the stale one when its encoded timestamp expires.
|
|
242
|
+
let match: string | undefined;
|
|
243
|
+
for (const f of files) {
|
|
244
|
+
if ((f === hash || f.startsWith(hash + '_')) && (!match || f > match)) match = f;
|
|
245
|
+
}
|
|
246
|
+
if (!match) return null;
|
|
247
|
+
return path.join(bucketPath, match);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
252
|
+
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
253
|
+
* files written by older versions).
|
|
254
|
+
*/
|
|
255
|
+
private walkCacheFiles(): string[] {
|
|
256
|
+
const results: string[] = [];
|
|
257
|
+
let topEntries: string[];
|
|
258
|
+
try { topEntries = fs.readdirSync(this.opts.dir); } catch { return results; }
|
|
259
|
+
for (const top of topEntries) {
|
|
260
|
+
const topPath = path.join(this.opts.dir, top);
|
|
261
|
+
try {
|
|
262
|
+
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
263
|
+
for (const file of fs.readdirSync(topPath)) {
|
|
264
|
+
results.push(path.join(topPath, file));
|
|
265
|
+
}
|
|
266
|
+
} catch { /* skip locked/gone */ }
|
|
267
|
+
}
|
|
268
|
+
return results;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private isForbidden(key: string): boolean {
|
|
272
|
+
return this.opts.forbiddenPrefixes.some(p => key.startsWith(p));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private encrypt(data: Buffer): Buffer {
|
|
276
|
+
if (!this.opts.encryption) return data;
|
|
277
|
+
// V1 envelope: DISK_MAGIC prefix wrapping the mode-aware CacheEncryption blob.
|
|
278
|
+
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private decrypt(data: Buffer): Buffer {
|
|
282
|
+
const mLen = DISK_MAGIC.length;
|
|
283
|
+
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
284
|
+
if (!this.opts.encryption) throw new Error('DiskTier: entry is encrypted but no encryption configured');
|
|
285
|
+
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
290
|
+
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
291
|
+
* Returns the buffer unchanged when no encryption instance is configured.
|
|
292
|
+
*/
|
|
293
|
+
private encryptV2(data: Buffer): Buffer {
|
|
294
|
+
if (!this.opts.encryption) return data;
|
|
295
|
+
return this.opts.encryption.encryptBuffer(data);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
300
|
+
* When an encryption instance is configured the format is the mode-aware
|
|
301
|
+
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
302
|
+
* without one the payload is raw msgpack.
|
|
303
|
+
*/
|
|
304
|
+
private decryptV2(inner: Buffer): Buffer {
|
|
305
|
+
if (!this.opts.encryption) return inner;
|
|
306
|
+
return this.opts.encryption.decryptBuffer(inner);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Spill an evicted L1 entry to disk.
|
|
313
|
+
*
|
|
314
|
+
* Returns a Promise that resolves when the file is durably written. Callers
|
|
315
|
+
* that treat the spill as fire-and-forget should do:
|
|
316
|
+
* `void disk.save(key, entry)`
|
|
317
|
+
*
|
|
318
|
+
* Implementation notes:
|
|
319
|
+
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
320
|
+
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
321
|
+
* on any external resource.
|
|
322
|
+
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
323
|
+
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
324
|
+
*/
|
|
325
|
+
async save(key: string, entry: DiskCacheEntry): Promise<void> {
|
|
326
|
+
if (this.isForbidden(key)) return;
|
|
327
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
328
|
+
|
|
329
|
+
this.ensureDir();
|
|
330
|
+
if (!this.dirReady) return;
|
|
331
|
+
this.ensureUsageCounted();
|
|
332
|
+
if (this.diskUsageBytes >= this.opts.maxBytes) return; // disk cap hit
|
|
333
|
+
|
|
334
|
+
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
335
|
+
let final: Buffer;
|
|
336
|
+
try {
|
|
337
|
+
const payload: DiskPayload = {
|
|
338
|
+
version: DISK_TIER_VERSION,
|
|
339
|
+
key,
|
|
340
|
+
entry: {
|
|
341
|
+
...entry,
|
|
342
|
+
data: entry.data instanceof Uint8Array
|
|
343
|
+
? Buffer.from(entry.data)
|
|
344
|
+
: entry.data,
|
|
345
|
+
},
|
|
346
|
+
writtenAt: Date.now(),
|
|
347
|
+
};
|
|
348
|
+
const packed = pack(payload);
|
|
349
|
+
if (packed.length > this.opts.entryMaxBytes) return;
|
|
350
|
+
let toEncrypt = packed;
|
|
351
|
+
if (this.opts.compression && this.opts.compression !== 'none' && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
352
|
+
toEncrypt = compressWithHeader(packed, this.opts.compression);
|
|
353
|
+
}
|
|
354
|
+
// V2 format: 16-byte plaintext header (magic + expiresAt) followed by the
|
|
355
|
+
// encrypted-or-raw payload. The plaintext expiresAt allows purgeNextBucket()
|
|
356
|
+
// to check expiry with a 16-byte partial read — no decrypt or unpack needed.
|
|
357
|
+
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
358
|
+
DISK_MAGIC_V2.copy(header, 0);
|
|
359
|
+
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
360
|
+
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
361
|
+
} catch (err) {
|
|
362
|
+
this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
|
|
367
|
+
const hash = this.keyToHash(key);
|
|
368
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
369
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
370
|
+
this.diskUsageBytes += final.length; // optimistic — rolled back on error
|
|
371
|
+
this.fileCount++;
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
375
|
+
await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
|
|
376
|
+
|
|
377
|
+
// Atomic rename with micro-retry loop for Windows NTFS handle release
|
|
378
|
+
try {
|
|
379
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
380
|
+
} catch (renameErr: unknown) {
|
|
381
|
+
const code = (renameErr as { code?: string })?.code;
|
|
382
|
+
if (code === 'EBUSY' || code === 'EPERM') {
|
|
383
|
+
await new Promise<void>(resolve => setTimeout(resolve, 5));
|
|
384
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
385
|
+
} else {
|
|
386
|
+
throw renameErr;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (this._db) {
|
|
391
|
+
this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length);
|
|
392
|
+
}
|
|
393
|
+
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
394
|
+
} catch (err) {
|
|
395
|
+
try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
|
|
396
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
397
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
398
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
399
|
+
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
404
|
+
load(key: string): DiskCacheEntry | null {
|
|
405
|
+
if (this.isForbidden(key)) return null;
|
|
406
|
+
this.ensureDir();
|
|
407
|
+
if (!this.dirReady) return null;
|
|
408
|
+
|
|
409
|
+
const hash = this.keyToHash(key);
|
|
410
|
+
let filePath: string | null;
|
|
411
|
+
|
|
412
|
+
if (this._db) {
|
|
413
|
+
// SQLite fast path: single B-tree lookup replaces readdirSync + filename scan.
|
|
414
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
|
|
415
|
+
if (!row) return null;
|
|
416
|
+
if (row.expires_at <= Date.now()) {
|
|
417
|
+
this._stmtDelete!.run(hash);
|
|
418
|
+
try {
|
|
419
|
+
const sz = fs.statSync(row.file_path).size;
|
|
420
|
+
fs.unlinkSync(row.file_path);
|
|
421
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
422
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
423
|
+
} catch { /* ok */ }
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
filePath = row.file_path;
|
|
427
|
+
} else {
|
|
428
|
+
filePath = this.findFilePath(hash);
|
|
429
|
+
if (!filePath) return null;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
try {
|
|
433
|
+
// V3 filename fast-path (file-only mode): expiresAt encoded in name avoids
|
|
434
|
+
// opening the file when the entry is already stale.
|
|
435
|
+
if (!this._db) {
|
|
436
|
+
const filename = path.basename(filePath);
|
|
437
|
+
if (filename.length === 77 && filename[64] === '_') {
|
|
438
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
439
|
+
if (expiresAt <= Date.now()) {
|
|
440
|
+
try {
|
|
441
|
+
const sz = fs.statSync(filePath).size;
|
|
442
|
+
fs.unlinkSync(filePath);
|
|
443
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
444
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
445
|
+
} catch { /* ok */ }
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const stat = fs.statSync(filePath);
|
|
452
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
453
|
+
fs.unlinkSync(filePath);
|
|
454
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
455
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const raw = fs.readFileSync(filePath);
|
|
460
|
+
// Delete immediately — entry will be promoted back to L1
|
|
461
|
+
try {
|
|
462
|
+
fs.unlinkSync(filePath);
|
|
463
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
464
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
465
|
+
} catch { /* ok */ }
|
|
466
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
467
|
+
|
|
468
|
+
let decrypted: Buffer;
|
|
469
|
+
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
470
|
+
// V2/V3: quick expiry guard from plaintext header before paying decrypt cost
|
|
471
|
+
const expiresAt = Number(raw.readBigUInt64LE(8));
|
|
472
|
+
if (expiresAt <= Date.now()) return null;
|
|
473
|
+
try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
|
|
474
|
+
} else {
|
|
475
|
+
// V1 / legacy unencrypted — backward compat
|
|
476
|
+
try { decrypted = this.decrypt(raw); } catch { return null; }
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
|
|
480
|
+
const payload = unpack(uncompressed) as DiskPayload;
|
|
481
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
482
|
+
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
483
|
+
|
|
484
|
+
const entry = payload.entry;
|
|
485
|
+
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
486
|
+
|
|
487
|
+
this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
488
|
+
return entry;
|
|
489
|
+
} catch (err) {
|
|
490
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
491
|
+
this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
492
|
+
return null;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Explicitly delete a key from disk (cache invalidation). */
|
|
497
|
+
delete(key: string): void {
|
|
498
|
+
const hash = this.keyToHash(key);
|
|
499
|
+
let filePath: string | null;
|
|
500
|
+
if (this._db) {
|
|
501
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
|
|
502
|
+
filePath = row?.file_path ?? null;
|
|
503
|
+
this._stmtDelete!.run(hash);
|
|
504
|
+
} else {
|
|
505
|
+
filePath = this.findFilePath(hash);
|
|
506
|
+
}
|
|
507
|
+
if (!filePath) return;
|
|
508
|
+
try {
|
|
509
|
+
const stat = fs.statSync(filePath);
|
|
510
|
+
fs.unlinkSync(filePath);
|
|
511
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
512
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
513
|
+
} catch { /* ok */ }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Purge all expired entries. Returns number deleted. */
|
|
517
|
+
purgeExpired(): number {
|
|
518
|
+
this.ensureDir();
|
|
519
|
+
if (!this.dirReady) return 0;
|
|
520
|
+
|
|
521
|
+
if (this._db) {
|
|
522
|
+
// SQLite fast path: one indexed query finds all expired rows.
|
|
523
|
+
const now = Date.now();
|
|
524
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
525
|
+
for (const row of expired) {
|
|
526
|
+
try {
|
|
527
|
+
fs.unlinkSync(row.file_path);
|
|
528
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
529
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
530
|
+
} catch { /* already gone */ }
|
|
531
|
+
}
|
|
532
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
533
|
+
return expired.length;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const now = Date.now();
|
|
537
|
+
let purged = 0;
|
|
538
|
+
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
539
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
540
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
541
|
+
const filename = path.basename(filePath);
|
|
542
|
+
|
|
543
|
+
// Clean up orphaned .tmp files older than 5 minutes
|
|
544
|
+
if (filename.endsWith('.tmp')) {
|
|
545
|
+
try {
|
|
546
|
+
const stat = fs.statSync(filePath);
|
|
547
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
548
|
+
fs.unlinkSync(filePath);
|
|
549
|
+
purged++;
|
|
550
|
+
}
|
|
551
|
+
} catch { /* already gone */ }
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
556
|
+
if (filename.length === 77 && filename[64] === '_') {
|
|
557
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
558
|
+
if (expiresAt <= now) {
|
|
559
|
+
try {
|
|
560
|
+
const sz = fs.statSync(filePath).size;
|
|
561
|
+
fs.unlinkSync(filePath);
|
|
562
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
563
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
564
|
+
purged++;
|
|
565
|
+
} catch { /* already gone */ }
|
|
566
|
+
}
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// ── V2 header fast path: read only the 16-byte plaintext header ────────
|
|
571
|
+
let fd = -1;
|
|
572
|
+
try {
|
|
573
|
+
fd = fs.openSync(filePath, 'r');
|
|
574
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
575
|
+
fs.closeSync(fd); fd = -1;
|
|
576
|
+
|
|
577
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
578
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
579
|
+
if (expiresAt <= now) {
|
|
580
|
+
try {
|
|
581
|
+
const sz = fs.statSync(filePath).size;
|
|
582
|
+
fs.unlinkSync(filePath);
|
|
583
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
584
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
585
|
+
purged++;
|
|
586
|
+
} catch { /* already gone */ }
|
|
587
|
+
}
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
|
|
592
|
+
const stat = fs.statSync(filePath);
|
|
593
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
594
|
+
fs.unlinkSync(filePath);
|
|
595
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
596
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
597
|
+
purged++;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
const raw = fs.readFileSync(filePath);
|
|
601
|
+
let dec: Buffer;
|
|
602
|
+
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; }
|
|
603
|
+
const payload = unpack(dec) as DiskPayload;
|
|
604
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
605
|
+
fs.unlinkSync(filePath);
|
|
606
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
607
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
608
|
+
purged++;
|
|
609
|
+
}
|
|
610
|
+
} catch { /* skip locked/gone */ } finally {
|
|
611
|
+
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return purged;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
619
|
+
*
|
|
620
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
621
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
622
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
623
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
624
|
+
* incremented so tests that inspect the counter continue to work.
|
|
625
|
+
*
|
|
626
|
+
* File-only fallback:
|
|
627
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
628
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
629
|
+
*
|
|
630
|
+
* Returns the number of entries deleted in this tick.
|
|
631
|
+
*/
|
|
632
|
+
purgeNextBucket(): number {
|
|
633
|
+
this.ensureDir();
|
|
634
|
+
if (!this.dirReady) return 0;
|
|
635
|
+
// Always advance the pointer — preserves observable state for tests and
|
|
636
|
+
// metrics regardless of which code path runs below.
|
|
637
|
+
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
638
|
+
|
|
639
|
+
if (this._db) {
|
|
640
|
+
const now = Date.now();
|
|
641
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
642
|
+
for (const row of expired) {
|
|
643
|
+
try {
|
|
644
|
+
fs.unlinkSync(row.file_path);
|
|
645
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
646
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
647
|
+
} catch { /* already gone */ }
|
|
648
|
+
}
|
|
649
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
650
|
+
|
|
651
|
+
// Belt-and-suspenders: scan one filesystem bucket for orphan files — files
|
|
652
|
+
// written to disk before a crash between writeFile() and the SQLite INSERT.
|
|
653
|
+
// V3 fast path: no file I/O for live entries (expiry is in the filename).
|
|
654
|
+
// Expired orphans are unlinked here; they are invisible to the SQLite query.
|
|
655
|
+
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
656
|
+
const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, '0'));
|
|
657
|
+
let orphanFiles: string[];
|
|
658
|
+
try { orphanFiles = fs.readdirSync(orphanBucketP); } catch { return expired.length; }
|
|
659
|
+
for (const file of orphanFiles) {
|
|
660
|
+
if (file.endsWith('.tmp')) {
|
|
661
|
+
const fp = path.join(orphanBucketP, file);
|
|
662
|
+
try {
|
|
663
|
+
const stat = fs.statSync(fp);
|
|
664
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
665
|
+
fs.unlinkSync(fp);
|
|
666
|
+
}
|
|
667
|
+
} catch { /* already gone */ }
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (file.length === 77 && file[64] === '_') {
|
|
672
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
673
|
+
if (expiresAt <= now) {
|
|
674
|
+
const fp = path.join(orphanBucketP, file);
|
|
675
|
+
try {
|
|
676
|
+
const sz = fs.statSync(fp).size;
|
|
677
|
+
fs.unlinkSync(fp);
|
|
678
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
679
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
680
|
+
} catch { /* already gone */ }
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return expired.length;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// ── File-only fallback: one-bucket scan ───────────────────────────────
|
|
688
|
+
const bucket = (this._nextJanitorBucket - 1 + 256) % 256; // use the bucket we just advanced past
|
|
689
|
+
const bucketHex = bucket.toString(16).padStart(2, '0');
|
|
690
|
+
const bucketPath = path.join(this.opts.dir, bucketHex);
|
|
691
|
+
let files: string[];
|
|
692
|
+
try { files = fs.readdirSync(bucketPath); } catch { return 0; }
|
|
693
|
+
const now = Date.now();
|
|
694
|
+
let purged = 0;
|
|
695
|
+
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
696
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
697
|
+
for (const file of files) {
|
|
698
|
+
// Clean up orphaned .tmp files older than 5 minutes
|
|
699
|
+
if (file.endsWith('.tmp')) {
|
|
700
|
+
const fp = path.join(bucketPath, file);
|
|
701
|
+
try {
|
|
702
|
+
const stat = fs.statSync(fp);
|
|
703
|
+
if (now - stat.mtimeMs > 5 * 60 * 1000) {
|
|
704
|
+
fs.unlinkSync(fp);
|
|
705
|
+
purged++;
|
|
706
|
+
}
|
|
707
|
+
} catch { /* already gone */ }
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
|
|
712
|
+
// Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
|
|
713
|
+
if (file.length === 77 && file[64] === '_') {
|
|
714
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
715
|
+
if (expiresAt <= now) {
|
|
716
|
+
const filePath = path.join(bucketPath, file);
|
|
717
|
+
try {
|
|
718
|
+
const sz = fs.statSync(filePath).size;
|
|
719
|
+
fs.unlinkSync(filePath);
|
|
720
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
721
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
722
|
+
purged++;
|
|
723
|
+
} catch { /* already gone */ }
|
|
724
|
+
}
|
|
725
|
+
continue; // live or just deleted — no further work
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ── V2 header path: open+read(16)+close ───────────────────────────────
|
|
729
|
+
const filePath = path.join(bucketPath, file);
|
|
730
|
+
let fd = -1;
|
|
731
|
+
try {
|
|
732
|
+
fd = fs.openSync(filePath, 'r');
|
|
733
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
734
|
+
fs.closeSync(fd); fd = -1;
|
|
735
|
+
|
|
736
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
737
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
738
|
+
if (expiresAt <= now) {
|
|
739
|
+
try {
|
|
740
|
+
const sz = fs.statSync(filePath).size;
|
|
741
|
+
fs.unlinkSync(filePath);
|
|
742
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
743
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
744
|
+
purged++;
|
|
745
|
+
} catch { /* already gone */ }
|
|
746
|
+
}
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
|
|
751
|
+
const stat = fs.statSync(filePath);
|
|
752
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
753
|
+
fs.unlinkSync(filePath);
|
|
754
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
755
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
756
|
+
purged++;
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
const raw = fs.readFileSync(filePath);
|
|
760
|
+
let dec: Buffer;
|
|
761
|
+
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; }
|
|
762
|
+
const payload = unpack(dec) as DiskPayload;
|
|
763
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
764
|
+
fs.unlinkSync(filePath);
|
|
765
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
766
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
767
|
+
purged++;
|
|
768
|
+
}
|
|
769
|
+
} catch { /* skip locked/gone */ } finally {
|
|
770
|
+
if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return purged;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
777
|
+
clear(): number {
|
|
778
|
+
this.ensureDir();
|
|
779
|
+
if (!this.dirReady) return 0;
|
|
780
|
+
let cleared = 0;
|
|
781
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
782
|
+
try {
|
|
783
|
+
const stat = fs.statSync(filePath);
|
|
784
|
+
fs.unlinkSync(filePath);
|
|
785
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
786
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
787
|
+
cleared++;
|
|
788
|
+
} catch { /* skip locked/gone */ }
|
|
789
|
+
}
|
|
790
|
+
if (this._db) {
|
|
791
|
+
this._db.exec('DELETE FROM meta');
|
|
792
|
+
this.diskUsageBytes = 0;
|
|
793
|
+
this.fileCount = 0;
|
|
794
|
+
}
|
|
795
|
+
return cleared;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
get stats(): { files: number; sizeKB: number; maxKB: number } {
|
|
799
|
+
if (this._db) {
|
|
800
|
+
// Query the index for authoritative counts — O(1) SQLite aggregate.
|
|
801
|
+
const row = this._stmtStats!.get() as { cnt: number; bytes: number };
|
|
802
|
+
this.fileCount = row.cnt;
|
|
803
|
+
this.diskUsageBytes = row.bytes;
|
|
804
|
+
}
|
|
805
|
+
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
809
|
+
get indexMode(): 'sqlite' | 'file-only' {
|
|
810
|
+
return this._db ? 'sqlite' : 'file-only';
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
814
|
+
close(): void {
|
|
815
|
+
if (this._db) {
|
|
816
|
+
try { this._db.close(); } catch { /* ok */ }
|
|
817
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
818
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|