tricache 0.8.0 → 0.9.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.
Files changed (44) hide show
  1. package/README.md +4 -2
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-DVvroyqA.d.ts} +16 -1
  4. package/dist/{cache-service-5MZXFIGK.js → cache-service-KI5ACF3F.js} +1 -1
  5. package/dist/chunk-BQRURGGD.js +60 -0
  6. package/dist/chunk-IITRFWHY.js +196 -0
  7. package/dist/{chunk-6PQ5MOWR.js → chunk-PL5J3ZNT.js} +370 -81
  8. package/dist/cli.cjs +392 -84
  9. package/dist/cli.js +22 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +350 -81
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +99 -38
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +5 -5
  17. package/dist/hono/index.cjs +7760 -0
  18. package/dist/hono/index.d.ts +91 -0
  19. package/dist/hono/index.js +185 -0
  20. package/dist/{hono-DQRS1Xd7.d.ts → hono-VA9A1m0I.d.ts} +3 -2
  21. package/dist/http/index.cjs +449 -119
  22. package/dist/http/index.d.ts +6 -30
  23. package/dist/http/index.js +9 -59
  24. package/dist/index.cjs +370 -81
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +1 -1
  27. package/dist/nestjs/index.cjs +350 -81
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +1 -1
  30. package/dist/next/index.cjs +350 -81
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +1 -1
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/{types-B6krw64X.d.ts → types-B_QkVwJ7.d.ts} +23 -0
  35. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  36. package/package.json +16 -6
  37. package/src/cache-service.ts +302 -35
  38. package/src/cli.ts +21 -4
  39. package/src/edge/hono.ts +123 -42
  40. package/src/hono/index.ts +316 -0
  41. package/src/http/index.ts +5 -0
  42. package/src/ipc-telemetry.ts +29 -1
  43. package/src/types.ts +25 -0
  44. package/dist/chunk-ZTSWCFYO.js +0 -135
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![Docs](https://img.shields.io/badge/docs-VitePress-blue.svg)](https://kareem411.github.io/TriCache/)
5
5
  [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/tricache.svg)](https://www.npmjs.com/package/tricache)
7
- [![Tests](https://img.shields.io/badge/tests-809%20passing-brightgreen)](tests)
7
+ [![Tests](https://img.shields.io/badge/tests-862%20passing-brightgreen)](tests)
8
8
  [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](src)
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
10
10
  [![Node.js ≥ 20](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)
@@ -122,7 +122,8 @@ const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.int
122
122
  | **Prisma ORM** | `tricache/prisma` | `$extends` client extension with query hashing and auto-mutation tag eviction. |
123
123
  | **Drizzle ORM** | `tricache/drizzle` | `withCache(query, opts)` query wrapper with SQL+parameters hashing and background SWR. |
124
124
  | **Express & Fastify** | `tricache/http` | Route caching middleware with deterministic query sorting, weak ETag, and `304 Not Modified`. |
125
- | **Hono & Edge Isolates** | `tricache/edge` | Zero-Node-dependency implementation for Cloudflare Workers, Fastly Compute, Hono, and Vercel Edge. |
125
+ | **Node Hono** | `tricache/hono` | First-class `cacheMiddleware` on `CacheService` with ttl/tags/SWR and `304 Not Modified`. |
126
+ | **Edge Isolates & Hono** | `tricache/edge` | Zero-Node-dependency implementation for Cloudflare Workers, Fastly Compute, Hono, and Vercel Edge. |
126
127
  | **SSE Dashboard** | `tricache/dashboard` | Zero-dependency Server-Sent Events real-time admin dashboard. |
127
128
  | **Live CLI Top** | `npx tricache top` | Real-time terminal ASCII monitor over Unix sockets and Windows named pipes. |
128
129
 
@@ -134,6 +135,7 @@ const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.int
134
135
  * 🔬 **[Architecture & Mathematical Internals](docs/architecture-internals.md)** — W-TinyLFU, CMS, Bloom filters, SigV4 signer
135
136
  * ☸️ **[Kubernetes SRE & Production Guide](docs/kubernetes-production-guide.md)** — `/dev/shm`, cgroups, eviction defense, readiness probes
136
137
  * ☁️ **[Cold-Start Cloud Snapshot Hydration](docs/cold-start-cloud-hydration.md)** — S3, Cloudflare R2, readiness gates
138
+ * 📈 **[Prometheus /metrics Scraping Recipe](docs/metrics-recipe.md)** — Express / Fastify / Next.js endpoints, scrape config, and one-command local Grafana stack
137
139
  * 💰 **[Cloud ROI Financial Simulation](bench/cloud-roi-simulation.ts)** — Deterministic Mulberry32 Zipfian benchmark (`pnpm bench:roi`)
138
140
  * 📊 **[Full Benchmark Suite](BENCHMARKS.md)** — Throughput, serialization, concurrency analysis
139
141
 
@@ -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
@@ -1,4 +1,4 @@
1
- import { C as CacheOptions, a as CacheMetrics, b as CacheHealthStatus, c as CachePresetType, d as CrossRegionInvalidationEvent, e as CachePriority, W as WrapOptions, f as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, g as WTinyLfuStats } from './types-B6krw64X.js';
1
+ import { C as CacheOptions, a as CacheMetrics, b as CacheHealthStatus, c as CachePresetType, d as CrossRegionInvalidationEvent, e as CachePriority, W as WrapOptions, f as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, g as WTinyLfuStats } from './types-B_QkVwJ7.js';
2
2
 
3
3
  /**
4
4
  * TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
@@ -266,6 +266,21 @@ declare class CacheService {
266
266
  private streamClient;
267
267
  private _lastStreamId;
268
268
  private _destroyed;
269
+ private readonly _pendingDiskDeletes;
270
+ private _globalEpoch;
271
+ private readonly _keyMutationEpochs;
272
+ /**
273
+ * Pattern tombstones for disk tier.
274
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
275
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
276
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
277
+ */
278
+ private readonly _patternTombstones;
279
+ private _addPatternTombstone;
280
+ private _isTombstonedByPattern;
281
+ private _assertActive;
282
+ private _bumpKeyMutation;
283
+ private _getKeyMutationEpoch;
269
284
  private _ipcServer?;
270
285
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
271
286
  private _subDisconnectedAt;
@@ -2,7 +2,7 @@ import {
2
2
  CacheService,
3
3
  ProcessTerminationBus,
4
4
  deepMergeOptions
5
- } from "./chunk-6PQ5MOWR.js";
5
+ } from "./chunk-PL5J3ZNT.js";
6
6
  import "./chunk-LJ5QJB5O.js";
7
7
  import "./chunk-XZL45ABR.js";
8
8
  export {
@@ -0,0 +1,60 @@
1
+ // src/http/utils.ts
2
+ import crypto from "crypto";
3
+ function buildDeterministicKey(req, options) {
4
+ if (options?.keyGenerator) {
5
+ return options.keyGenerator(req);
6
+ }
7
+ const method = (req.method || "GET").toUpperCase();
8
+ const rawUrl = req.originalUrl || req.url || "/";
9
+ const qIdx = rawUrl.indexOf("?");
10
+ const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
11
+ let queryString = "";
12
+ if (qIdx >= 0) {
13
+ const rawQuery = rawUrl.slice(qIdx + 1);
14
+ try {
15
+ const params = new URLSearchParams(rawQuery);
16
+ params.sort();
17
+ queryString = params.toString();
18
+ } catch {
19
+ queryString = rawQuery;
20
+ }
21
+ }
22
+ let key = `http:${method}:${path}`;
23
+ if (queryString) {
24
+ key += `?${queryString}`;
25
+ }
26
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
27
+ const sortedHeaders = [...options.headerWhitelist].sort();
28
+ for (const h of sortedHeaders) {
29
+ const normalizedHeader = h.toLowerCase();
30
+ const val = req.headers[normalizedHeader];
31
+ if (val !== void 0 && val !== null && val !== "") {
32
+ const headerStr = Array.isArray(val) ? val.join(",") : String(val);
33
+ key += `|h:${normalizedHeader}=${headerStr}`;
34
+ }
35
+ }
36
+ }
37
+ return key;
38
+ }
39
+ function shouldSkipCache(req, customSkip) {
40
+ if (customSkip && customSkip(req)) return true;
41
+ const cc = req.headers ? req.headers["cache-control"] || req.headers["Cache-Control"] : void 0;
42
+ if (typeof cc === "string") {
43
+ const lower = cc.toLowerCase();
44
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
45
+ return true;
46
+ }
47
+ }
48
+ return false;
49
+ }
50
+ function generateETag(data) {
51
+ const str = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : JSON.stringify(data);
52
+ const hash = crypto.createHash("sha1").update(str).digest("hex").slice(0, 16);
53
+ return `W/"${str.length.toString(16)}-${hash}"`;
54
+ }
55
+
56
+ export {
57
+ buildDeterministicKey,
58
+ shouldSkipCache,
59
+ generateETag
60
+ };
@@ -0,0 +1,196 @@
1
+ // src/edge/hono.ts
2
+ async function computeEdgeETag(text) {
3
+ try {
4
+ if (typeof crypto !== "undefined" && crypto.subtle) {
5
+ const encoder = new TextEncoder();
6
+ const data = encoder.encode(text);
7
+ const hashBuf = await crypto.subtle.digest("SHA-1", data);
8
+ const hashArr = Array.from(new Uint8Array(hashBuf));
9
+ const hashHex = hashArr.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
10
+ return `W/"${text.length.toString(16)}-${hashHex}"`;
11
+ }
12
+ } catch {
13
+ }
14
+ let h = 0;
15
+ for (let i = 0; i < text.length; i++) {
16
+ h = Math.imul(31, h) + text.charCodeAt(i) | 0;
17
+ }
18
+ return `W/"${text.length.toString(16)}-${Math.abs(h).toString(16)}"`;
19
+ }
20
+ function buildEdgeDeterministicKey(c, options) {
21
+ if (options?.keyGenerator) {
22
+ return options.keyGenerator(c);
23
+ }
24
+ const req = c.req;
25
+ const method = (req.method || "GET").toUpperCase();
26
+ const rawUrl = req.url || "/";
27
+ const qIdx = rawUrl.indexOf("?");
28
+ const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
29
+ let queryString = "";
30
+ if (qIdx >= 0) {
31
+ const rawQuery = rawUrl.slice(qIdx + 1);
32
+ try {
33
+ const params = new URLSearchParams(rawQuery);
34
+ params.sort();
35
+ queryString = params.toString();
36
+ } catch {
37
+ queryString = rawQuery;
38
+ }
39
+ }
40
+ let key = `edge:http:${method}:${path}`;
41
+ if (queryString) {
42
+ key += `?${queryString}`;
43
+ }
44
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.header) {
45
+ const sortedHeaders = [...options.headerWhitelist].sort();
46
+ for (const h of sortedHeaders) {
47
+ const val = req.header(h);
48
+ if (val !== void 0 && val !== null && val !== "") {
49
+ key += `|h:${h.toLowerCase()}=${val}`;
50
+ }
51
+ }
52
+ }
53
+ return key;
54
+ }
55
+ var NonCacheableEdgeResponseError = class extends Error {
56
+ constructor(response) {
57
+ super(`Non-cacheable status: ${response.status}`);
58
+ this.response = response;
59
+ this.name = "NonCacheableEdgeResponseError";
60
+ }
61
+ response;
62
+ isNonCacheable = true;
63
+ };
64
+ function honoEdgeCache(options = {}) {
65
+ const {
66
+ cache,
67
+ etag = true,
68
+ ttl = 300,
69
+ swr,
70
+ tags,
71
+ skipCache,
72
+ keyGenerator,
73
+ headerWhitelist
74
+ } = options;
75
+ return async (c, next) => {
76
+ const method = c.req.method;
77
+ if (method !== "GET" && method !== "HEAD") {
78
+ return await next();
79
+ }
80
+ if (skipCache && skipCache(c)) {
81
+ return await next();
82
+ }
83
+ const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
84
+ if (typeof cc === "string") {
85
+ const lower = cc.toLowerCase();
86
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
87
+ return await next();
88
+ }
89
+ }
90
+ if (!cache) {
91
+ return await next();
92
+ }
93
+ const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
94
+ const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
95
+ const resolvedTags = typeof tags === "function" ? tags(c) : tags;
96
+ let ranNext = false;
97
+ try {
98
+ const cached = await cache.get(
99
+ key,
100
+ async () => {
101
+ ranNext = true;
102
+ await next();
103
+ const res = c.res;
104
+ if (!res) {
105
+ return null;
106
+ }
107
+ const contentType = res.headers?.get?.("content-type") || "text/plain; charset=utf-8";
108
+ if (contentType.toLowerCase().includes("text/event-stream")) {
109
+ throw new NonCacheableEdgeResponseError({
110
+ body: "",
111
+ contentType,
112
+ status: 0
113
+ });
114
+ }
115
+ const cc2 = res.headers?.get?.("cache-control");
116
+ if (cc2) {
117
+ const lowerCc = cc2.toLowerCase();
118
+ if (lowerCc.includes("no-store") || lowerCc.includes("no-cache") || lowerCc.includes("private")) {
119
+ throw new NonCacheableEdgeResponseError({
120
+ body: "",
121
+ contentType,
122
+ status: 0
123
+ });
124
+ }
125
+ }
126
+ const statusCode = res.status ?? 200;
127
+ if (statusCode < 200 || statusCode >= 300 || statusCode === 206) {
128
+ throw new NonCacheableEdgeResponseError({
129
+ body: "",
130
+ contentType,
131
+ status: statusCode
132
+ });
133
+ }
134
+ const clone = res.clone();
135
+ const text = await clone.text();
136
+ const bodyEtag = etag ? await computeEdgeETag(text) : void 0;
137
+ const capturedHeaders = {};
138
+ if (res.headers && typeof res.headers.forEach === "function") {
139
+ res.headers.forEach((value, name) => {
140
+ const lower = name.toLowerCase();
141
+ if (lower !== "content-length" && lower !== "transfer-encoding" && lower !== "connection" && lower !== "etag" && lower !== "content-type") {
142
+ capturedHeaders[name] = value;
143
+ }
144
+ });
145
+ }
146
+ const snapshot = {
147
+ body: text,
148
+ contentType,
149
+ headers: capturedHeaders,
150
+ etag: bodyEtag,
151
+ status: statusCode
152
+ };
153
+ return snapshot;
154
+ },
155
+ ttl,
156
+ {
157
+ swr,
158
+ tags: resolvedTags,
159
+ ctx: c.executionCtx
160
+ }
161
+ );
162
+ if (!cached) {
163
+ return;
164
+ }
165
+ if (cached.etag && ifNoneMatch === cached.etag) {
166
+ const notModifiedHeaders = { ETag: cached.etag };
167
+ if (cached.headers?.["cache-control"]) notModifiedHeaders["Cache-Control"] = cached.headers["cache-control"];
168
+ if (cached.headers?.["vary"]) notModifiedHeaders["Vary"] = cached.headers["vary"];
169
+ return applyEdgeResponse(c, null, 304, notModifiedHeaders);
170
+ }
171
+ const headers = { ...cached.headers };
172
+ if (cached.etag) headers["ETag"] = cached.etag;
173
+ if (cached.contentType) headers["Content-Type"] = cached.contentType;
174
+ return applyEdgeResponse(c, cached.body, cached.status ?? 200, headers);
175
+ } catch (err) {
176
+ if (err instanceof NonCacheableEdgeResponseError) {
177
+ if (!ranNext) {
178
+ return await next();
179
+ }
180
+ return;
181
+ }
182
+ throw err;
183
+ }
184
+ };
185
+ }
186
+ function applyEdgeResponse(c, body, status, headers) {
187
+ const response = c.body(body, status, headers);
188
+ c.res = response;
189
+ return response;
190
+ }
191
+
192
+ export {
193
+ computeEdgeETag,
194
+ buildEdgeDeterministicKey,
195
+ honoEdgeCache
196
+ };