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/README.md +32 -0
- package/dist/cache-service.d.ts +54 -1
- package/dist/cache-service.d.ts.map +1 -1
- package/dist/cache-service.js +353 -59
- package/dist/cache-service.js.map +1 -1
- package/dist/disk-tier.d.ts +74 -7
- package/dist/disk-tier.d.ts.map +1 -1
- package/dist/disk-tier.js +512 -28
- package/dist/disk-tier.js.map +1 -1
- package/dist/encryption.d.ts +2 -0
- package/dist/encryption.d.ts.map +1 -1
- package/dist/encryption.js +55 -33
- package/dist/encryption.js.map +1 -1
- package/dist/index.cjs +952 -155
- package/dist/index.d.cts +269 -8
- package/dist/smart-memory-cache.d.ts +30 -0
- package/dist/smart-memory-cache.d.ts.map +1 -1
- package/dist/smart-memory-cache.js +216 -36
- package/dist/smart-memory-cache.js.map +1 -1
- package/dist/types.d.ts +109 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -1
- package/dist/wasm/bloom-filter-wasm.js +5 -21
- package/dist/wasm/bloom-filter-wasm.js.map +1 -1
- package/package.json +11 -10
- package/src/cache-service.ts +394 -57
- package/src/disk-tier.ts +481 -27
- package/src/encryption.ts +61 -34
- package/src/smart-memory-cache.ts +213 -41
- package/src/types.ts +117 -0
- package/src/wasm/bloom-filter-wasm.ts +5 -21
package/dist/index.d.cts
CHANGED
|
@@ -96,6 +96,9 @@ interface CacheHit {
|
|
|
96
96
|
ttlMs?: number;
|
|
97
97
|
/** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
|
|
98
98
|
delta?: number;
|
|
99
|
+
/** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
|
|
100
|
+
* reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
|
|
101
|
+
fetchedAt?: number;
|
|
99
102
|
}
|
|
100
103
|
/** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
|
|
101
104
|
* legacy disk files written by older versions may have a JSON string in data) */
|
|
@@ -196,6 +199,22 @@ interface CacheMetrics {
|
|
|
196
199
|
sizeKB: number;
|
|
197
200
|
maxKB: number;
|
|
198
201
|
};
|
|
202
|
+
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
203
|
+
adaptiveTtl?: {
|
|
204
|
+
enabled: true;
|
|
205
|
+
/** Number of unique keys currently tracked in the latency ring buffers */
|
|
206
|
+
trackedKeys: number;
|
|
207
|
+
/**
|
|
208
|
+
* Top-20 slowest keys by p95 fetch latency, sorted descending.
|
|
209
|
+
* Keys are shown without the instance namespace prefix.
|
|
210
|
+
* Only keys with ≥ 5 recorded samples appear here.
|
|
211
|
+
*/
|
|
212
|
+
slowestKeys: Array<{
|
|
213
|
+
key: string;
|
|
214
|
+
p95Ms: number;
|
|
215
|
+
adaptedTtlSec: number;
|
|
216
|
+
}>;
|
|
217
|
+
};
|
|
199
218
|
}
|
|
200
219
|
/** Per-category memory limits for L1 */
|
|
201
220
|
interface CategoryLimit {
|
|
@@ -217,6 +236,12 @@ interface CacheOptions {
|
|
|
217
236
|
l1MaxBytes?: number;
|
|
218
237
|
/** Max total entries in L1. Default: 2000 */
|
|
219
238
|
l1MaxEntries?: number;
|
|
239
|
+
/**
|
|
240
|
+
* Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
|
|
241
|
+
* before the hard limit is reached. Range: 0–1. Default: 0.9.
|
|
242
|
+
* Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
|
|
243
|
+
*/
|
|
244
|
+
l1EvictionWatermark?: number;
|
|
220
245
|
/**
|
|
221
246
|
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
222
247
|
* Merged over the built-in defaults.
|
|
@@ -424,6 +449,90 @@ interface CacheOptions {
|
|
|
424
449
|
* No-op when Redis is disabled or unreachable — safe to set unconditionally.
|
|
425
450
|
*/
|
|
426
451
|
warmKeys?: string;
|
|
452
|
+
/**
|
|
453
|
+
* Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
|
|
454
|
+
* namespace prefix) and the tier that served it. Useful for per-route hit-rate
|
|
455
|
+
* metrics without waiting for the `onMetrics` interval.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
|
|
459
|
+
*/
|
|
460
|
+
onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
|
|
461
|
+
/**
|
|
462
|
+
* Called on every cache miss (after L1, disk, and L2 are all exhausted).
|
|
463
|
+
* Receives the caller-facing key (no namespace prefix).
|
|
464
|
+
*
|
|
465
|
+
* @example
|
|
466
|
+
* onMiss: (key) => cloudwatch.putMetricData({ key })
|
|
467
|
+
*/
|
|
468
|
+
onMiss?: (key: string) => void;
|
|
469
|
+
/**
|
|
470
|
+
* When `true`, every value returned from an L1 cache hit is recursively
|
|
471
|
+
* frozen with `Object.freeze()` before being handed to the caller.
|
|
472
|
+
* Any attempt to mutate the returned object throws a `TypeError` immediately,
|
|
473
|
+
* catching reference-semantic corruption bugs that would otherwise silently
|
|
474
|
+
* corrupt the cached entry.
|
|
475
|
+
*
|
|
476
|
+
* **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
|
|
477
|
+
* Deep-freezing large objects has measurable overhead per hit.
|
|
478
|
+
*
|
|
479
|
+
* @example
|
|
480
|
+
* frozen: process.env.NODE_ENV !== 'production'
|
|
481
|
+
*/
|
|
482
|
+
frozen?: boolean;
|
|
483
|
+
/**
|
|
484
|
+
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
485
|
+
* and automatically derives an optimal TTL from the p95 fetch duration:
|
|
486
|
+
*
|
|
487
|
+
* ```
|
|
488
|
+
* adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
|
|
489
|
+
* ```
|
|
490
|
+
*
|
|
491
|
+
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
492
|
+
* for a key, then the library takes over TTL management autonomously.
|
|
493
|
+
*
|
|
494
|
+
* Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
|
|
495
|
+
* their base TTL. Callers no longer need to reason about individual TTL values.
|
|
496
|
+
*
|
|
497
|
+
* Default: `false`.
|
|
498
|
+
*/
|
|
499
|
+
adaptiveTtl?: boolean;
|
|
500
|
+
/**
|
|
501
|
+
* Minimum TTL (seconds) the adaptive tuner will ever assign.
|
|
502
|
+
* Guards against extremely fast fetches producing near-zero TTLs.
|
|
503
|
+
* Default: `10`.
|
|
504
|
+
*/
|
|
505
|
+
adaptiveTtlMin?: number;
|
|
506
|
+
/**
|
|
507
|
+
* Maximum TTL (seconds) the adaptive tuner will ever assign.
|
|
508
|
+
* Guards against pathologically slow fetches producing indefinite caching.
|
|
509
|
+
* Default: `86400` (24 hours).
|
|
510
|
+
*/
|
|
511
|
+
adaptiveTtlMax?: number;
|
|
512
|
+
/**
|
|
513
|
+
* `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
|
|
514
|
+
*
|
|
515
|
+
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
516
|
+
* 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
|
|
517
|
+
* if you want the cache to absorb more upstream pressure.
|
|
518
|
+
*
|
|
519
|
+
* Default: `20`.
|
|
520
|
+
*/
|
|
521
|
+
adaptiveTtlMultiplier?: number;
|
|
522
|
+
/**
|
|
523
|
+
* Number of fetch duration samples kept per key in the ring buffer.
|
|
524
|
+
* Larger values smooth out latency spikes but use slightly more memory
|
|
525
|
+
* (~8 bytes × samples per tracked key).
|
|
526
|
+
* Default: `32`.
|
|
527
|
+
*/
|
|
528
|
+
adaptiveTtlSamples?: number;
|
|
529
|
+
/**
|
|
530
|
+
* Maximum number of distinct keys tracked by the adaptive TTL system.
|
|
531
|
+
* When the cap is reached, the oldest-tracked key is evicted from the
|
|
532
|
+
* ring-buffer store to make room for the new key.
|
|
533
|
+
* Default: `5000`.
|
|
534
|
+
*/
|
|
535
|
+
adaptiveTtlMaxKeys?: number;
|
|
427
536
|
}
|
|
428
537
|
|
|
429
538
|
/**
|
|
@@ -470,9 +579,11 @@ declare class CacheService {
|
|
|
470
579
|
private snapshotLoaded;
|
|
471
580
|
private _readyPromise;
|
|
472
581
|
private cleanupInterval;
|
|
582
|
+
private diskJanitorInterval;
|
|
473
583
|
private oomInterval;
|
|
474
584
|
private metricsInterval;
|
|
475
585
|
private _shutdownHandler;
|
|
586
|
+
private latencyTracker;
|
|
476
587
|
private readonly instanceId;
|
|
477
588
|
private readonly backplaneChannel;
|
|
478
589
|
private subClient;
|
|
@@ -510,6 +621,9 @@ declare class CacheService {
|
|
|
510
621
|
private nk;
|
|
511
622
|
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
512
623
|
private _jitterTtl;
|
|
624
|
+
/** Shared no-op span for the common case where no tracer is configured.
|
|
625
|
+
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
626
|
+
private static readonly _nullSpan;
|
|
513
627
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
514
628
|
private _startSpan;
|
|
515
629
|
private initBackplane;
|
|
@@ -544,6 +658,13 @@ declare class CacheService {
|
|
|
544
658
|
refreshAhead?: number;
|
|
545
659
|
xfetchBeta?: number;
|
|
546
660
|
notFoundTtl?: number;
|
|
661
|
+
/**
|
|
662
|
+
* Tags to associate with this cache entry when fetchFn populates it on a miss.
|
|
663
|
+
* Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
|
|
664
|
+
* via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
|
|
665
|
+
* On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
|
|
666
|
+
*/
|
|
667
|
+
tags?: string[];
|
|
547
668
|
}): Promise<T>;
|
|
548
669
|
private _revalidate;
|
|
549
670
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
@@ -551,6 +672,11 @@ declare class CacheService {
|
|
|
551
672
|
tags?: string[];
|
|
552
673
|
dependsOn?: string[];
|
|
553
674
|
}): Promise<void>;
|
|
675
|
+
/**
|
|
676
|
+
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
677
|
+
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
678
|
+
*/
|
|
679
|
+
private _registerTags;
|
|
554
680
|
/**
|
|
555
681
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
556
682
|
*
|
|
@@ -612,6 +738,27 @@ declare class CacheService {
|
|
|
612
738
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
613
739
|
*/
|
|
614
740
|
entries<T = unknown>(): Generator<[string, T]>;
|
|
741
|
+
/**
|
|
742
|
+
* High-throughput bulk scan over all live L1 entries.
|
|
743
|
+
*
|
|
744
|
+
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
745
|
+
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
746
|
+
* caller uses the `offset` parameter instead of pre-slicing.
|
|
747
|
+
*
|
|
748
|
+
* ```typescript
|
|
749
|
+
* // Zero extra string allocations — use rawKey + offset directly:
|
|
750
|
+
* cache.scan((rawKey, value, offset) => {
|
|
751
|
+
* const key = rawKey.slice(offset); // allocate only if needed
|
|
752
|
+
* sync(key, value as User);
|
|
753
|
+
* });
|
|
754
|
+
* ```
|
|
755
|
+
*
|
|
756
|
+
* @param fn Called once per live L1 entry.
|
|
757
|
+
* `rawKey` — key with namespace prefix still attached.
|
|
758
|
+
* `value` — deserialized cached value.
|
|
759
|
+
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
760
|
+
*/
|
|
761
|
+
scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
|
|
615
762
|
/**
|
|
616
763
|
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
617
764
|
* Returns `false` if the key is absent or already expired.
|
|
@@ -687,7 +834,9 @@ declare class CacheService {
|
|
|
687
834
|
* const loaded = await cache.warmFromL2('org:*');
|
|
688
835
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
689
836
|
*/
|
|
690
|
-
warmFromL2(pattern: string
|
|
837
|
+
warmFromL2(pattern: string, opts?: {
|
|
838
|
+
priority?: CachePriority;
|
|
839
|
+
}): Promise<number>;
|
|
691
840
|
/**
|
|
692
841
|
* Invalidate all keys associated with a tag.
|
|
693
842
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -697,6 +846,19 @@ declare class CacheService {
|
|
|
697
846
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
698
847
|
*/
|
|
699
848
|
invalidateTag(tag: string): Promise<void>;
|
|
849
|
+
/**
|
|
850
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
851
|
+
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
852
|
+
* reducing latency when invalidating several related tags together.
|
|
853
|
+
*
|
|
854
|
+
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
855
|
+
* synchronously before the Redis round-trip.
|
|
856
|
+
*
|
|
857
|
+
* @example
|
|
858
|
+
* // Instead of three serial round-trips:
|
|
859
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
860
|
+
*/
|
|
861
|
+
invalidateTags(tags: string[]): Promise<void>;
|
|
700
862
|
/**
|
|
701
863
|
* Measure L1 / disk / Redis latency.
|
|
702
864
|
* Useful for health checks and dashboards.
|
|
@@ -831,8 +993,10 @@ declare class CacheService {
|
|
|
831
993
|
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
832
994
|
declare class CacheEncryption {
|
|
833
995
|
private _key;
|
|
996
|
+
private _keyObj;
|
|
834
997
|
private readonly _mode;
|
|
835
998
|
private _prevKey;
|
|
999
|
+
private _prevKeyObj;
|
|
836
1000
|
private _prevMode;
|
|
837
1001
|
private readonly _ivPool;
|
|
838
1002
|
private _ivOffset;
|
|
@@ -901,6 +1065,8 @@ interface SmartMemoryCacheOptions {
|
|
|
901
1065
|
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
902
1066
|
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
903
1067
|
logger: ILogger;
|
|
1068
|
+
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
1069
|
+
evictionWatermark?: number;
|
|
904
1070
|
}
|
|
905
1071
|
declare class SmartMemoryCache {
|
|
906
1072
|
private readonly cache;
|
|
@@ -921,6 +1087,15 @@ declare class SmartMemoryCache {
|
|
|
921
1087
|
private categoryHits;
|
|
922
1088
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
923
1089
|
private _bloomDirtyCount;
|
|
1090
|
+
/**
|
|
1091
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
1092
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
1093
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
1094
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
1095
|
+
* any other code can observe the pool state.
|
|
1096
|
+
*/
|
|
1097
|
+
private readonly _evictPool;
|
|
1098
|
+
private readonly _evictGPool;
|
|
924
1099
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
925
1100
|
private recalculateStats;
|
|
926
1101
|
private getCategory;
|
|
@@ -984,6 +1159,25 @@ declare class SmartMemoryCache {
|
|
|
984
1159
|
* are silently skipped.
|
|
985
1160
|
*/
|
|
986
1161
|
liveEntries(): Generator<[string, SmartCacheEntry]>;
|
|
1162
|
+
/**
|
|
1163
|
+
* Non-generator bulk scan over all live entries.
|
|
1164
|
+
*
|
|
1165
|
+
* Faster than the generator-based iterators for bulk operations because:
|
|
1166
|
+
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
1167
|
+
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
1168
|
+
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
1169
|
+
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
1170
|
+
* monomorphic profile for this path.
|
|
1171
|
+
*
|
|
1172
|
+
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
1173
|
+
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
1174
|
+
* key, avoiding the allocation entirely for callers that don't.
|
|
1175
|
+
*
|
|
1176
|
+
* @param fn Called once per live entry.
|
|
1177
|
+
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
1178
|
+
* Pass 0 when no namespace is configured.
|
|
1179
|
+
*/
|
|
1180
|
+
scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
|
|
987
1181
|
/**
|
|
988
1182
|
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
989
1183
|
* Use this instead of liveEntries() when you only need keys.
|
|
@@ -1088,20 +1282,55 @@ declare class DiskTier {
|
|
|
1088
1282
|
private diskUsageBytes;
|
|
1089
1283
|
private usageCounted;
|
|
1090
1284
|
private fileCount;
|
|
1285
|
+
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1286
|
+
private _nextJanitorBucket;
|
|
1287
|
+
private _db;
|
|
1288
|
+
private _stmtInsert;
|
|
1289
|
+
private _stmtSelect;
|
|
1290
|
+
private _stmtDelete;
|
|
1291
|
+
private _stmtExpire;
|
|
1292
|
+
private _stmtDelExp;
|
|
1293
|
+
private _stmtStats;
|
|
1091
1294
|
constructor(opts: DiskTierOptions);
|
|
1092
1295
|
private ensureDir;
|
|
1296
|
+
/**
|
|
1297
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
1298
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
1299
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
1300
|
+
*
|
|
1301
|
+
* Schema:
|
|
1302
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
1303
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
1304
|
+
*
|
|
1305
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
1306
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
1307
|
+
*/
|
|
1308
|
+
private _initSqlite;
|
|
1093
1309
|
private ensureUsageCounted;
|
|
1094
1310
|
/**
|
|
1095
|
-
*
|
|
1311
|
+
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
1312
|
+
* Kept separate from path construction so callers can find files by prefix
|
|
1313
|
+
* without knowing which filename generation was used when the file was written.
|
|
1314
|
+
*/
|
|
1315
|
+
private keyToHash;
|
|
1316
|
+
/**
|
|
1317
|
+
* Build the write path for a NEW file (V3 generation).
|
|
1318
|
+
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
1319
|
+
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
1096
1320
|
*
|
|
1097
|
-
*
|
|
1098
|
-
*
|
|
1099
|
-
* degrades EXT4/NTFS performance at scale.
|
|
1321
|
+
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
1322
|
+
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
1100
1323
|
*
|
|
1101
|
-
*
|
|
1102
|
-
|
|
1324
|
+
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1325
|
+
*/
|
|
1326
|
+
private hashToWritePath;
|
|
1327
|
+
/**
|
|
1328
|
+
* Find the on-disk file for a key hash, handling all filename generations:
|
|
1329
|
+
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
1330
|
+
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
1331
|
+
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1103
1332
|
*/
|
|
1104
|
-
private
|
|
1333
|
+
private findFilePath;
|
|
1105
1334
|
/**
|
|
1106
1335
|
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
1107
1336
|
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
@@ -1111,6 +1340,18 @@ declare class DiskTier {
|
|
|
1111
1340
|
private isForbidden;
|
|
1112
1341
|
private encrypt;
|
|
1113
1342
|
private decrypt;
|
|
1343
|
+
/**
|
|
1344
|
+
* V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
|
|
1345
|
+
* the outer 16-byte header alongside the plaintext expiresAt).
|
|
1346
|
+
* Returns the buffer unchanged when no encryption key is configured.
|
|
1347
|
+
*/
|
|
1348
|
+
private encryptV2;
|
|
1349
|
+
/**
|
|
1350
|
+
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
1351
|
+
* When a key is configured the format is IV(12)+TAG(16)+ciphertext;
|
|
1352
|
+
* without a key the payload is raw msgpack.
|
|
1353
|
+
*/
|
|
1354
|
+
private decryptV2;
|
|
1114
1355
|
/**
|
|
1115
1356
|
* Spill an evicted L1 entry to disk.
|
|
1116
1357
|
*
|
|
@@ -1132,6 +1373,22 @@ declare class DiskTier {
|
|
|
1132
1373
|
delete(key: string): void;
|
|
1133
1374
|
/** Purge all expired entries. Returns number deleted. */
|
|
1134
1375
|
purgeExpired(): number;
|
|
1376
|
+
/**
|
|
1377
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
1378
|
+
*
|
|
1379
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
1380
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
1381
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
1382
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
1383
|
+
* incremented so tests that inspect the counter continue to work.
|
|
1384
|
+
*
|
|
1385
|
+
* File-only fallback:
|
|
1386
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
1387
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
1388
|
+
*
|
|
1389
|
+
* Returns the number of entries deleted in this tick.
|
|
1390
|
+
*/
|
|
1391
|
+
purgeNextBucket(): number;
|
|
1135
1392
|
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1136
1393
|
clear(): number;
|
|
1137
1394
|
get stats(): {
|
|
@@ -1139,6 +1396,10 @@ declare class DiskTier {
|
|
|
1139
1396
|
sizeKB: number;
|
|
1140
1397
|
maxKB: number;
|
|
1141
1398
|
};
|
|
1399
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
1400
|
+
get indexMode(): 'sqlite' | 'file-only';
|
|
1401
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1402
|
+
close(): void;
|
|
1142
1403
|
}
|
|
1143
1404
|
|
|
1144
1405
|
declare class WasmBloomFilter {
|
|
@@ -19,6 +19,8 @@ export interface SmartMemoryCacheOptions {
|
|
|
19
19
|
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
20
20
|
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
21
21
|
logger: ILogger;
|
|
22
|
+
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
23
|
+
evictionWatermark?: number;
|
|
22
24
|
}
|
|
23
25
|
export declare class SmartMemoryCache {
|
|
24
26
|
private readonly cache;
|
|
@@ -39,6 +41,15 @@ export declare class SmartMemoryCache {
|
|
|
39
41
|
private categoryHits;
|
|
40
42
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
41
43
|
private _bloomDirtyCount;
|
|
44
|
+
/**
|
|
45
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
46
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
47
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
48
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
49
|
+
* any other code can observe the pool state.
|
|
50
|
+
*/
|
|
51
|
+
private readonly _evictPool;
|
|
52
|
+
private readonly _evictGPool;
|
|
42
53
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
43
54
|
private recalculateStats;
|
|
44
55
|
private getCategory;
|
|
@@ -102,6 +113,25 @@ export declare class SmartMemoryCache {
|
|
|
102
113
|
* are silently skipped.
|
|
103
114
|
*/
|
|
104
115
|
liveEntries(): Generator<[string, SmartCacheEntry]>;
|
|
116
|
+
/**
|
|
117
|
+
* Non-generator bulk scan over all live entries.
|
|
118
|
+
*
|
|
119
|
+
* Faster than the generator-based iterators for bulk operations because:
|
|
120
|
+
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
121
|
+
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
122
|
+
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
123
|
+
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
124
|
+
* monomorphic profile for this path.
|
|
125
|
+
*
|
|
126
|
+
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
127
|
+
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
128
|
+
* key, avoiding the allocation entirely for callers that don't.
|
|
129
|
+
*
|
|
130
|
+
* @param fn Called once per live entry.
|
|
131
|
+
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
132
|
+
* Pass 0 when no namespace is configured.
|
|
133
|
+
*/
|
|
134
|
+
scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
|
|
105
135
|
/**
|
|
106
136
|
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
107
137
|
* Use this instead of liveEntries() when you only need keys.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smart-memory-cache.d.ts","sourceRoot":"","sources":["../src/smart-memory-cache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