tricache 0.4.0 → 0.5.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAa,iBAAiB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAuB,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAS,sBAAsB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAiB,aAAa,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAU,0BAA0B,CAAC;AAE/D,OAAO,EACL,aAAa,EACb,aAAa,GAYd,MAAM,SAAS,CAAC"}
@@ -0,0 +1,178 @@
1
+ /**
2
+ * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
3
+ *
4
+ * Features:
5
+ * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
6
+ * - msgpackr compression for entries ≥ 512 bytes
7
+ * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
8
+ * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
9
+ * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
10
+ * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
11
+ * - Periodic cleanup of hard-expired entries + bloom filter rebuild
12
+ * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
+ */
14
+ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
15
+ export interface SmartMemoryCacheOptions {
16
+ maxBytes: number;
17
+ maxEntries: number;
18
+ categories: Record<string, CategoryLimit>;
19
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
20
+ onEviction?: (key: string, reason: EvictionReason) => void;
21
+ logger: ILogger;
22
+ }
23
+ export declare class SmartMemoryCache {
24
+ private readonly cache;
25
+ private readonly opts;
26
+ private bloom;
27
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
28
+ private readonly categoryPrefixes;
29
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
30
+ private readonly sketch;
31
+ private totalSize;
32
+ private categoryCount;
33
+ private categorySize;
34
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
35
+ private categoryKeys;
36
+ private bloomChecks;
37
+ private bloomFalsePos;
38
+ private compressions;
39
+ private categoryHits;
40
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
41
+ private _bloomDirtyCount;
42
+ constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
43
+ private recalculateStats;
44
+ private getCategory;
45
+ private getCategoryLimit;
46
+ private _delete;
47
+ private ensureCapacity;
48
+ private score;
49
+ /**
50
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
51
+ * saturated the filter past its ~1 % FP capacity.
52
+ *
53
+ * Trigger: (insertions − live entries) > maxCapacity
54
+ *
55
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
56
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
57
+ * cache holds more entries than the filter's rated capacity — which would
58
+ * stall the write path entirely.
59
+ *
60
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
61
+ */
62
+ private maybeRebuildBloom;
63
+ private smartEvict;
64
+ get(key: string): CacheHit | null;
65
+ set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
66
+ delete(key: string): boolean;
67
+ private keysMatchingPattern;
68
+ deletePattern(pattern: string): number;
69
+ /** Flush all entries, or only those whose key starts with `prefix`. */
70
+ clear(prefix?: string): number;
71
+ /**
72
+ * Evict entries that violate current category or global limits.
73
+ * Returns the number of entries evicted.
74
+ */
75
+ rebalance(): number;
76
+ /**
77
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
78
+ * Only reflects L1 state — does not query Redis or disk.
79
+ */
80
+ ttl(key: string): number | null;
81
+ /**
82
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
83
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
84
+ * exceeds the configured threshold.
85
+ *
86
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
87
+ * @returns Number of entries evicted
88
+ */
89
+ evictPercentage(pct: number): number;
90
+ cleanup(): number;
91
+ exportEntries(forbiddenPrefixes: readonly string[]): Array<{
92
+ key: string;
93
+ entry: SmartCacheEntry;
94
+ }>;
95
+ importEntries(entries: Array<{
96
+ key: string;
97
+ entry: SmartCacheEntry;
98
+ }>, forbiddenPrefixes: readonly string[]): number;
99
+ /**
100
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
101
+ * Expired entries that are still in the Map (awaiting background cleanup)
102
+ * are silently skipped.
103
+ */
104
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
105
+ /**
106
+ * Yields only the keys of live entries — no intermediate tuple allocation.
107
+ * Use this instead of liveEntries() when you only need keys.
108
+ */
109
+ liveKeys(): Generator<string>;
110
+ /**
111
+ * Yields only the resolved values of live entries.
112
+ * Iterates Map.values() so the key is never loaded into the yielded path.
113
+ * Returns the cached deserialized object when available (entry.value), otherwise
114
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
115
+ */
116
+ liveValues(): Generator<unknown>;
117
+ get size(): number;
118
+ get memoryUsage(): number;
119
+ getStats(): {
120
+ entries: number;
121
+ sizeBytes: number;
122
+ sizeKB: number;
123
+ categories: Record<string, {
124
+ entries: number;
125
+ hits: number;
126
+ }>;
127
+ bloom: {
128
+ checks: number;
129
+ falsePositives: number;
130
+ };
131
+ compression: {
132
+ compressed: number;
133
+ uncompressed: number;
134
+ bytesSaved: number;
135
+ };
136
+ };
137
+ /**
138
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
139
+ * Does NOT count as a hit or perform SWR logic.
140
+ */
141
+ getEntry(key: string): SmartCacheEntry | undefined;
142
+ /**
143
+ * Return true if the key exists in L1 and has not expired.
144
+ * Uses the bloom filter as a fast negative check.
145
+ */
146
+ has(key: string): boolean;
147
+ /**
148
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
149
+ * @param newTtlMs - New TTL from now, in milliseconds.
150
+ */
151
+ touch(key: string, newTtlMs: number): boolean;
152
+ /**
153
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
154
+ * Returns `false` if the key is absent or already expired.
155
+ */
156
+ bumpExpiry(key: string, additionalMs: number): boolean;
157
+ bloomMightContain(key: string): boolean;
158
+ bloomStats(): {
159
+ bitsSet: number;
160
+ fillFactor: number;
161
+ } | {
162
+ bitsSet: number;
163
+ fillFactor: number;
164
+ };
165
+ /**
166
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
167
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
168
+ * Useful for diagnosing which keys are driving cache pressure.
169
+ *
170
+ * @param n - Maximum number of entries to return. Default: 10.
171
+ */
172
+ hotKeys(n: number): Array<{
173
+ key: string;
174
+ hits: number;
175
+ sizeBytes: number;
176
+ }>;
177
+ }
178
+ //# sourceMappingURL=smart-memory-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smart-memory-cache.d.ts","sourceRoot":"","sources":["../src/smart-memory-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAwKhH,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAK,MAAM,CAAC;IACpB,UAAU,EAAG,MAAM,CAAC;IACpB,UAAU,EAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC3C,SAAS,CAAC,EAAG,CAAC,GAAG,EAA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