tricache 0.5.0 → 0.6.0

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