tricache 0.4.0 → 0.5.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/src/disk-tier.ts CHANGED
@@ -24,7 +24,17 @@ import { DiskCacheEntry, ILogger } from './types.js';
24
24
  const AES_ALGO = 'aes-256-gcm' as const;
25
25
  const IV_BYTES = 12;
26
26
  const TAG_BYTES = 16;
27
- const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
27
+ const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
28
+ /**
29
+ * V2 file format — expiresAt stored in plaintext outside the ciphertext so the
30
+ * janitor can check expiry with a 16-byte header read rather than a full
31
+ * decrypt + unpack. Layout (bytes):
32
+ * 0–7 DISK_MAGIC_V2 ("DTIERV2\0")
33
+ * 8–15 expiresAt, uint64 LE (ms since epoch, outside encryption)
34
+ * 16+ encryptV2(msgpack(DiskPayload)) — IV+TAG+ct if key set, else raw msgpack
35
+ */
36
+ const DISK_MAGIC_V2 = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x32, 0x00]); // "DTIERV2\0"
37
+ const V2_HEADER_LEN = 16; // magic(8) + expiresAt(8)
28
38
 
29
39
  interface DiskPayload {
30
40
  version: number;
@@ -52,6 +62,8 @@ export class DiskTier {
52
62
  private diskUsageBytes = 0;
53
63
  private usageCounted = false;
54
64
  private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
65
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
66
+ private _nextJanitorBucket = 0;
55
67
 
56
68
  constructor(opts: DiskTierOptions) {
57
69
  this.opts = opts;
@@ -85,18 +97,49 @@ export class DiskTier {
85
97
  }
86
98
 
87
99
  /**
88
- * Map a cache key to its on-disk path.
100
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
101
+ * Kept separate from path construction so callers can find files by prefix
102
+ * without knowing which filename generation was used when the file was written.
103
+ */
104
+ private keyToHash(key: string): string {
105
+ return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
106
+ }
107
+
108
+ /**
109
+ * Build the write path for a NEW file (V3 generation).
110
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
111
+ * with zero file I/O — after readdirSync() it only needs a string parse.
89
112
  *
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.
113
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
114
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
93
115
  *
94
- * key → SHA-256 hex e3b0c442...
95
- * path → {dir}/e3/e3b0c442...
116
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
96
117
  */
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);
118
+ private hashToWritePath(hash: string, expiresAt: number): string {
119
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, '0')}`);
120
+ }
121
+
122
+ /**
123
+ * Find the on-disk file for a key hash, handling all filename generations:
124
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
125
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
126
+ * Returns null when the bucket dir does not exist or the key is absent.
127
+ */
128
+ private findFilePath(hash: string): string | null {
129
+ const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
130
+ let files: string[];
131
+ try { files = fs.readdirSync(bucketPath); } catch { return null; }
132
+ // Return the lexicographically largest match: V3 filenames are
133
+ // "{hash}_{expiresHex12}", so lex-max = largest timestamp = newest entry.
134
+ // If the same key was evicted to disk twice (different TTLs → different names),
135
+ // this ensures we always serve and delete the freshest copy; the janitor cleans
136
+ // up the stale one when its encoded timestamp expires.
137
+ let match: string | undefined;
138
+ for (const f of files) {
139
+ if ((f === hash || f.startsWith(hash + '_')) && (!match || f > match)) match = f;
140
+ }
141
+ if (!match) return null;
142
+ return path.join(bucketPath, match);
100
143
  }
101
144
 
102
145
  /**
@@ -147,6 +190,37 @@ export class DiskTier {
147
190
  return Buffer.concat([d.update(ct), d.final()]);
148
191
  }
149
192
 
193
+ /**
194
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
195
+ * the outer 16-byte header alongside the plaintext expiresAt).
196
+ * Returns the buffer unchanged when no encryption key is configured.
197
+ */
198
+ private encryptV2(data: Buffer): Buffer {
199
+ const key = this.opts.encryptionKey;
200
+ if (!key) return data;
201
+ const iv = crypto.randomBytes(IV_BYTES);
202
+ const c = crypto.createCipheriv(AES_ALGO, key, iv);
203
+ const enc = Buffer.concat([c.update(data), c.final()]);
204
+ const tag = c.getAuthTag();
205
+ return Buffer.concat([iv, tag, enc]);
206
+ }
207
+
208
+ /**
209
+ * V2 decryption — inner payload after stripping the 16-byte header.
210
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
211
+ * without a key the payload is raw msgpack.
212
+ */
213
+ private decryptV2(inner: Buffer): Buffer {
214
+ const key = this.opts.encryptionKey;
215
+ if (!key) return inner;
216
+ const iv = inner.subarray(0, IV_BYTES);
217
+ const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
218
+ const ct = inner.subarray(IV_BYTES + TAG_BYTES);
219
+ const d = crypto.createDecipheriv(AES_ALGO, key, iv);
220
+ d.setAuthTag(tag);
221
+ return Buffer.concat([d.update(ct), d.final()]);
222
+ }
223
+
150
224
  // ── Public API ────────────────────────────────────────────────────────────
151
225
 
152
226
  /**
@@ -188,14 +262,21 @@ export class DiskTier {
188
262
  };
189
263
  const packed = pack(payload);
190
264
  if (packed.length > this.opts.entryMaxBytes) return;
191
- final = this.encrypt(packed);
265
+ // V2 format: 16-byte plaintext header (magic + expiresAt) followed by the
266
+ // encrypted-or-raw payload. The plaintext expiresAt allows purgeNextBucket()
267
+ // to check expiry with a 16-byte partial read — no decrypt or unpack needed.
268
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
269
+ DISK_MAGIC_V2.copy(header, 0);
270
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
271
+ final = Buffer.concat([header, this.encryptV2(packed)]);
192
272
  } catch (err) {
193
273
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
194
274
  return;
195
275
  }
196
276
 
197
- // ── Async phase: mkdir + write (does not block the event loop) ────────
198
- const filePath = this.keyToPath(key);
277
+ // ── Async phase: mkdir + write (does not block the event loop) ────
278
+ const hash = this.keyToHash(key);
279
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
199
280
  this.diskUsageBytes += final.length; // optimistic — rolled back on error
200
281
  this.fileCount++;
201
282
 
@@ -216,9 +297,26 @@ export class DiskTier {
216
297
  this.ensureDir();
217
298
  if (!this.dirReady) return null;
218
299
 
219
- const filePath = this.keyToPath(key);
300
+ const hash = this.keyToHash(key);
301
+ const filePath = this.findFilePath(hash);
302
+ if (!filePath) return null;
303
+
220
304
  try {
221
- if (!fs.existsSync(filePath)) return null;
305
+ // V3 fast path: expiresAt is in the filename — avoid even opening the file
306
+ // when the entry is already known to be stale.
307
+ const filename = path.basename(filePath);
308
+ if (filename.length === 77 && filename[64] === '_') {
309
+ const expiresAt = parseInt(filename.slice(65), 16);
310
+ if (expiresAt <= Date.now()) {
311
+ try {
312
+ const sz = fs.statSync(filePath).size;
313
+ fs.unlinkSync(filePath);
314
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
315
+ this.fileCount = Math.max(0, this.fileCount - 1);
316
+ } catch { /* ok */ }
317
+ return null;
318
+ }
319
+ }
222
320
 
223
321
  const stat = fs.statSync(filePath);
224
322
  if (stat.size > this.opts.entryMaxBytes) {
@@ -232,7 +330,15 @@ export class DiskTier {
232
330
  try { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); } catch { /* ok */ }
233
331
 
234
332
  let decrypted: Buffer;
235
- try { decrypted = this.decrypt(raw); } catch { return null; }
333
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
334
+ // V2/V3: quick expiry guard from plaintext header before paying decrypt cost
335
+ const expiresAt = Number(raw.readBigUInt64LE(8));
336
+ if (expiresAt <= Date.now()) return null;
337
+ try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
338
+ } else {
339
+ // V1 / legacy unencrypted — backward compat
340
+ try { decrypted = this.decrypt(raw); } catch { return null; }
341
+ }
236
342
 
237
343
  const payload = unpack(decrypted) as DiskPayload;
238
344
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
@@ -251,14 +357,14 @@ export class DiskTier {
251
357
 
252
358
  /** Explicitly delete a key from disk (cache invalidation). */
253
359
  delete(key: string): void {
254
- const filePath = this.keyToPath(key);
360
+ const hash = this.keyToHash(key);
361
+ const filePath = this.findFilePath(hash);
362
+ if (!filePath) return;
255
363
  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
- }
364
+ const stat = fs.statSync(filePath);
365
+ fs.unlinkSync(filePath);
366
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
367
+ this.fileCount = Math.max(0, this.fileCount - 1);
262
368
  } catch { /* ok */ }
263
369
  }
264
370
 
@@ -266,9 +372,50 @@ export class DiskTier {
266
372
  purgeExpired(): number {
267
373
  this.ensureDir();
268
374
  if (!this.dirReady) return 0;
375
+ const now = Date.now();
269
376
  let purged = 0;
377
+ // One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
378
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
270
379
  for (const filePath of this.walkCacheFiles()) {
380
+ const filename = path.basename(filePath);
381
+
382
+ // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
383
+ if (filename.length === 77 && filename[64] === '_') {
384
+ const expiresAt = parseInt(filename.slice(65), 16);
385
+ if (expiresAt <= now) {
386
+ try {
387
+ const sz = fs.statSync(filePath).size;
388
+ fs.unlinkSync(filePath);
389
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
390
+ this.fileCount = Math.max(0, this.fileCount - 1);
391
+ purged++;
392
+ } catch { /* already gone */ }
393
+ }
394
+ continue;
395
+ }
396
+
397
+ // ── V2 header fast path: read only the 16-byte plaintext header ────────
398
+ let fd = -1;
271
399
  try {
400
+ fd = fs.openSync(filePath, 'r');
401
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
402
+ fs.closeSync(fd); fd = -1;
403
+
404
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
405
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
406
+ if (expiresAt <= now) {
407
+ try {
408
+ const sz = fs.statSync(filePath).size;
409
+ fs.unlinkSync(filePath);
410
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
411
+ this.fileCount = Math.max(0, this.fileCount - 1);
412
+ purged++;
413
+ } catch { /* already gone */ }
414
+ }
415
+ continue;
416
+ }
417
+
418
+ // ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
272
419
  const stat = fs.statSync(filePath);
273
420
  if (stat.size > this.opts.entryMaxBytes) {
274
421
  fs.unlinkSync(filePath);
@@ -281,13 +428,104 @@ export class DiskTier {
281
428
  let dec: Buffer;
282
429
  try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
283
430
  const payload = unpack(dec) as DiskPayload;
284
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
431
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
285
432
  fs.unlinkSync(filePath);
286
433
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
287
434
  this.fileCount = Math.max(0, this.fileCount - 1);
288
435
  purged++;
289
436
  }
290
- } catch { /* skip locked/gone */ }
437
+ } catch { /* skip locked/gone */ } finally {
438
+ if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
439
+ }
440
+ }
441
+ return purged;
442
+ }
443
+
444
+ /**
445
+ * Purge expired entries from exactly one of the 256 subdirectory buckets, then
446
+ * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
447
+ * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
448
+ * of landing as one large synchronous burst every 5 minutes.
449
+ *
450
+ * V3 files: expiresAt is encoded in the filename — live entries skip with zero
451
+ * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
452
+ *
453
+ * Returns the number of entries deleted in this tick.
454
+ */
455
+ purgeNextBucket(): number {
456
+ this.ensureDir();
457
+ if (!this.dirReady) return 0;
458
+ const bucket = this._nextJanitorBucket.toString(16).padStart(2, '0');
459
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
460
+ const bucketPath = path.join(this.opts.dir, bucket);
461
+ let files: string[];
462
+ try { files = fs.readdirSync(bucketPath); } catch { return 0; }
463
+ const now = Date.now();
464
+ let purged = 0;
465
+ // One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
466
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
467
+ for (const file of files) {
468
+ // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
469
+ // Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
470
+ if (file.length === 77 && file[64] === '_') {
471
+ const expiresAt = parseInt(file.slice(65), 16);
472
+ if (expiresAt <= now) {
473
+ const filePath = path.join(bucketPath, file);
474
+ try {
475
+ const sz = fs.statSync(filePath).size;
476
+ fs.unlinkSync(filePath);
477
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
478
+ this.fileCount = Math.max(0, this.fileCount - 1);
479
+ purged++;
480
+ } catch { /* already gone */ }
481
+ }
482
+ continue; // live or just deleted — no further work
483
+ }
484
+
485
+ // ── V2 header path: open+read(16)+close ───────────────────────────────
486
+ const filePath = path.join(bucketPath, file);
487
+ let fd = -1;
488
+ try {
489
+ fd = fs.openSync(filePath, 'r');
490
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
491
+ fs.closeSync(fd); fd = -1;
492
+
493
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
494
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
495
+ if (expiresAt <= now) {
496
+ try {
497
+ const sz = fs.statSync(filePath).size;
498
+ fs.unlinkSync(filePath);
499
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
500
+ this.fileCount = Math.max(0, this.fileCount - 1);
501
+ purged++;
502
+ } catch { /* already gone */ }
503
+ }
504
+ continue;
505
+ }
506
+
507
+ // ── Legacy path: V1 encrypted or pre-magic unencrypted ────────────
508
+ const stat = fs.statSync(filePath);
509
+ if (stat.size > this.opts.entryMaxBytes) {
510
+ fs.unlinkSync(filePath);
511
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
512
+ this.fileCount = Math.max(0, this.fileCount - 1);
513
+ purged++;
514
+ continue;
515
+ }
516
+ const raw = fs.readFileSync(filePath);
517
+ let dec: Buffer;
518
+ try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
519
+ const payload = unpack(dec) as DiskPayload;
520
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
521
+ fs.unlinkSync(filePath);
522
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
523
+ this.fileCount = Math.max(0, this.fileCount - 1);
524
+ purged++;
525
+ }
526
+ } catch { /* skip locked/gone */ } finally {
527
+ if (fd >= 0) try { fs.closeSync(fd); } catch { /* ok */ }
528
+ }
291
529
  }
292
530
  return purged;
293
531
  }
package/src/encryption.ts CHANGED
@@ -220,11 +220,12 @@ export class CacheEncryption {
220
220
  if (this._mode === 'aes-128-ctr') {
221
221
  const iv = this._nextCtrIV();
222
222
  const c = createCipheriv('aes-128-ctr', this._key, iv);
223
- const enc = c.update(plaintext, 'utf8'); // CTR: stream cipher — final() emits no bytes
224
- c.final();
225
- const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length);
223
+ const enc = c.update(plaintext, 'utf8');
224
+ const fin = c.final(); // CTR: almost always empty — captured defensively
225
+ const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
226
226
  iv.copy(out, 0);
227
227
  enc.copy(out, CTR_IV_BYTES);
228
+ if (fin.length > 0) fin.copy(out, CTR_IV_BYTES + enc.length);
228
229
  return PREFIX_CTR + out.toString('base64');
229
230
  }
230
231
  const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
@@ -276,9 +277,9 @@ export class CacheEncryption {
276
277
  const iv = combined.subarray(0, CTR_IV_BYTES);
277
278
  const ct = combined.subarray(CTR_IV_BYTES);
278
279
  const d = createDecipheriv('aes-128-ctr', key, iv);
279
- const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
280
- d.final();
281
- return plain.toString('utf8');
280
+ const plain = d.update(ct);
281
+ const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
282
+ return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
282
283
  }
283
284
  const is256 = value.startsWith(PREFIX_256);
284
285
  const is128 = value.startsWith(PREFIX_128);
@@ -314,13 +315,14 @@ export class CacheEncryption {
314
315
  if (this._mode === 'aes-128-ctr') {
315
316
  const iv = this._nextCtrIV();
316
317
  const c = createCipheriv('aes-128-ctr', this._key, iv);
317
- const enc = c.update(data); // CTR: stream cipher — final() emits no bytes
318
- c.final();
318
+ const enc = c.update(data);
319
+ const fin = c.final(); // CTR: almost always empty — captured defensively
319
320
  // Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
320
- const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length);
321
+ const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length + fin.length);
321
322
  MAGIC_CTR.copy(out, 0);
322
323
  iv.copy(out, MAGIC_LEN);
323
324
  enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
325
+ if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
324
326
  return out;
325
327
  }
326
328
  const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
@@ -375,9 +377,9 @@ export class CacheEncryption {
375
377
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
376
378
  const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
377
379
  const d = createDecipheriv('aes-128-ctr', key, iv);
378
- const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
379
- d.final();
380
- return plain;
380
+ const plain = d.update(ct);
381
+ const fin = d.final(); // CTR: almost always empty — captured defensively
382
+ return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
381
383
  }
382
384
  const is256 = magic.equals(MAGIC_256);
383
385
  const is128 = magic.equals(MAGIC_128);