tricache 0.5.1 → 0.6.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 +133 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +938 -217
- package/dist/index.d.cts +248 -6
- package/dist/index.d.ts +248 -6
- package/dist/index.js +845 -452
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +6 -6
- package/src/cache-service.ts +510 -109
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +105 -31
- package/src/types.ts +179 -1
- package/src/worker-pool.ts +190 -0
package/dist/index.d.cts
CHANGED
|
@@ -198,6 +198,23 @@ interface CacheMetrics {
|
|
|
198
198
|
files: number;
|
|
199
199
|
sizeKB: number;
|
|
200
200
|
maxKB: number;
|
|
201
|
+
disabled: boolean;
|
|
202
|
+
};
|
|
203
|
+
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
204
|
+
adaptiveTtl?: {
|
|
205
|
+
enabled: true;
|
|
206
|
+
/** Number of unique keys currently tracked in the latency ring buffers */
|
|
207
|
+
trackedKeys: number;
|
|
208
|
+
/**
|
|
209
|
+
* Top-20 slowest keys by p95 fetch latency, sorted descending.
|
|
210
|
+
* Keys are shown without the instance namespace prefix.
|
|
211
|
+
* Only keys with ≥ 5 recorded samples appear here.
|
|
212
|
+
*/
|
|
213
|
+
slowestKeys: Array<{
|
|
214
|
+
key: string;
|
|
215
|
+
p95Ms: number;
|
|
216
|
+
adaptedTtlSec: number;
|
|
217
|
+
}>;
|
|
201
218
|
};
|
|
202
219
|
}
|
|
203
220
|
/** Per-category memory limits for L1 */
|
|
@@ -220,6 +237,12 @@ interface CacheOptions {
|
|
|
220
237
|
l1MaxBytes?: number;
|
|
221
238
|
/** Max total entries in L1. Default: 2000 */
|
|
222
239
|
l1MaxEntries?: number;
|
|
240
|
+
/**
|
|
241
|
+
* Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
|
|
242
|
+
* before the hard limit is reached. Range: 0–1. Default: 0.9.
|
|
243
|
+
* Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
|
|
244
|
+
*/
|
|
245
|
+
l1EvictionWatermark?: number;
|
|
223
246
|
/**
|
|
224
247
|
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
225
248
|
* Merged over the built-in defaults.
|
|
@@ -458,6 +481,154 @@ interface CacheOptions {
|
|
|
458
481
|
* frozen: process.env.NODE_ENV !== 'production'
|
|
459
482
|
*/
|
|
460
483
|
frozen?: boolean;
|
|
484
|
+
/**
|
|
485
|
+
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
486
|
+
* and automatically derives an optimal TTL from the p95 fetch duration:
|
|
487
|
+
*
|
|
488
|
+
* ```
|
|
489
|
+
* adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
|
|
490
|
+
* ```
|
|
491
|
+
*
|
|
492
|
+
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
493
|
+
* for a key, then the library takes over TTL management autonomously.
|
|
494
|
+
*
|
|
495
|
+
* Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
|
|
496
|
+
* their base TTL. Callers no longer need to reason about individual TTL values.
|
|
497
|
+
*
|
|
498
|
+
* Default: `false`.
|
|
499
|
+
*/
|
|
500
|
+
adaptiveTtl?: boolean;
|
|
501
|
+
/**
|
|
502
|
+
* Minimum TTL (seconds) the adaptive tuner will ever assign.
|
|
503
|
+
* Guards against extremely fast fetches producing near-zero TTLs.
|
|
504
|
+
* Default: `10`.
|
|
505
|
+
*/
|
|
506
|
+
adaptiveTtlMin?: number;
|
|
507
|
+
/**
|
|
508
|
+
* Maximum TTL (seconds) the adaptive tuner will ever assign.
|
|
509
|
+
* Guards against pathologically slow fetches producing indefinite caching.
|
|
510
|
+
* Default: `86400` (24 hours).
|
|
511
|
+
*/
|
|
512
|
+
adaptiveTtlMax?: number;
|
|
513
|
+
/**
|
|
514
|
+
* `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
|
|
515
|
+
*
|
|
516
|
+
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
517
|
+
* 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
|
|
518
|
+
* if you want the cache to absorb more upstream pressure.
|
|
519
|
+
*
|
|
520
|
+
* Default: `20`.
|
|
521
|
+
*/
|
|
522
|
+
adaptiveTtlMultiplier?: number;
|
|
523
|
+
/**
|
|
524
|
+
* Number of fetch duration samples kept per key in the ring buffer.
|
|
525
|
+
* Larger values smooth out latency spikes but use slightly more memory
|
|
526
|
+
* (~8 bytes × samples per tracked key).
|
|
527
|
+
* Default: `32`.
|
|
528
|
+
*/
|
|
529
|
+
adaptiveTtlSamples?: number;
|
|
530
|
+
/**
|
|
531
|
+
* Maximum number of distinct keys tracked by the adaptive TTL system.
|
|
532
|
+
* When the cap is reached, the oldest-tracked key is evicted from the
|
|
533
|
+
* ring-buffer store to make room for the new key.
|
|
534
|
+
* Default: `5000`.
|
|
535
|
+
*/
|
|
536
|
+
adaptiveTtlMaxKeys?: number;
|
|
537
|
+
/**
|
|
538
|
+
* When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
|
|
539
|
+
* encryption and decryption for large payloads to those threads, keeping the
|
|
540
|
+
* V8 main event loop free for concurrent HTTP requests.
|
|
541
|
+
*
|
|
542
|
+
* Only takes effect when `encryptionKey` is set — plaintext payloads are never
|
|
543
|
+
* serialized off-thread because `JSON.stringify/parse` is already fast.
|
|
544
|
+
*
|
|
545
|
+
* Default: `false`. Enable in long-running servers that write multi-megabyte
|
|
546
|
+
* encrypted payloads and observe event-loop latency spikes.
|
|
547
|
+
*/
|
|
548
|
+
workerThreads?: boolean;
|
|
549
|
+
/**
|
|
550
|
+
* Byte threshold above which an L2 payload is offloaded to a worker thread
|
|
551
|
+
* for encryption / decryption. Payloads smaller than this are processed
|
|
552
|
+
* synchronously (IPC overhead would exceed the savings).
|
|
553
|
+
* Default: `131072` (128 KB).
|
|
554
|
+
*/
|
|
555
|
+
workerThresholdBytes?: number;
|
|
556
|
+
/**
|
|
557
|
+
* Number of worker threads in the pool.
|
|
558
|
+
* Default: `Math.min(4, os.availableParallelism())`.
|
|
559
|
+
*/
|
|
560
|
+
workerPoolSize?: number;
|
|
561
|
+
/**
|
|
562
|
+
* Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
|
|
563
|
+
* disconnected before tricache considers its L1 entries potentially stale.
|
|
564
|
+
*
|
|
565
|
+
* When the subscriber reconnects after a gap longer than this value, all L1
|
|
566
|
+
* entries that were written *before* the disconnect started are evicted.
|
|
567
|
+
* This prevents the instance from silently serving data that peers may have
|
|
568
|
+
* invalidated while the backplane connection was down.
|
|
569
|
+
*
|
|
570
|
+
* Set to `0` to disable the fence entirely (accept eventual-consistency drift).
|
|
571
|
+
* Default: `5000` (5 seconds).
|
|
572
|
+
*/
|
|
573
|
+
backplaneMaxStalenessMs?: number;
|
|
574
|
+
/**
|
|
575
|
+
* Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
|
|
576
|
+
*
|
|
577
|
+
* Tricache auto-detects common serverless / ephemeral-filesystem runtimes
|
|
578
|
+
* (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
|
|
579
|
+
* Fly.io) and disables the disk tier automatically. Set this to `false` to
|
|
580
|
+
* override that detection and force the disk tier on regardless of runtime.
|
|
581
|
+
*
|
|
582
|
+
* When disabled:
|
|
583
|
+
* - L1 evictions are dropped instead of being spilled to disk.
|
|
584
|
+
* - Cold-start snapshot persistence is skipped.
|
|
585
|
+
* - The `disk` metrics field still appears but shows zeroed counters.
|
|
586
|
+
*
|
|
587
|
+
* Default: `undefined` (auto-detect).
|
|
588
|
+
*/
|
|
589
|
+
disableDisk?: boolean;
|
|
590
|
+
/**
|
|
591
|
+
* Redis Cluster node list. When provided, tricache connects using ioredis
|
|
592
|
+
* `Cluster` mode with automatic slot routing and multi-node connection
|
|
593
|
+
* pooling — no external proxy required.
|
|
594
|
+
*
|
|
595
|
+
* Takes precedence over `redisHost`/`redisPort`.
|
|
596
|
+
*
|
|
597
|
+
* @example
|
|
598
|
+
* redisClusterNodes: [
|
|
599
|
+
* { host: 'redis-1.internal', port: 6379 },
|
|
600
|
+
* { host: 'redis-2.internal', port: 6379 },
|
|
601
|
+
* { host: 'redis-3.internal', port: 6379 },
|
|
602
|
+
* ]
|
|
603
|
+
*/
|
|
604
|
+
redisClusterNodes?: Array<{
|
|
605
|
+
host: string;
|
|
606
|
+
port: number;
|
|
607
|
+
}>;
|
|
608
|
+
/**
|
|
609
|
+
* Redis Sentinel configuration for high-availability setups.
|
|
610
|
+
* When provided, tricache connects through Sentinel for automatic
|
|
611
|
+
* primary failover — no static `redisHost` / `redisPort` needed.
|
|
612
|
+
*
|
|
613
|
+
* Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
|
|
614
|
+
*
|
|
615
|
+
* @example
|
|
616
|
+
* redisSentinel: {
|
|
617
|
+
* name: 'mymaster',
|
|
618
|
+
* sentinels: [
|
|
619
|
+
* { host: 'sentinel-1.internal', port: 26379 },
|
|
620
|
+
* { host: 'sentinel-2.internal', port: 26379 },
|
|
621
|
+
* ],
|
|
622
|
+
* }
|
|
623
|
+
*/
|
|
624
|
+
redisSentinel?: {
|
|
625
|
+
/** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
|
|
626
|
+
name: string;
|
|
627
|
+
sentinels: Array<{
|
|
628
|
+
host: string;
|
|
629
|
+
port: number;
|
|
630
|
+
}>;
|
|
631
|
+
};
|
|
461
632
|
}
|
|
462
633
|
|
|
463
634
|
/**
|
|
@@ -483,6 +654,10 @@ declare class CacheService {
|
|
|
483
654
|
private readonly enc;
|
|
484
655
|
private readonly l1;
|
|
485
656
|
private readonly disk;
|
|
657
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
658
|
+
private _diskDisabled;
|
|
659
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
660
|
+
private _workerPool;
|
|
486
661
|
private readonly opts;
|
|
487
662
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
488
663
|
private readonly _namespace;
|
|
@@ -508,9 +683,12 @@ declare class CacheService {
|
|
|
508
683
|
private oomInterval;
|
|
509
684
|
private metricsInterval;
|
|
510
685
|
private _shutdownHandler;
|
|
686
|
+
private latencyTracker;
|
|
511
687
|
private readonly instanceId;
|
|
512
688
|
private readonly backplaneChannel;
|
|
513
689
|
private subClient;
|
|
690
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
691
|
+
private _subDisconnectedAt;
|
|
514
692
|
private readonly counters;
|
|
515
693
|
constructor(options?: CacheOptions);
|
|
516
694
|
/**
|
|
@@ -554,6 +732,11 @@ declare class CacheService {
|
|
|
554
732
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
555
733
|
_handleBackplaneMessage(message: string): void;
|
|
556
734
|
private publishInvalidation;
|
|
735
|
+
/**
|
|
736
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
737
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
738
|
+
*/
|
|
739
|
+
private _scanKeys;
|
|
557
740
|
private getRedis;
|
|
558
741
|
writeSnapshot(altPath?: string): void;
|
|
559
742
|
loadSnapshot(): void;
|
|
@@ -917,8 +1100,10 @@ declare class CacheService {
|
|
|
917
1100
|
type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
918
1101
|
declare class CacheEncryption {
|
|
919
1102
|
private _key;
|
|
1103
|
+
private _keyObj;
|
|
920
1104
|
private readonly _mode;
|
|
921
1105
|
private _prevKey;
|
|
1106
|
+
private _prevKeyObj;
|
|
922
1107
|
private _prevMode;
|
|
923
1108
|
private readonly _ivPool;
|
|
924
1109
|
private _ivOffset;
|
|
@@ -987,6 +1172,8 @@ interface SmartMemoryCacheOptions {
|
|
|
987
1172
|
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
988
1173
|
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
989
1174
|
logger: ILogger;
|
|
1175
|
+
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
1176
|
+
evictionWatermark?: number;
|
|
990
1177
|
}
|
|
991
1178
|
declare class SmartMemoryCache {
|
|
992
1179
|
private readonly cache;
|
|
@@ -1007,6 +1194,15 @@ declare class SmartMemoryCache {
|
|
|
1007
1194
|
private categoryHits;
|
|
1008
1195
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
1009
1196
|
private _bloomDirtyCount;
|
|
1197
|
+
/**
|
|
1198
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
1199
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
1200
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
1201
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
1202
|
+
* any other code can observe the pool state.
|
|
1203
|
+
*/
|
|
1204
|
+
private readonly _evictPool;
|
|
1205
|
+
private readonly _evictGPool;
|
|
1010
1206
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
|
|
1011
1207
|
private recalculateStats;
|
|
1012
1208
|
private getCategory;
|
|
@@ -1056,6 +1252,24 @@ declare class SmartMemoryCache {
|
|
|
1056
1252
|
*/
|
|
1057
1253
|
evictPercentage(pct: number): number;
|
|
1058
1254
|
cleanup(): number;
|
|
1255
|
+
/**
|
|
1256
|
+
* Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
|
|
1257
|
+
*
|
|
1258
|
+
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
1259
|
+
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
1260
|
+
* Entries written before the disconnect started may have been invalidated by
|
|
1261
|
+
* peers while the backplane was down; evicting them forces a controlled
|
|
1262
|
+
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1263
|
+
*
|
|
1264
|
+
* Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
|
|
1265
|
+
* Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
|
|
1266
|
+
* conservatively.
|
|
1267
|
+
*
|
|
1268
|
+
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1269
|
+
* this time are evicted.
|
|
1270
|
+
* @returns Number of entries evicted.
|
|
1271
|
+
*/
|
|
1272
|
+
evictSetBefore(cutoffMs: number): number;
|
|
1059
1273
|
exportEntries(forbiddenPrefixes: readonly string[]): Array<{
|
|
1060
1274
|
key: string;
|
|
1061
1275
|
entry: SmartCacheEntry;
|
|
@@ -1195,8 +1409,28 @@ declare class DiskTier {
|
|
|
1195
1409
|
private fileCount;
|
|
1196
1410
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1197
1411
|
private _nextJanitorBucket;
|
|
1412
|
+
private _db;
|
|
1413
|
+
private _stmtInsert;
|
|
1414
|
+
private _stmtSelect;
|
|
1415
|
+
private _stmtDelete;
|
|
1416
|
+
private _stmtExpire;
|
|
1417
|
+
private _stmtDelExp;
|
|
1418
|
+
private _stmtStats;
|
|
1198
1419
|
constructor(opts: DiskTierOptions);
|
|
1199
1420
|
private ensureDir;
|
|
1421
|
+
/**
|
|
1422
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
1423
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
1424
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
1425
|
+
*
|
|
1426
|
+
* Schema:
|
|
1427
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
1428
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
1429
|
+
*
|
|
1430
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
1431
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
1432
|
+
*/
|
|
1433
|
+
private _initSqlite;
|
|
1200
1434
|
private ensureUsageCounted;
|
|
1201
1435
|
/**
|
|
1202
1436
|
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
@@ -1265,13 +1499,17 @@ declare class DiskTier {
|
|
|
1265
1499
|
/** Purge all expired entries. Returns number deleted. */
|
|
1266
1500
|
purgeExpired(): number;
|
|
1267
1501
|
/**
|
|
1268
|
-
* Purge expired entries
|
|
1269
|
-
*
|
|
1270
|
-
*
|
|
1271
|
-
*
|
|
1502
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
1503
|
+
*
|
|
1504
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
1505
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
1506
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
1507
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
1508
|
+
* incremented so tests that inspect the counter continue to work.
|
|
1272
1509
|
*
|
|
1273
|
-
*
|
|
1274
|
-
*
|
|
1510
|
+
* File-only fallback:
|
|
1511
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
1512
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
1275
1513
|
*
|
|
1276
1514
|
* Returns the number of entries deleted in this tick.
|
|
1277
1515
|
*/
|
|
@@ -1283,6 +1521,10 @@ declare class DiskTier {
|
|
|
1283
1521
|
sizeKB: number;
|
|
1284
1522
|
maxKB: number;
|
|
1285
1523
|
};
|
|
1524
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
1525
|
+
get indexMode(): 'sqlite' | 'file-only';
|
|
1526
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1527
|
+
close(): void;
|
|
1286
1528
|
}
|
|
1287
1529
|
|
|
1288
1530
|
declare class WasmBloomFilter {
|