tricache 0.5.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/README.md +18 -0
- package/dist/index.cjs +518 -112
- package/dist/index.d.cts +152 -8
- package/dist/index.d.ts +1310 -18
- package/dist/index.js +3131 -25
- package/package.json +11 -10
- package/src/cache-service.ts +197 -44
- package/src/disk-tier.ts +263 -25
- package/src/encryption.ts +14 -12
- package/src/smart-memory-cache.ts +152 -13
- package/src/types.ts +37 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
- package/dist/cache-service.d.ts +0 -366
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1494
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -83
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -324
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -88
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -371
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -178
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -753
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -428
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -99
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
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
|
|
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
|
-
*
|
|
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
|
-
*
|
|
91
|
-
*
|
|
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
|
-
*
|
|
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
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
300
|
+
const hash = this.keyToHash(key);
|
|
301
|
+
const filePath = this.findFilePath(hash);
|
|
302
|
+
if (!filePath) return null;
|
|
303
|
+
|
|
220
304
|
try {
|
|
221
|
-
|
|
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
|
-
|
|
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
|
|
360
|
+
const hash = this.keyToHash(key);
|
|
361
|
+
const filePath = this.findFilePath(hash);
|
|
362
|
+
if (!filePath) return;
|
|
255
363
|
try {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
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 <=
|
|
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');
|
|
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);
|
|
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);
|
|
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);
|
|
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);
|
|
@@ -17,7 +17,7 @@ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger,
|
|
|
17
17
|
|
|
18
18
|
// Reusable return object for get() — eliminates one heap allocation per hot read.
|
|
19
19
|
// Safe because JS is single-threaded: callers consume all fields before the next get().
|
|
20
|
-
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined };
|
|
20
|
+
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0 };
|
|
21
21
|
import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
22
22
|
|
|
23
23
|
|
|
@@ -93,15 +93,35 @@ class JsBloomFilter {
|
|
|
93
93
|
|
|
94
94
|
type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Return a bloom filter sized for `maxEntries` at a ~1 % false-positive target.
|
|
98
|
+
*
|
|
99
|
+
* The WASM filter is hardcoded at 100 K bits (k = 7), which holds ≈ 10 400 entries
|
|
100
|
+
* at 1 % FP. For larger caches the filter saturates quickly, producing high FP rates
|
|
101
|
+
* that force wasted Map.get() calls on every definite miss. When `maxEntries` exceeds
|
|
102
|
+
* the WASM filter's rated capacity, we instantiate a JS filter sized via the optimal
|
|
103
|
+
* formula: m = ⌈–n · ln p / (ln 2)²⌉ with k = round(ln 2 · m / n) clamped to [4, 10].
|
|
104
|
+
*/
|
|
105
|
+
function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
|
|
106
|
+
// Compute optimal bit-count for p = 1 % and the requested entry ceiling.
|
|
107
|
+
const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
|
|
108
|
+
const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
|
|
109
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
|
|
110
|
+
|
|
97
111
|
try {
|
|
98
112
|
const wasm = new WasmBloomFilter();
|
|
99
|
-
|
|
100
|
-
|
|
113
|
+
if (wasm.maxCapacity >= maxEntries) {
|
|
114
|
+
logger.debug('SmartMemoryCache: WASM BloomFilter active');
|
|
115
|
+
return wasm;
|
|
116
|
+
}
|
|
117
|
+
// WASM filter is undersized for this cache — fall through to right-sized JS filter.
|
|
118
|
+
logger.debug('SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter', {
|
|
119
|
+
wasmCapacity: wasm.maxCapacity, maxEntries, optimalBits,
|
|
120
|
+
});
|
|
101
121
|
} catch (err) {
|
|
102
122
|
logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
|
|
103
|
-
return new JsBloomFilter();
|
|
104
123
|
}
|
|
124
|
+
return new JsBloomFilter(optimalBits, optimalK);
|
|
105
125
|
}
|
|
106
126
|
|
|
107
127
|
// ─── Count-Min Sketch ─────────────────────────────────────────────────────────
|
|
@@ -179,6 +199,46 @@ class CountMinSketch {
|
|
|
179
199
|
}
|
|
180
200
|
}
|
|
181
201
|
|
|
202
|
+
// ─── Glob matcher ───────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Pure-string glob matcher — replaces RegExp on the deletePattern hot path.
|
|
206
|
+
* Supports only '*' wildcards (any sequence, including empty).
|
|
207
|
+
* No NFA/DFA state machine, no backtracking.
|
|
208
|
+
*
|
|
209
|
+
* Two-layer design to avoid per-key allocation in the inner loop:
|
|
210
|
+
* globMatch() — public entry point; splits the pattern once.
|
|
211
|
+
* globMatchParts() — hot inner loop; receives the pre-split segments.
|
|
212
|
+
*
|
|
213
|
+
* Algorithm:
|
|
214
|
+
* 1. First segment anchors the prefix (startsWith, O(|first|)).
|
|
215
|
+
* 2. Last segment anchors the suffix (endsWith, O(|last|)).
|
|
216
|
+
* 3. Middle segments are located left-to-right with indexOf (O(N) total, no re-scan).
|
|
217
|
+
*/
|
|
218
|
+
function globMatchParts(parts: string[], first: string, last: string, key: string): boolean {
|
|
219
|
+
if (first.length > 0 && !key.startsWith(first)) return false;
|
|
220
|
+
if (last.length > 0 && !key.endsWith(last)) return false;
|
|
221
|
+
if (first.length + last.length > key.length) return false; // anchors overlap
|
|
222
|
+
|
|
223
|
+
// Walk any middle segments left-to-right — indexOf never backtracks.
|
|
224
|
+
let pos = first.length;
|
|
225
|
+
const end = key.length - last.length;
|
|
226
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
227
|
+
const seg = parts[i];
|
|
228
|
+
if (seg.length === 0) continue; // consecutive '*' — skip
|
|
229
|
+
const idx = key.indexOf(seg, pos);
|
|
230
|
+
if (idx === -1 || idx + seg.length > end) return false;
|
|
231
|
+
pos = idx + seg.length;
|
|
232
|
+
}
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function globMatch(pattern: string, key: string): boolean {
|
|
237
|
+
const parts = pattern.split('*');
|
|
238
|
+
if (parts.length === 1) return pattern === key; // no wildcard — exact match
|
|
239
|
+
return globMatchParts(parts, parts[0], parts[parts.length - 1], key);
|
|
240
|
+
}
|
|
241
|
+
|
|
182
242
|
// ─── SmartMemoryCache ─────────────────────────────────────────────────────────
|
|
183
243
|
|
|
184
244
|
export interface SmartMemoryCacheOptions {
|
|
@@ -213,7 +273,7 @@ export class SmartMemoryCache {
|
|
|
213
273
|
|
|
214
274
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
|
|
215
275
|
this.opts = opts;
|
|
216
|
-
this.bloom = createBloomFilter(opts.logger);
|
|
276
|
+
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
217
277
|
this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
|
|
218
278
|
|
|
219
279
|
if (existing) {
|
|
@@ -274,7 +334,21 @@ export class SmartMemoryCache {
|
|
|
274
334
|
const catSz = this.categorySize.get(category) ?? 0;
|
|
275
335
|
const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
276
336
|
const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
277
|
-
if (!catOvf && !glbOvf)
|
|
337
|
+
if (!catOvf && !glbOvf) {
|
|
338
|
+
// Proactive watermark: when either the global entry count OR total byte
|
|
339
|
+
// usage crosses 90 % of its configured ceiling while there is still
|
|
340
|
+
// headroom, run one eviction pass now — during the cheap headroom path —
|
|
341
|
+
// so the hard cliffs at 100 % are rarely reached and writes at full
|
|
342
|
+
// capacity become uncommon. Both dimensions are guarded so that
|
|
343
|
+
// large-payload workloads (where maxBytes is the binding constraint)
|
|
344
|
+
// benefit equally alongside entry-count-bound workloads.
|
|
345
|
+
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
|
|
346
|
+
const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
|
|
347
|
+
if (entryWatermark || byteWatermark) {
|
|
348
|
+
this.smartEvict(category, false);
|
|
349
|
+
}
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
278
352
|
this.smartEvict(category, catOvf);
|
|
279
353
|
}
|
|
280
354
|
|
|
@@ -305,9 +379,15 @@ export class SmartMemoryCache {
|
|
|
305
379
|
// Two independent triggers — whichever fires first:
|
|
306
380
|
// 1. Phantom count (insertions of dead keys since last rebuild)
|
|
307
381
|
// 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
|
|
308
|
-
//
|
|
309
|
-
//
|
|
310
|
-
|
|
382
|
+
//
|
|
383
|
+
// Dirty-count cap: bloom.maxCapacity grows proportionally with filter size, but
|
|
384
|
+
// we want rebuild frequency to stay proportional to cache ENTRY count, not bit
|
|
385
|
+
// count. Without the cap a JS filter sized for 50 K entries allows ~12 500 ghost
|
|
386
|
+
// entries before a rebuild — 5× longer than the old WASM filter, which let phantom
|
|
387
|
+
// bits accumulate and raised the measured FP rate. The cap restores the original
|
|
388
|
+
// rebuild cadence: rebuild after ~5 % of maxEntries are deleted, with a 256 floor.
|
|
389
|
+
const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
|
|
390
|
+
if (this._bloomDirtyCount > dirtyThreshold ||
|
|
311
391
|
this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
|
|
312
392
|
this.bloom.rebuild(this.cache.keys());
|
|
313
393
|
this._bloomDirtyCount = 0;
|
|
@@ -400,6 +480,7 @@ export class SmartMemoryCache {
|
|
|
400
480
|
_hit.expiresAt = entry.expiresAt;
|
|
401
481
|
_hit.ttlMs = entry.ttlMs;
|
|
402
482
|
_hit.delta = entry.delta;
|
|
483
|
+
_hit.fetchedAt = now;
|
|
403
484
|
return _hit;
|
|
404
485
|
}
|
|
405
486
|
|
|
@@ -438,7 +519,9 @@ export class SmartMemoryCache {
|
|
|
438
519
|
|
|
439
520
|
const now = Date.now();
|
|
440
521
|
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
441
|
-
|
|
522
|
+
// Only add new keys to the bloom — overwrites already have their bits set.
|
|
523
|
+
// Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
|
|
524
|
+
if (!existingEntry) this.bloom.add(key);
|
|
442
525
|
this.maybeRebuildBloom();
|
|
443
526
|
this.totalSize += size;
|
|
444
527
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
@@ -456,9 +539,40 @@ export class SmartMemoryCache {
|
|
|
456
539
|
|
|
457
540
|
private keysMatchingPattern(pattern: string): string[] {
|
|
458
541
|
if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
|
|
459
|
-
|
|
542
|
+
|
|
543
|
+
// Fast path: trailing-only wildcard whose prefix exactly matches a configured
|
|
544
|
+
// category (e.g. deletePattern('user:*') when 'user:' is a category).
|
|
545
|
+
// categoryKeys already indexes all live keys per category prefix in O(1),
|
|
546
|
+
// so we skip the O(N) Map scan and regex evaluation entirely.
|
|
547
|
+
// We snapshot via Array.from() before returning so _delete() mutations to
|
|
548
|
+
// the Set during the subsequent iteration are safe.
|
|
549
|
+
if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
|
|
550
|
+
const prefix = pattern.slice(0, -1);
|
|
551
|
+
const catKeys = this.categoryKeys.get(prefix);
|
|
552
|
+
if (catKeys !== undefined) return Array.from(catKeys);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// Fast path: exactly one '*' that is NOT at the end (e.g. "user:*:profile").
|
|
556
|
+
// AOT detection lets us avoid globMatchParts dispatch and its empty middle-
|
|
557
|
+
// segment loop — keys only need startsWith + endsWith + length checks inline.
|
|
558
|
+
const firstStar = pattern.indexOf('*');
|
|
559
|
+
if (firstStar === pattern.lastIndexOf('*')) {
|
|
560
|
+
const prefix = pattern.slice(0, firstStar);
|
|
561
|
+
const suffix = pattern.slice(firstStar + 1); // empty when star is last char
|
|
562
|
+
const minLen = prefix.length + suffix.length;
|
|
563
|
+
const out: string[] = [];
|
|
564
|
+
for (const k of this.cache.keys()) {
|
|
565
|
+
if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out.push(k);
|
|
566
|
+
}
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// General case: multiple '*' wildcards — split once, then scan.
|
|
571
|
+
const parts = pattern.split('*');
|
|
572
|
+
const first = parts[0];
|
|
573
|
+
const last = parts[parts.length - 1];
|
|
460
574
|
const out: string[] = [];
|
|
461
|
-
for (const k of this.cache.keys()) if (
|
|
575
|
+
for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
|
|
462
576
|
return out;
|
|
463
577
|
}
|
|
464
578
|
|
|
@@ -634,6 +748,31 @@ export class SmartMemoryCache {
|
|
|
634
748
|
}
|
|
635
749
|
}
|
|
636
750
|
|
|
751
|
+
/**
|
|
752
|
+
* Non-generator bulk scan over all live entries.
|
|
753
|
+
*
|
|
754
|
+
* Faster than the generator-based iterators for bulk operations because:
|
|
755
|
+
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
756
|
+
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
757
|
+
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
758
|
+
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
759
|
+
* monomorphic profile for this path.
|
|
760
|
+
*
|
|
761
|
+
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
762
|
+
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
763
|
+
* key, avoiding the allocation entirely for callers that don't.
|
|
764
|
+
*
|
|
765
|
+
* @param fn Called once per live entry.
|
|
766
|
+
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
767
|
+
* Pass 0 when no namespace is configured.
|
|
768
|
+
*/
|
|
769
|
+
scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void {
|
|
770
|
+
const now = Date.now();
|
|
771
|
+
for (const [key, entry] of this.cache) {
|
|
772
|
+
if (entry.expiresAt > now) fn(key, entry, prefixLen);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
637
776
|
/**
|
|
638
777
|
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
639
778
|
* Use this instead of liveEntries() when you only need keys.
|