tricache 0.1.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/src/types.ts ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * tricache — shared types and interfaces
3
+ */
4
+
5
+ // ─── Logger ─────────────────────────────────────────────────────────────────
6
+
7
+ /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
8
+ export interface ILogger {
9
+ debug(msg: string, meta?: Record<string, unknown>): void;
10
+ info(msg: string, meta?: Record<string, unknown>): void;
11
+ warn(msg: string, meta?: Record<string, unknown>): void;
12
+ error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
13
+ }
14
+
15
+ /** Default no-op logger — swap out via CacheService options */
16
+ export const consoleLogger: ILogger = {
17
+ debug: (msg, meta) => {},
18
+ info: (msg, meta) => console.info('[tricache]', msg, meta ?? ''),
19
+ warn: (msg, meta) => console.warn('[tricache]', msg, meta ?? ''),
20
+ error: (msg, meta, err) => console.error('[tricache]', msg, meta ?? '', err ?? ''),
21
+ };
22
+
23
+ // ─── Cache priorities ────────────────────────────────────────────────────────
24
+
25
+ /** Priority levels for L1 eviction — higher = less likely to be evicted */
26
+ export enum CachePriority {
27
+ LOW = 1, // Easily regenerated (analytics, reports)
28
+ NORMAL = 2, // General data
29
+ HIGH = 3, // Frequently accessed (profiles, config)
30
+ CRITICAL = 4, // Must never be evicted unless expired (auth tokens, active sessions)
31
+ }
32
+
33
+ // ─── Internal L1 entry shape ─────────────────────────────────────────────────
34
+
35
+ /** Internal representation of a single cache entry in the L1 Map */
36
+ export interface SmartCacheEntry {
37
+ /** msgpackr-packed binary payload */
38
+ data: Buffer;
39
+ /** always true for entries written by the current code;
40
+ * may be false in legacy snapshots/disk files — handled transparently on import */
41
+ isCompressed: boolean;
42
+ /** Hard expiry — entry is deleted after this timestamp */
43
+ expiresAt: number;
44
+ /** SWR soft expiry — serve stale + revalidate in background when past this */
45
+ staleAt?: number;
46
+ /** Exact byte size of the stored value */
47
+ size: number;
48
+ /** Access count (LFU numerator) */
49
+ hits: number;
50
+ /** Last access timestamp (LRU comparator) */
51
+ lastAccess: number;
52
+ /** Eviction priority */
53
+ priority: CachePriority;
54
+ }
55
+
56
+ /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
57
+ export interface CacheHit {
58
+ value: unknown;
59
+ /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
60
+ isStale: boolean;
61
+ }
62
+
63
+ // ─── Disk tier ───────────────────────────────────────────────────────────────
64
+
65
+ /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
66
+ * legacy disk files written by older versions may have a JSON string in data) */
67
+ export interface DiskCacheEntry {
68
+ data: string | Buffer | Uint8Array;
69
+ isCompressed: boolean;
70
+ expiresAt: number;
71
+ staleAt?: number;
72
+ size: number;
73
+ hits: number;
74
+ lastAccess: number;
75
+ priority: number;
76
+ }
77
+
78
+ // ─── Metrics snapshot ────────────────────────────────────────────────────────
79
+
80
+ /**
81
+ * Snapshot of runtime metrics for a CacheService instance.
82
+ * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
83
+ * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
84
+ */
85
+ export interface CacheMetrics {
86
+ /** Configured namespace (empty string = no namespace) */
87
+ namespace: string;
88
+ /** Milliseconds since the CacheService instance was constructed */
89
+ uptimeMs: number;
90
+
91
+ gets: {
92
+ total: number;
93
+ l1Hits: number;
94
+ /** Fraction of gets served from L1 RAM cache (0–1) */
95
+ l1HitRate: number;
96
+ diskHits: number;
97
+ /** Fraction of gets served from L1.5 disk tier (0–1) */
98
+ diskHitRate: number;
99
+ l2Hits: number;
100
+ /** Fraction of gets served from L2 Redis (0–1) */
101
+ l2HitRate: number;
102
+ /** fetchFn calls (cache misses that fell through to the DB) */
103
+ fetches: number;
104
+ /** Fraction of gets that called fetchFn (0–1) */
105
+ fetchRate: number;
106
+ /** Concurrent get() calls deduplicated by the stampede guard */
107
+ stampedePrevented: number;
108
+ };
109
+
110
+ sets: { total: number };
111
+ deletes: { total: number };
112
+ revalidations: { total: number };
113
+
114
+ bloom: {
115
+ /** Total bloom-filter checks (get() calls that passed prefix filter) */
116
+ checksTotal: number;
117
+ /**
118
+ * Times the filter said "might contain" but the key was absent in L1.
119
+ * A high rate suggests the bloom filter capacity needs increasing.
120
+ */
121
+ falsePositives: number;
122
+ /** falsePositives / checksTotal (0–1; ideal < 0.01) */
123
+ falsePositiveRate: number;
124
+ };
125
+
126
+ compression: {
127
+ entriesCompressed: number;
128
+ entriesUncompressed: number;
129
+ /** Approximate bytes saved by msgpackr vs raw JSON */
130
+ bytesSaved: number;
131
+ };
132
+
133
+ /** Pub/Sub invalidation backplane statistics */
134
+ backplane: {
135
+ enabled: boolean;
136
+ /** Invalidation messages published to other instances */
137
+ sent: number;
138
+ /** Invalidation messages received from other instances */
139
+ received: number;
140
+ /** Own messages silently skipped (prevents double-eviction) */
141
+ skipped: number;
142
+ };
143
+
144
+ /** OOM guard statistics */
145
+ oom: {
146
+ enabled: boolean;
147
+ /** Number of emergency L1 eviction rounds triggered */
148
+ evictions: number;
149
+ /** Timestamp of the most recent OOM eviction, or null */
150
+ lastTriggeredAt: number | null;
151
+ };
152
+
153
+ l1: { entries: number; sizeBytes: number; maxBytes: number };
154
+ disk: { files: number; sizeKB: number; maxKB: number };
155
+ }
156
+
157
+ // ─── Configuration ───────────────────────────────────────────────────────────
158
+
159
+ /** Per-category memory limits for L1 */
160
+ export interface CategoryLimit {
161
+ maxEntries: number;
162
+ maxSizeBytes: number;
163
+ }
164
+
165
+ /**
166
+ * Options accepted by CacheService.create()
167
+ *
168
+ * All fields are optional — sensible defaults are used when omitted.
169
+ */
170
+ export interface CacheOptions {
171
+ /**
172
+ * Plug in your own logger (pino, winston, bunyan, …).
173
+ * Defaults to a minimal console logger that only prints warn/error.
174
+ */
175
+ logger?: ILogger;
176
+
177
+ // ── L1 (in-memory) ────────────────────────────────────────────────────────
178
+ /** Max total bytes held in L1 RAM cache. Default: 200 MB */
179
+ l1MaxBytes?: number;
180
+ /** Max total entries in L1. Default: 2000 */
181
+ l1MaxEntries?: number;
182
+ /**
183
+ * Per-category limits keyed by the key prefix (e.g. `'org:'`).
184
+ * Merged over the built-in defaults.
185
+ */
186
+ categoryLimits?: Record<string, CategoryLimit>;
187
+ /**
188
+ * Key prefixes that are never written to disk snapshots or the disk tier.
189
+ * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
190
+ */
191
+ forbiddenSnapshotPrefixes?: string[];
192
+
193
+ // ── L1.5 (disk tier) ────────────────────────────────────────────────────
194
+ /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
195
+ diskCacheDir?: string;
196
+ /** Max total bytes for the disk tier. Default: 500 MB */
197
+ diskMaxBytes?: number;
198
+ /** Max bytes for a single disk entry. Default: 10 MB */
199
+ diskEntryMaxBytes?: number;
200
+
201
+ // ── L2 (Redis) ────────────────────────────────────────────────────────────
202
+ /**
203
+ * Redis/Valkey hostname (no `redis://` prefix).
204
+ * Falls back to the `REDIS_HOST` environment variable.
205
+ * When neither is provided, L2 is disabled.
206
+ */
207
+ redisHost?: string;
208
+ /** Redis port. Default: 6379 */
209
+ redisPort?: number;
210
+ /**
211
+ * Whether to enable TLS for the Redis connection. Default: true in production,
212
+ * false otherwise.
213
+ */
214
+ redisTls?: boolean;
215
+ /**
216
+ * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
217
+ * services that don't need distributed caching). Default: false in production,
218
+ * true in development.
219
+ */
220
+ disableRedis?: boolean;
221
+
222
+ // ── Encryption ────────────────────────────────────────────────────────────
223
+ /**
224
+ * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
225
+ * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
226
+ * If not provided in production, a warning is logged and data is stored plaintext.
227
+ */
228
+ encryptionKey?: string;
229
+ /**
230
+ * Encryption algorithm used for L2 (Redis) values and disk-tier files.
231
+ * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
232
+ * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
233
+ * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
234
+ * Any key length (minimum 16 bytes recommended).
235
+ * Use for dev environments or non-sensitive data only.
236
+ * Default: `'aes-256-gcm'`
237
+ */
238
+ encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
239
+
240
+ // ── Snapshot ────────────────────────────────────────────────────────────
241
+ /**
242
+ * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
243
+ * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
244
+ */
245
+ snapshotPath?: string;
246
+ /**
247
+ * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
248
+ */
249
+ snapshotMaxAgeMs?: number;
250
+
251
+ /**
252
+ * Optional namespace prefix for all cache keys.
253
+ *
254
+ * When set, every key is transparently stored as `${namespace}:${key}` in
255
+ * L1, L1.5 (disk), and L2 (Redis). This enables:
256
+ * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
257
+ * — tenants sharing the same Redis instance or disk dir are fully isolated.
258
+ * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
259
+ * - **Service-level scoping**: microservices sharing one Redis without key collisions.
260
+ *
261
+ * Consumers never see the prefix — `get('user:1')` behaves identically
262
+ * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
263
+ * scope to the namespace.
264
+ *
265
+ * The process-level singleton, disk cache directory, and cold-start snapshot
266
+ * path are all scoped per namespace, so two `CacheService.create()` calls
267
+ * with different namespaces return completely independent instances.
268
+ *
269
+ * Default: `''` (no prefix)
270
+ */
271
+ namespace?: string;
272
+
273
+ // ── Invalidation backplane (Redis Pub/Sub) ──────────────────────────────
274
+ /**
275
+ * Enable Redis Pub/Sub invalidation backplane so every running instance
276
+ * evicts a key from its L1 when any peer calls `set()` or `delete()`.
277
+ *
278
+ * Gives you sub-microsecond in-process cache speed with cluster-wide
279
+ * consistency across all your app servers.
280
+ *
281
+ * Default: `true` (auto-activates when Redis is available).
282
+ * Set to `false` for single-process services or eventual-consistency scenarios.
283
+ */
284
+ invalidationBackplane?: boolean;
285
+
286
+ // ── OOM protection ──────────────────────────────────────────────────────
287
+ /**
288
+ * Enable the GC-aware OOM guard. When heap utilisation crosses
289
+ * `oomHeapThreshold`, a fraction of the coldest L1 entries are
290
+ * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
291
+ * Docker/Kubernetes containers with tight memory limits.
292
+ *
293
+ * Default: `true`
294
+ */
295
+ oomProtection?: boolean;
296
+ /**
297
+ * Heap-used / heap-total ratio that triggers emergency eviction.
298
+ * Default: `0.85` (85 %)
299
+ */
300
+ oomHeapThreshold?: number;
301
+ /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
302
+ oomCheckIntervalMs?: number;
303
+ /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
304
+ oomEvictPercent?: number;
305
+
306
+ // ── Metrics / observability ─────────────────────────────────────────────
307
+ /**
308
+ * Callback invoked periodically with a `CacheMetrics` snapshot.
309
+ * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
310
+ *
311
+ * @example
312
+ * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
313
+ */
314
+ onMetrics?: (metrics: CacheMetrics) => void;
315
+ /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
316
+ metricsIntervalMs?: number;
317
+ }
@@ -0,0 +1,117 @@
1
+ /// <reference lib="dom" />
2
+
3
+ /**
4
+ * WasmBloomFilter — WASM-powered Bloom filter using FNV-1a/djb2 double-hashing.
5
+ *
6
+ * The 562-byte WASM binary is inlined as Base64 to avoid any runtime file-system
7
+ * dependency. It implements a 100,000-bit filter with k=7 hash probes giving a
8
+ * ~0.01% false-positive rate at 2,000 entries.
9
+ *
10
+ * Memory layout (1 WASM page = 64 KB):
11
+ * [0 .. 12499] = 100,000-bit bit-array
12
+ * [20000 .. 20511] = 512-byte key staging area (JS → WASM string transfer)
13
+ *
14
+ * Used by SmartMemoryCache as the first-level miss detector.
15
+ * Falls back to the pure-JS BloomFilter if WASM fails to instantiate.
16
+ */
17
+
18
+ const BLOOM_WASM_BASE64 =
19
+ 'AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUG' +
20
+ 'BQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVz' +
21
+ 'ZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAA' +
22
+ 'cyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJB' +
23
+ 'BXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAA' +
24
+ 'CxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEh' +
25
+ 'A0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEh' +
26
+ 'A0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJA' +
27
+ 'A0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAA' +
28
+ 'LQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==';
29
+
30
+ const KEY_STAGING_OFFSET = 20_000;
31
+ const MAX_KEY_BYTES = 512;
32
+
33
+ interface BloomWasmExports {
34
+ memory: WebAssembly.Memory;
35
+ add(ptr: number, len: number): void;
36
+ mightContain(ptr: number, len: number): number;
37
+ reset(): void;
38
+ countBits(): number;
39
+ }
40
+
41
+ function instantiateSync(): WebAssembly.Instance {
42
+ const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, 'base64');
43
+ const compiled = new WebAssembly.Module(wasmBytes);
44
+ return new WebAssembly.Instance(compiled, {});
45
+ }
46
+
47
+ export class WasmBloomFilter {
48
+ private readonly exports: BloomWasmExports;
49
+ private readonly mem: Uint8Array;
50
+ private readonly encoder = new TextEncoder();
51
+ private readonly numBits = 100_000;
52
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
53
+ private readonly _maxCapacity: number;
54
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
55
+ private _insertionCount = 0;
56
+
57
+ constructor() {
58
+ const instance = instantiateSync();
59
+ this.exports = instance.exports as unknown as BloomWasmExports;
60
+ this.mem = new Uint8Array(this.exports.memory.buffer);
61
+ const k = 7, p = 0.01;
62
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
63
+ }
64
+
65
+ private writeKey(key: string): number {
66
+ const max = Math.min(key.length, MAX_KEY_BYTES);
67
+ if (max === 0) return 0;
68
+ // Fast path: write ASCII bytes directly, skipping TextEncoder heap allocation.
69
+ // On the first non-ASCII char, fall back to TextEncoder for correct multi-byte encoding.
70
+ for (let i = 0; i < max; i++) {
71
+ const c = key.charCodeAt(i);
72
+ if (c > 127) {
73
+ const encoded = this.encoder.encode(key);
74
+ const len = Math.min(encoded.length, MAX_KEY_BYTES);
75
+ this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
76
+ return len;
77
+ }
78
+ this.mem[KEY_STAGING_OFFSET + i] = c;
79
+ }
80
+ return max;
81
+ }
82
+
83
+ add(key: string): void {
84
+ const len = this.writeKey(key);
85
+ if (len === 0) return;
86
+ this.exports.add(KEY_STAGING_OFFSET, len);
87
+ this._insertionCount++;
88
+ }
89
+
90
+ mightContain(key: string): boolean {
91
+ const len = this.writeKey(key);
92
+ if (len === 0) return true;
93
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
94
+ }
95
+
96
+ reset(): void { this.exports.reset(); this._insertionCount = 0; }
97
+
98
+ rebuild(keys: Iterable<string>): void {
99
+ this.reset();
100
+ for (const key of keys) this.add(key);
101
+ }
102
+
103
+ get stats(): { bitsSet: number; fillFactor: number } {
104
+ const bitsSet = this.exports.countBits();
105
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
106
+ }
107
+
108
+ /** Number of add() calls since last reset/rebuild. */
109
+ get insertions(): number { return this._insertionCount; }
110
+
111
+ /**
112
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
113
+ * Exact formula for k=7 hash rounds, m=100 000 bits:
114
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
115
+ */
116
+ get maxCapacity(): number { return this._maxCapacity; }
117
+ }