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