tricache 0.8.0 → 1.0.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 +10 -4
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
- package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +767 -133
- package/dist/cli.js +24 -6
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +734 -132
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +163 -46
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +42 -14
- package/dist/hono/index.cjs +8093 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
- package/dist/http/index.cjs +833 -170
- package/dist/http/index.d.ts +6 -30
- package/dist/http/index.js +9 -59
- package/dist/index.cjs +755 -130
- package/dist/index.d.ts +35 -6
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +725 -130
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +725 -130
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +3 -3
- package/dist/prisma/index.d.ts +2 -2
- package/dist/serialize-worker.cjs +127 -9
- package/dist/serialize-worker.js +8 -4
- package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +22 -9
- package/src/cache-service.ts +540 -68
- package/src/cli.ts +21 -4
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +38 -11
- package/src/edge/hono.ts +123 -42
- package/src/env.d.ts +13 -0
- package/src/hono/index.ts +316 -0
- package/src/http/index.ts +5 -0
- package/src/index.ts +9 -1
- package/src/ipc-telemetry.ts +29 -1
- package/src/serialize-worker.ts +6 -2
- package/src/types.ts +68 -5
- package/src/utils/tag-matcher.ts +90 -0
- package/dist/chunk-ZTSWCFYO.js +0 -135
- /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://kareem411.github.io/TriCache/)
|
|
5
5
|
[](https://www.npmjs.com/package/tricache)
|
|
6
6
|
[](https://www.npmjs.com/package/tricache)
|
|
7
|
-
[](tests)
|
|
8
8
|
[](src)
|
|
9
9
|
[](LICENSE)
|
|
10
10
|
[](https://nodejs.org)
|
|
@@ -73,10 +73,12 @@ await cache.invalidateTag('users');
|
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
* **Window TinyLFU (W-TinyLFU)**: ~1% Window LRU absorbs recency bursts; 4-row Count-Min Sketch rejects table scans. [[Internals $\rightarrow$](https://kareem411.github.io/TriCache/architecture-internals)]
|
|
76
|
+
* **WebAssembly Zstandard Compression**: Out-of-the-box `zstd` WASM engine compresses payloads $>1$ KB by ~95% with automatic Brotli fallback and optional LZ4.
|
|
76
77
|
* **Off-Heap `/dev/shm` RAM Spill**: Targets Linux POSIX shared memory tmpfs ($\ge 256\text{MB}$ total, $\ge 128\text{MB}$ free), burning 0 cloud IOPS. [[SRE Guide $\rightarrow$](https://kareem411.github.io/TriCache/kubernetes-production-guide)]
|
|
77
78
|
* **Dynamic Latency Watchdog**: Graduated shedding (0% $\rightarrow$ 25% $\rightarrow$ 75% $\rightarrow$ 100%) with asymmetric Redis hysteresis (15ms cutoff, 10ms recovery floor).
|
|
78
79
|
* **Ephemeral Quotas & K8s Eviction Defense**: Chunked watermark pruning (80% $\rightarrow$ 60% in 500-entry batches) and proactive $<10\%$ space spill pauses.
|
|
79
|
-
* **
|
|
80
|
+
* **Wildcard & Hierarchical Tag Invalidation**: Glob matching (`user:*`) and parent-child tree cascading (`{ cascade: true }`) over $O(1)$ generational version counters.
|
|
81
|
+
* **Differential Multi-Tier Waterfall Batching**: Cascading `cache.mget` resolves L1 $\rightarrow$ L2 $\rightarrow$ Disk $\rightarrow$ DB miss fetch with zero $N+1$ queries.
|
|
80
82
|
* **Zero-Dependency Cloud Hydration (SigV4)**: Hydrates cold pods from S3/R2 in milliseconds via native Web Crypto. [[Cloud Guide $\rightarrow$](https://kareem411.github.io/TriCache/cold-start-cloud-hydration)]
|
|
81
83
|
|
|
82
84
|
---
|
|
@@ -88,8 +90,10 @@ await cache.invalidateTag('users');
|
|
|
88
90
|
| **Storage Hierarchy** | In-Memory only | Single Remote (Redis) | Memory + Redis | **Three-Tier (RAM $\rightarrow$ `/dev/shm` $\rightarrow$ Redis)** |
|
|
89
91
|
| **Warm Hit Latency** | ~300 ns | 1,200,000 ns (1.2 ms) | ~400 ns | **356 ns (2.81M ops/sec)** |
|
|
90
92
|
| **Thundering-Herd Defense**| ❌ No | ❌ External plugin | ❌ No | **✅ Native Singleflight Coalescing** |
|
|
91
|
-
| **Tag Invalidation** | ❌ None | $O(N)$ blocking scan | $O(N)$ Redis Set | **✅ $O(1)$ Generational
|
|
93
|
+
| **Tag Invalidation** | ❌ None | $O(N)$ blocking scan | $O(N)$ Redis Set | **✅ $O(1)$ Generational + Wildcards & Cascades** |
|
|
92
94
|
| **Cluster Sync Backplane**| ❌ None | At-most-once Pub/Sub | Pub/Sub | **✅ Durable Redis Streams (`XADD`/`XREAD`)** |
|
|
95
|
+
| **Compression** | ❌ None | ❌ Manual | ❌ None | **✅ WebAssembly Zstandard (Default) & LZ4** |
|
|
96
|
+
| **Waterfall Batching (`mget`)**| ❌ None | ❌ Manual loops | ❌ None | **✅ Multi-Tier Cascading ($0$ $N+1$ Queries)** |
|
|
93
97
|
| **Container Memory Safety**| Unbounded GC | N/A (Remote only) | Heap-bound | **✅ Off-heap tmpfs + 80% OOM Guard** |
|
|
94
98
|
| **Encryption at Rest** | ❌ None | ❌ None | ❌ None | **✅ AES-256-GCM / Web Crypto AEAD** |
|
|
95
99
|
|
|
@@ -122,7 +126,8 @@ const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.int
|
|
|
122
126
|
| **Prisma ORM** | `tricache/prisma` | `$extends` client extension with query hashing and auto-mutation tag eviction. |
|
|
123
127
|
| **Drizzle ORM** | `tricache/drizzle` | `withCache(query, opts)` query wrapper with SQL+parameters hashing and background SWR. |
|
|
124
128
|
| **Express & Fastify** | `tricache/http` | Route caching middleware with deterministic query sorting, weak ETag, and `304 Not Modified`. |
|
|
125
|
-
| **Hono
|
|
129
|
+
| **Node Hono** | `tricache/hono` | First-class `cacheMiddleware` on `CacheService` with ttl/tags/SWR and `304 Not Modified`. |
|
|
130
|
+
| **Edge Isolates & Hono** | `tricache/edge` | Zero-Node-dependency implementation for Cloudflare Workers, Fastly Compute, Hono, and Vercel Edge. |
|
|
126
131
|
| **SSE Dashboard** | `tricache/dashboard` | Zero-dependency Server-Sent Events real-time admin dashboard. |
|
|
127
132
|
| **Live CLI Top** | `npx tricache top` | Real-time terminal ASCII monitor over Unix sockets and Windows named pipes. |
|
|
128
133
|
|
|
@@ -134,6 +139,7 @@ const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.int
|
|
|
134
139
|
* 🔬 **[Architecture & Mathematical Internals](docs/architecture-internals.md)** — W-TinyLFU, CMS, Bloom filters, SigV4 signer
|
|
135
140
|
* ☸️ **[Kubernetes SRE & Production Guide](docs/kubernetes-production-guide.md)** — `/dev/shm`, cgroups, eviction defense, readiness probes
|
|
136
141
|
* ☁️ **[Cold-Start Cloud Snapshot Hydration](docs/cold-start-cloud-hydration.md)** — S3, Cloudflare R2, readiness gates
|
|
142
|
+
* 📈 **[Prometheus /metrics Scraping Recipe](docs/metrics-recipe.md)** — Express / Fastify / Next.js endpoints, scrape config, and one-command local Grafana stack
|
|
137
143
|
* 💰 **[Cloud ROI Financial Simulation](bench/cloud-roi-simulation.ts)** — Deterministic Mulberry32 Zipfian benchmark (`pnpm bench:roi`)
|
|
138
144
|
* 📊 **[Full Benchmark Suite](BENCHMARKS.md)** — Throughput, serialization, concurrency analysis
|
|
139
145
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Example Prometheus scrape config for TriCache.
|
|
2
|
+
# See docs/metrics-recipe.md §3 for the full walkthrough.
|
|
3
|
+
#
|
|
4
|
+
# Bind Prometheus + Grafana to 127.0.0.1 only (see docker-compose.metrics.yml).
|
|
5
|
+
# DO NOT expose /metrics publicly without auth or IP allow-list.
|
|
6
|
+
|
|
7
|
+
global:
|
|
8
|
+
scrape_interval: 15s
|
|
9
|
+
evaluation_interval: 15s
|
|
10
|
+
|
|
11
|
+
scrape_configs:
|
|
12
|
+
- job_name: tricache
|
|
13
|
+
metrics_path: /metrics
|
|
14
|
+
static_configs:
|
|
15
|
+
- targets: ['host.docker.internal:3000'] # Prometheus in docker → host app
|
|
16
|
+
labels:
|
|
17
|
+
service: tricache
|
|
18
|
+
env: dev
|
|
@@ -2,9 +2,9 @@ import {
|
|
|
2
2
|
CacheService,
|
|
3
3
|
ProcessTerminationBus,
|
|
4
4
|
deepMergeOptions
|
|
5
|
-
} from "./chunk-
|
|
6
|
-
import "./chunk-
|
|
7
|
-
import "./chunk-
|
|
5
|
+
} from "./chunk-7SZSQS55.js";
|
|
6
|
+
import "./chunk-UBWLPKTI.js";
|
|
7
|
+
import "./chunk-2AJKEQMZ.js";
|
|
8
8
|
export {
|
|
9
9
|
CacheService,
|
|
10
10
|
ProcessTerminationBus,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CacheOptions,
|
|
1
|
+
import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-5HXqBfAf.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
|
|
@@ -227,6 +227,7 @@ declare class CacheService {
|
|
|
227
227
|
private readonly opts;
|
|
228
228
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
229
229
|
private readonly _namespace;
|
|
230
|
+
private readonly prefixLen;
|
|
230
231
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
231
232
|
private readonly _redisDisabled;
|
|
232
233
|
private readonly watchdog;
|
|
@@ -266,6 +267,21 @@ declare class CacheService {
|
|
|
266
267
|
private streamClient;
|
|
267
268
|
private _lastStreamId;
|
|
268
269
|
private _destroyed;
|
|
270
|
+
private readonly _pendingDiskDeletes;
|
|
271
|
+
private _globalEpoch;
|
|
272
|
+
private readonly _keyMutationEpochs;
|
|
273
|
+
/**
|
|
274
|
+
* Pattern tombstones for disk tier.
|
|
275
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
276
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
277
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
278
|
+
*/
|
|
279
|
+
private readonly _patternTombstones;
|
|
280
|
+
private _addPatternTombstone;
|
|
281
|
+
private _isTombstonedByPattern;
|
|
282
|
+
private _assertActive;
|
|
283
|
+
private _bumpKeyMutation;
|
|
284
|
+
private _getKeyMutationEpoch;
|
|
269
285
|
private _ipcServer?;
|
|
270
286
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
271
287
|
private _subDisconnectedAt;
|
|
@@ -623,7 +639,7 @@ declare class CacheService {
|
|
|
623
639
|
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
624
640
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
625
641
|
*/
|
|
626
|
-
mget<T>(keys: string[], fetchFn
|
|
642
|
+
mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
627
643
|
/**
|
|
628
644
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
629
645
|
* startup warming configured via `warmKeys` has completed.
|
|
@@ -677,27 +693,43 @@ declare class CacheService {
|
|
|
677
693
|
priority?: CachePriority;
|
|
678
694
|
}): Promise<number>;
|
|
679
695
|
/**
|
|
680
|
-
*
|
|
681
|
-
*
|
|
696
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
697
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
698
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
699
|
+
*/
|
|
700
|
+
private _resolveMatchingTags;
|
|
701
|
+
/**
|
|
702
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
703
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
704
|
+
*
|
|
705
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
706
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
682
707
|
*
|
|
683
708
|
* @example
|
|
684
709
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
685
710
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
711
|
+
*
|
|
712
|
+
* @example
|
|
713
|
+
* // Wildcard pattern invalidation
|
|
714
|
+
* await cache.invalidateTag('org:123:*');
|
|
715
|
+
*
|
|
716
|
+
* @example
|
|
717
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
718
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
686
719
|
*/
|
|
687
|
-
invalidateTag(tag: string): Promise<void>;
|
|
720
|
+
invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
|
|
688
721
|
/**
|
|
689
722
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
690
|
-
*
|
|
691
|
-
*
|
|
723
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
724
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
692
725
|
*
|
|
693
|
-
*
|
|
694
|
-
*
|
|
726
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
727
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
695
728
|
*
|
|
696
729
|
* @example
|
|
697
|
-
*
|
|
698
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
730
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
699
731
|
*/
|
|
700
|
-
invalidateTags(tags: string[]): Promise<void>;
|
|
732
|
+
invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void>;
|
|
701
733
|
/**
|
|
702
734
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
703
735
|
*/
|
|
@@ -99,10 +99,63 @@ var WasmBloomFilter = class {
|
|
|
99
99
|
}
|
|
100
100
|
};
|
|
101
101
|
|
|
102
|
+
// src/utils/tag-matcher.ts
|
|
103
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
104
|
+
function isWildcardTag(tag) {
|
|
105
|
+
return tag.includes("*") || tag.includes("?");
|
|
106
|
+
}
|
|
107
|
+
function matchesTagPattern(pattern, tag) {
|
|
108
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
109
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
110
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
111
|
+
const prefix = pattern.slice(0, -1);
|
|
112
|
+
return tag.startsWith(prefix);
|
|
113
|
+
}
|
|
114
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
115
|
+
const suffix = pattern.slice(1);
|
|
116
|
+
return tag.endsWith(suffix);
|
|
117
|
+
}
|
|
118
|
+
let re = globRegexCache.get(pattern);
|
|
119
|
+
if (!re) {
|
|
120
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
121
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
122
|
+
re = new RegExp(`^${escaped}$`);
|
|
123
|
+
globRegexCache.set(pattern, re);
|
|
124
|
+
}
|
|
125
|
+
return re.test(tag);
|
|
126
|
+
}
|
|
127
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
128
|
+
if (candidateTag === parentTag) return true;
|
|
129
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
130
|
+
return candidateTag.startsWith(prefix);
|
|
131
|
+
}
|
|
132
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
133
|
+
if (!tags.length) return [];
|
|
134
|
+
const result = /* @__PURE__ */ new Set();
|
|
135
|
+
for (const tag of tags) {
|
|
136
|
+
if (!tag) continue;
|
|
137
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
138
|
+
if (parts.length <= 1) {
|
|
139
|
+
result.add(tag);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
let accumulated = "";
|
|
143
|
+
for (let i = 0; i < parts.length; i++) {
|
|
144
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
145
|
+
result.add(accumulated);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return Array.from(result);
|
|
149
|
+
}
|
|
150
|
+
|
|
102
151
|
export {
|
|
103
152
|
uint8ArrayToBase64,
|
|
104
153
|
base64ToUint8Array,
|
|
105
154
|
utf8ToUint8Array,
|
|
106
155
|
uint8ArrayToUtf8,
|
|
107
|
-
WasmBloomFilter
|
|
156
|
+
WasmBloomFilter,
|
|
157
|
+
isWildcardTag,
|
|
158
|
+
matchesTagPattern,
|
|
159
|
+
isChildTag,
|
|
160
|
+
expandHierarchicalTags
|
|
108
161
|
};
|