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/dist/disk-tier.js CHANGED
@@ -16,12 +16,29 @@
16
16
  import fs from 'fs';
17
17
  import path from 'path';
18
18
  import crypto from 'crypto';
19
+ import { createRequire } from 'module';
19
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 */ }
20
27
  // ── Encryption (self-contained to avoid circular import) ─────────────────────
21
28
  const AES_ALGO = 'aes-256-gcm';
22
29
  const IV_BYTES = 12;
23
30
  const TAG_BYTES = 16;
24
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)
25
42
  const DISK_TIER_VERSION = 1;
26
43
  export class DiskTier {
27
44
  opts;
@@ -29,6 +46,16 @@ export class DiskTier {
29
46
  diskUsageBytes = 0;
30
47
  usageCounted = false;
31
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)
32
59
  constructor(opts) {
33
60
  this.opts = opts;
34
61
  }
@@ -39,15 +66,70 @@ export class DiskTier {
39
66
  try {
40
67
  fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
41
68
  this.dirReady = true;
69
+ this._initSqlite();
42
70
  }
43
71
  catch (err) {
44
72
  this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: err.message });
45
73
  }
46
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
+ }
47
126
  ensureUsageCounted() {
48
127
  if (this.usageCounted)
49
128
  return;
50
129
  this.usageCounted = true;
130
+ // SQLite path: counts were already seeded in _initSqlite() — nothing more to do.
131
+ if (this._db)
132
+ return;
51
133
  try {
52
134
  this.ensureDir();
53
135
  let total = 0;
@@ -67,18 +149,54 @@ export class DiskTier {
67
149
  }
68
150
  }
69
151
  /**
70
- * Map a cache key to its on-disk path.
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.
71
163
  *
72
- * Files are sharded into two-character hex prefix subdirectories to avoid
73
- * putting thousands of flat files into a single directory node — which
74
- * degrades EXT4/NTFS performance at scale.
164
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
165
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
75
166
  *
76
- * key → SHA-256 hex e3b0c442...
77
- * path → {dir}/e3/e3b0c442...
167
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
78
168
  */
79
- keyToPath(key) {
80
- const hash = crypto.createHash('sha256').update(key, 'utf8').digest('hex');
81
- return path.join(this.opts.dir, hash.slice(0, 2), hash);
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);
82
200
  }
83
201
  /**
84
202
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -134,6 +252,37 @@ export class DiskTier {
134
252
  d.setAuthTag(tag);
135
253
  return Buffer.concat([d.update(ct), d.final()]);
136
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
+ }
137
286
  // ── Public API ────────────────────────────────────────────────────────────
138
287
  /**
139
288
  * Spill an evicted L1 entry to disk.
@@ -177,24 +326,39 @@ export class DiskTier {
177
326
  const packed = pack(payload);
178
327
  if (packed.length > this.opts.entryMaxBytes)
179
328
  return;
180
- final = this.encrypt(packed);
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)]);
181
336
  }
182
337
  catch (err) {
183
338
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: err.message });
184
339
  return;
185
340
  }
186
- // ── Async phase: mkdir + write (does not block the event loop) ────────
187
- const filePath = this.keyToPath(key);
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);
188
344
  this.diskUsageBytes += final.length; // optimistic — rolled back on error
189
345
  this.fileCount++;
190
346
  try {
191
347
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
192
348
  await fs.promises.writeFile(filePath, final, { mode: 0o600 });
349
+ if (this._db) {
350
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
351
+ }
193
352
  this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
194
353
  }
195
354
  catch (err) {
196
355
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
197
356
  this.fileCount = Math.max(0, this.fileCount - 1);
357
+ if (this._db)
358
+ try {
359
+ this._stmtDelete.run(hash);
360
+ }
361
+ catch { /* ok */ }
198
362
  this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: err.message });
199
363
  }
200
364
  }
@@ -205,14 +369,56 @@ export class DiskTier {
205
369
  this.ensureDir();
206
370
  if (!this.dirReady)
207
371
  return null;
208
- const filePath = this.keyToPath(key);
209
- try {
210
- if (!fs.existsSync(filePath))
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)
211
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
+ }
212
416
  const stat = fs.statSync(filePath);
213
417
  if (stat.size > this.opts.entryMaxBytes) {
214
418
  fs.unlinkSync(filePath);
215
419
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
420
+ if (this._db)
421
+ this._stmtDelete.run(hash);
216
422
  return null;
217
423
  }
218
424
  const raw = fs.readFileSync(filePath);
@@ -223,12 +429,29 @@ export class DiskTier {
223
429
  this.fileCount = Math.max(0, this.fileCount - 1);
224
430
  }
225
431
  catch { /* ok */ }
432
+ if (this._db)
433
+ this._stmtDelete.run(hash);
226
434
  let decrypted;
227
- try {
228
- decrypted = this.decrypt(raw);
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
+ }
229
446
  }
230
- catch {
231
- return null;
447
+ else {
448
+ // V1 / legacy unencrypted — backward compat
449
+ try {
450
+ decrypted = this.decrypt(raw);
451
+ }
452
+ catch {
453
+ return null;
454
+ }
232
455
  }
233
456
  const payload = unpack(decrypted);
234
457
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key)
@@ -242,20 +465,34 @@ export class DiskTier {
242
465
  return entry;
243
466
  }
244
467
  catch (err) {
468
+ if (this._db)
469
+ try {
470
+ this._stmtDelete.run(hash);
471
+ }
472
+ catch { /* ok */ }
245
473
  this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: err.message });
246
474
  return null;
247
475
  }
248
476
  }
249
477
  /** Explicitly delete a key from disk (cache invalidation). */
250
478
  delete(key) {
251
- const filePath = this.keyToPath(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;
252
491
  try {
253
- if (fs.existsSync(filePath)) {
254
- const stat = fs.statSync(filePath);
255
- fs.unlinkSync(filePath);
256
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
257
- this.fileCount = Math.max(0, this.fileCount - 1);
258
- }
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);
259
496
  }
260
497
  catch { /* ok */ }
261
498
  }
@@ -264,9 +501,65 @@ export class DiskTier {
264
501
  this.ensureDir();
265
502
  if (!this.dirReady)
266
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();
267
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);
268
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;
269
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 ────────────
270
563
  const stat = fs.statSync(filePath);
271
564
  if (stat.size > this.opts.entryMaxBytes) {
272
565
  fs.unlinkSync(filePath);
@@ -287,7 +580,7 @@ export class DiskTier {
287
580
  continue;
288
581
  }
289
582
  const payload = unpack(dec);
290
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
583
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
291
584
  fs.unlinkSync(filePath);
292
585
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
293
586
  this.fileCount = Math.max(0, this.fileCount - 1);
@@ -295,6 +588,172 @@ export class DiskTier {
295
588
  }
296
589
  }
297
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
+ }
298
757
  }
299
758
  return purged;
300
759
  }
@@ -314,11 +773,36 @@ export class DiskTier {
314
773
  }
315
774
  catch { /* skip locked/gone */ }
316
775
  }
776
+ if (this._db) {
777
+ this._db.exec('DELETE FROM meta');
778
+ this.diskUsageBytes = 0;
779
+ this.fileCount = 0;
780
+ }
317
781
  return cleared;
318
782
  }
319
783
  get stats() {
320
- // fileCount is maintained in-memory — O(1), no filesystem scan.
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
+ }
321
790
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
322
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
+ }
323
807
  }
324
808
  //# sourceMappingURL=disk-tier.js.map