tricache 0.7.1 → 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.
- package/LICENSE +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +284 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +315 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { C as CacheService } from '../cache-service-DVvroyqA.js';
|
|
2
|
+
import { W as WrapOptions } from '../types-B_QkVwJ7.js';
|
|
3
|
+
import { K as KeyDerivationOptions } from '../utils-CEsU_Z0s.js';
|
|
4
|
+
import 'crypto';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* tricache/hono — first-class Node.js Hono middleware on CacheService.
|
|
8
|
+
*
|
|
9
|
+
* This is the Node three-tier path (L1 RAM → L1.5 disk → L2 Redis), not the
|
|
10
|
+
* Web-Crypto edge helper exported from `tricache/edge` / `tricache/http`.
|
|
11
|
+
*
|
|
12
|
+
* Usage:
|
|
13
|
+
* import { Hono } from 'hono';
|
|
14
|
+
* import { cacheMiddleware } from 'tricache/hono';
|
|
15
|
+
*
|
|
16
|
+
* const app = new Hono();
|
|
17
|
+
* app.get('/api/posts', cacheMiddleware({ ttl: 300, tags: ['posts'] }), (c) => {
|
|
18
|
+
* return c.json({ data: '...' });
|
|
19
|
+
* });
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Minimal Hono context surface used by the middleware.
|
|
24
|
+
* Compatible with `import('hono').Context` without taking a runtime dependency.
|
|
25
|
+
*/
|
|
26
|
+
interface HonoCacheContext {
|
|
27
|
+
req: {
|
|
28
|
+
method: string;
|
|
29
|
+
url: string;
|
|
30
|
+
header?: (name: string) => string | undefined;
|
|
31
|
+
headers?: Headers | Record<string, string | string[] | undefined>;
|
|
32
|
+
};
|
|
33
|
+
res?: {
|
|
34
|
+
status?: number;
|
|
35
|
+
headers?: {
|
|
36
|
+
get(name: string): string | null | undefined;
|
|
37
|
+
};
|
|
38
|
+
clone?: () => {
|
|
39
|
+
text: () => Promise<string>;
|
|
40
|
+
};
|
|
41
|
+
body?: unknown;
|
|
42
|
+
};
|
|
43
|
+
body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
|
|
44
|
+
executionCtx?: unknown;
|
|
45
|
+
}
|
|
46
|
+
type HonoNext = () => Promise<void>;
|
|
47
|
+
type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
|
|
48
|
+
interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
|
|
49
|
+
/** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
|
|
50
|
+
cache?: CacheService;
|
|
51
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
52
|
+
etag?: boolean;
|
|
53
|
+
/** Custom cache key. Overrides default method + URL + sorted query derivation. */
|
|
54
|
+
keyGenerator?: (c: HonoCacheContext) => string;
|
|
55
|
+
/** Custom predicate to skip caching dynamically (e.g. authenticated sessions). */
|
|
56
|
+
skipCache?: (c: HonoCacheContext) => boolean;
|
|
57
|
+
/** Dynamic tags derivation from the Hono context. */
|
|
58
|
+
tags?: string[] | ((c: HonoCacheContext) => string[]);
|
|
59
|
+
}
|
|
60
|
+
interface CachedHonoResponse {
|
|
61
|
+
body: string;
|
|
62
|
+
contentType?: string;
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
etag?: string;
|
|
65
|
+
status: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Creates a Hono middleware that caches GET/HEAD responses through Node
|
|
69
|
+
* `CacheService`, with Express-aligned ttl/tags/SWR options, weak ETags, and
|
|
70
|
+
* RFC 7232 `If-None-Match` → `304 Not Modified`. Non-2xx, 206 Partial Content,
|
|
71
|
+
* private/no-store, and streaming SSE responses are never kept.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* import { Hono } from 'hono';
|
|
75
|
+
* import { CacheService } from 'tricache';
|
|
76
|
+
* import { cacheMiddleware } from 'tricache/hono';
|
|
77
|
+
*
|
|
78
|
+
* const app = new Hono();
|
|
79
|
+
* const cache = CacheService.create();
|
|
80
|
+
*
|
|
81
|
+
* app.get(
|
|
82
|
+
* '/api/posts',
|
|
83
|
+
* cacheMiddleware({ cache, ttl: 300, tags: ['posts'] }),
|
|
84
|
+
* (c) => c.json({ data: '...' }),
|
|
85
|
+
* );
|
|
86
|
+
*/
|
|
87
|
+
declare function cacheMiddleware(options?: HonoCacheOptions): HonoMiddleware;
|
|
88
|
+
/** Alias matching `createExpressMiddleware` / `createKoaMiddleware` naming. */
|
|
89
|
+
declare const createHonoMiddleware: typeof cacheMiddleware;
|
|
90
|
+
|
|
91
|
+
export { type CachedHonoResponse, type HonoCacheContext, type HonoCacheOptions, type HonoMiddleware, type HonoNext, cacheMiddleware, createHonoMiddleware };
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildDeterministicKey,
|
|
3
|
+
generateETag,
|
|
4
|
+
shouldSkipCache
|
|
5
|
+
} from "../chunk-BQRURGGD.js";
|
|
6
|
+
|
|
7
|
+
// src/hono/index.ts
|
|
8
|
+
function readRequestHeader(c, name) {
|
|
9
|
+
const headerFn = c.req.header;
|
|
10
|
+
if (typeof headerFn === "function") {
|
|
11
|
+
const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
|
|
12
|
+
if (viaFn !== void 0 && viaFn !== null && viaFn !== "") {
|
|
13
|
+
return viaFn;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const raw = c.req.headers;
|
|
17
|
+
if (!raw) return void 0;
|
|
18
|
+
if (typeof raw.get === "function") {
|
|
19
|
+
const viaGet = raw.get(name);
|
|
20
|
+
if (viaGet) return viaGet;
|
|
21
|
+
}
|
|
22
|
+
const record = raw;
|
|
23
|
+
const val = record[name.toLowerCase()] ?? record[name];
|
|
24
|
+
if (val === void 0 || val === null || val === "") return void 0;
|
|
25
|
+
return Array.isArray(val) ? val.join(",") : String(val);
|
|
26
|
+
}
|
|
27
|
+
function toRequestLike(c, headerWhitelist) {
|
|
28
|
+
const headers = {};
|
|
29
|
+
const cacheControl = readRequestHeader(c, "cache-control");
|
|
30
|
+
const ifNoneMatch = readRequestHeader(c, "if-none-match");
|
|
31
|
+
if (cacheControl) {
|
|
32
|
+
headers["cache-control"] = cacheControl;
|
|
33
|
+
headers["Cache-Control"] = cacheControl;
|
|
34
|
+
}
|
|
35
|
+
if (ifNoneMatch) {
|
|
36
|
+
headers["if-none-match"] = ifNoneMatch;
|
|
37
|
+
headers["If-None-Match"] = ifNoneMatch;
|
|
38
|
+
}
|
|
39
|
+
if (headerWhitelist) {
|
|
40
|
+
for (const h of headerWhitelist) {
|
|
41
|
+
headers[h.toLowerCase()] = readRequestHeader(c, h);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
method: (c.req.method || "GET").toUpperCase(),
|
|
46
|
+
url: c.req.url || "/",
|
|
47
|
+
headers
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function isCacheableStatus(status) {
|
|
51
|
+
return status >= 200 && status < 300 && status !== 206;
|
|
52
|
+
}
|
|
53
|
+
function hasNoStoreDirective(cacheControl) {
|
|
54
|
+
if (!cacheControl) return false;
|
|
55
|
+
const lower = cacheControl.toLowerCase();
|
|
56
|
+
return lower.includes("no-store") || lower.includes("no-cache") || lower.includes("private");
|
|
57
|
+
}
|
|
58
|
+
function applyHonoCachedResponse(c, cached, ifNoneMatch) {
|
|
59
|
+
if (cached.etag && ifNoneMatch === cached.etag) {
|
|
60
|
+
const notModifiedHeaders = { ETag: cached.etag };
|
|
61
|
+
if (cached.headers?.["cache-control"]) notModifiedHeaders["Cache-Control"] = cached.headers["cache-control"];
|
|
62
|
+
if (cached.headers?.["vary"]) notModifiedHeaders["Vary"] = cached.headers["vary"];
|
|
63
|
+
const result2 = c.body(null, 304, notModifiedHeaders);
|
|
64
|
+
if (result2 != null) {
|
|
65
|
+
c.res = result2;
|
|
66
|
+
}
|
|
67
|
+
return result2;
|
|
68
|
+
}
|
|
69
|
+
const headers = { ...cached.headers };
|
|
70
|
+
if (cached.etag) headers["ETag"] = cached.etag;
|
|
71
|
+
if (cached.contentType) headers["Content-Type"] = cached.contentType;
|
|
72
|
+
const result = c.body(cached.body, cached.status ?? 200, headers);
|
|
73
|
+
if (result != null) {
|
|
74
|
+
c.res = result;
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
async function snapshotHonoResponse(c, etag) {
|
|
79
|
+
const res = c.res;
|
|
80
|
+
if (!res) {
|
|
81
|
+
return { body: "", status: 0 };
|
|
82
|
+
}
|
|
83
|
+
const contentType = res.headers?.get?.("content-type") || "text/plain; charset=utf-8";
|
|
84
|
+
if (contentType.toLowerCase().includes("text/event-stream")) {
|
|
85
|
+
return { body: "", contentType, status: 0 };
|
|
86
|
+
}
|
|
87
|
+
const cacheControl = res.headers?.get?.("cache-control");
|
|
88
|
+
if (hasNoStoreDirective(cacheControl)) {
|
|
89
|
+
return { body: "", contentType, status: 0 };
|
|
90
|
+
}
|
|
91
|
+
const status = res.status ?? 200;
|
|
92
|
+
if (!isCacheableStatus(status)) {
|
|
93
|
+
return { body: "", contentType, status };
|
|
94
|
+
}
|
|
95
|
+
const clone = typeof res.clone === "function" ? res.clone() : void 0;
|
|
96
|
+
const text = clone && typeof clone.text === "function" ? await clone.text() : typeof res.body === "string" ? res.body : "";
|
|
97
|
+
const bodyEtag = etag ? generateETag(text) : void 0;
|
|
98
|
+
const capturedHeaders = {};
|
|
99
|
+
if (res.headers && typeof res.headers.forEach === "function") {
|
|
100
|
+
res.headers.forEach((value, name) => {
|
|
101
|
+
const lower = name.toLowerCase();
|
|
102
|
+
if (lower !== "content-length" && lower !== "transfer-encoding" && lower !== "connection" && lower !== "etag" && lower !== "content-type") {
|
|
103
|
+
capturedHeaders[name] = value;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
body: text,
|
|
109
|
+
contentType,
|
|
110
|
+
headers: capturedHeaders,
|
|
111
|
+
etag: bodyEtag,
|
|
112
|
+
status
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
var NonCacheableHonoResponseError = class extends Error {
|
|
116
|
+
constructor(response) {
|
|
117
|
+
super(`Non-cacheable response: status=${response.status}`);
|
|
118
|
+
this.response = response;
|
|
119
|
+
this.name = "NonCacheableHonoResponseError";
|
|
120
|
+
}
|
|
121
|
+
response;
|
|
122
|
+
isNonCacheable = true;
|
|
123
|
+
};
|
|
124
|
+
function cacheMiddleware(options = {}) {
|
|
125
|
+
const {
|
|
126
|
+
cache,
|
|
127
|
+
etag = true,
|
|
128
|
+
ttl = 300,
|
|
129
|
+
swr,
|
|
130
|
+
tags,
|
|
131
|
+
skipCache,
|
|
132
|
+
keyGenerator,
|
|
133
|
+
headerWhitelist
|
|
134
|
+
} = options;
|
|
135
|
+
let resolvedCache = cache;
|
|
136
|
+
return async (c, next) => {
|
|
137
|
+
const method = (c.req.method || "GET").toUpperCase();
|
|
138
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
139
|
+
return await next();
|
|
140
|
+
}
|
|
141
|
+
const reqLike = toRequestLike(c, headerWhitelist);
|
|
142
|
+
if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : void 0)) {
|
|
143
|
+
return await next();
|
|
144
|
+
}
|
|
145
|
+
if (!resolvedCache) {
|
|
146
|
+
const { CacheService } = await import("../cache-service-KI5ACF3F.js");
|
|
147
|
+
resolvedCache = CacheService.create();
|
|
148
|
+
}
|
|
149
|
+
const activeCache = resolvedCache;
|
|
150
|
+
const key = keyGenerator ? keyGenerator(c) : buildDeterministicKey(reqLike, { headerWhitelist });
|
|
151
|
+
const ifNoneMatch = readRequestHeader(c, "if-none-match");
|
|
152
|
+
const resolvedTags = typeof tags === "function" ? tags(c) : tags;
|
|
153
|
+
let ranNext = false;
|
|
154
|
+
try {
|
|
155
|
+
const cached = await activeCache.get(
|
|
156
|
+
key,
|
|
157
|
+
async () => {
|
|
158
|
+
ranNext = true;
|
|
159
|
+
await next();
|
|
160
|
+
const snapshot = await snapshotHonoResponse(c, etag);
|
|
161
|
+
if (!isCacheableStatus(snapshot.status)) {
|
|
162
|
+
throw new NonCacheableHonoResponseError(snapshot);
|
|
163
|
+
}
|
|
164
|
+
return snapshot;
|
|
165
|
+
},
|
|
166
|
+
ttl,
|
|
167
|
+
{ swr, tags: resolvedTags }
|
|
168
|
+
);
|
|
169
|
+
return applyHonoCachedResponse(c, cached, ifNoneMatch);
|
|
170
|
+
} catch (err) {
|
|
171
|
+
if (err instanceof NonCacheableHonoResponseError) {
|
|
172
|
+
if (!ranNext) {
|
|
173
|
+
return await next();
|
|
174
|
+
}
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
throw err;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
var createHonoMiddleware = cacheMiddleware;
|
|
182
|
+
export {
|
|
183
|
+
cacheMiddleware,
|
|
184
|
+
createHonoMiddleware
|
|
185
|
+
};
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { I as ICacheTracer } from './types-B_QkVwJ7.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pluggable asynchronous key-value storage adapter for Edge runtimes (L2 tier).
|
|
5
|
+
*/
|
|
6
|
+
interface IEdgeRemoteStorage {
|
|
7
|
+
/** Fetch a stored value by key. Returns null on miss. */
|
|
8
|
+
get(key: string): Promise<string | null>;
|
|
9
|
+
/** Store a value with an optional TTL in seconds. */
|
|
10
|
+
set(key: string, value: string, ttlSeconds?: number): Promise<void>;
|
|
11
|
+
/** Delete a key. */
|
|
12
|
+
delete(key: string): Promise<void>;
|
|
13
|
+
/** Optional batch read. Returns array matching keys order (null for missing). */
|
|
14
|
+
mget?(keys: string[]): Promise<(string | null)[]>;
|
|
15
|
+
/** Optional batch write. */
|
|
16
|
+
mset?(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
|
|
17
|
+
/** Optional clear by prefix or all keys. */
|
|
18
|
+
clear?(prefix?: string): Promise<void>;
|
|
19
|
+
/** Optional atomic or monotonic tag version increment for generational tag invalidation. */
|
|
20
|
+
incrementTagVersion?(tag: string): Promise<number>;
|
|
21
|
+
/** Optional tag version retrieval. */
|
|
22
|
+
getTagVersion?(tag: string): Promise<number>;
|
|
23
|
+
/** Optional batch tag version retrieval. */
|
|
24
|
+
batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Options for cache read operations in Edge environments.
|
|
28
|
+
*/
|
|
29
|
+
interface EdgeGetOptions {
|
|
30
|
+
/** Cache tags associated with this entry for bulk invalidation. */
|
|
31
|
+
tags?: string[];
|
|
32
|
+
/**
|
|
33
|
+
* Stale-While-Revalidate window in seconds.
|
|
34
|
+
* If entry is older than TTL but within (TTL + swr), stale data is returned
|
|
35
|
+
* immediately while a background fetcher runs to refresh the cache.
|
|
36
|
+
*/
|
|
37
|
+
swr?: number;
|
|
38
|
+
/**
|
|
39
|
+
* Execution context provided by Edge platforms (Cloudflare Workers, Vercel Edge).
|
|
40
|
+
* Critical: In edge isolates, background tasks spawned without ctx.waitUntil()
|
|
41
|
+
* are terminated as soon as the HTTP response terminates.
|
|
42
|
+
*/
|
|
43
|
+
ctx?: {
|
|
44
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Options for configuring the EdgeCacheService.
|
|
49
|
+
*/
|
|
50
|
+
interface EdgeCacheOptions {
|
|
51
|
+
/**
|
|
52
|
+
* Maximum number of keys held in L1 in-memory LRU. Default: 10,000.
|
|
53
|
+
*/
|
|
54
|
+
maxKeys?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Approximate maximum memory in bytes for L1 cache (calculated via UTF-8 length * 2).
|
|
57
|
+
* Default: 32 MB (33,554,432 bytes).
|
|
58
|
+
*/
|
|
59
|
+
maxBytes?: number;
|
|
60
|
+
/** Default TTL in seconds when not specified on get/set. Default: 300 (5 min). */
|
|
61
|
+
defaultTtlSeconds?: number;
|
|
62
|
+
/** Optional remote L2 storage adapter (Upstash, Cloudflare KV, Cloudflare DO). */
|
|
63
|
+
remoteStorage?: IEdgeRemoteStorage;
|
|
64
|
+
/** Optional at-rest encryption configuration via Web Crypto (AES-GCM). */
|
|
65
|
+
encryption?: {
|
|
66
|
+
keyBase64: string;
|
|
67
|
+
prevKeyBase64?: string;
|
|
68
|
+
mode?: 'aes-256-gcm' | 'aes-128-gcm';
|
|
69
|
+
};
|
|
70
|
+
/** Multi-tenant key namespace prefix. */
|
|
71
|
+
namespace?: string;
|
|
72
|
+
/** OpenTelemetry-compatible tracer for distributed tracing. */
|
|
73
|
+
tracer?: ICacheTracer;
|
|
74
|
+
/**
|
|
75
|
+
* Optional Bloom filter to defend against remote storage penetration on guaranteed misses.
|
|
76
|
+
* - `true`: automatically instantiates a default `WasmBloomFilter` (or `Murmur3BloomFilter` fallback).
|
|
77
|
+
* - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
|
|
78
|
+
*/
|
|
79
|
+
bloomFilter?: boolean | IEdgeBloomFilter;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Common contract for Edge-compatible Bloom filters (WASM or pure TypeScript Murmur3).
|
|
83
|
+
*/
|
|
84
|
+
interface IEdgeBloomFilter {
|
|
85
|
+
add(key: string): void;
|
|
86
|
+
mightContain(key: string): boolean;
|
|
87
|
+
reset(): void;
|
|
88
|
+
rebuild?(keys: Iterable<string>): void;
|
|
89
|
+
readonly insertions?: number;
|
|
90
|
+
readonly maxCapacity?: number;
|
|
91
|
+
readonly stats?: {
|
|
92
|
+
bitsSet: number;
|
|
93
|
+
fillFactor: number;
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Configuration for Upstash REST Redis adapter.
|
|
98
|
+
*/
|
|
99
|
+
interface UpstashRedisOptions {
|
|
100
|
+
/** Upstash REST URL (e.g. "https://us1-clean-slug-12345.upstash.io"). */
|
|
101
|
+
url: string;
|
|
102
|
+
/** Upstash REST bearer token. */
|
|
103
|
+
token: string;
|
|
104
|
+
/** Optional custom fetch implementation (defaults to globalThis.fetch). */
|
|
105
|
+
fetch?: typeof globalThis.fetch;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Minimal interface representing Cloudflare Workers KVNamespace binding.
|
|
109
|
+
*/
|
|
110
|
+
interface CloudflareKVNamespace {
|
|
111
|
+
get(key: string, options?: {
|
|
112
|
+
type?: 'text' | 'json' | 'arrayBuffer' | 'stream';
|
|
113
|
+
cacheTtl?: number;
|
|
114
|
+
}): Promise<string | null>;
|
|
115
|
+
put(key: string, value: string, options?: {
|
|
116
|
+
expirationTtl?: number;
|
|
117
|
+
metadata?: unknown;
|
|
118
|
+
}): Promise<void>;
|
|
119
|
+
delete(key: string): Promise<void>;
|
|
120
|
+
list?(options?: {
|
|
121
|
+
prefix?: string;
|
|
122
|
+
limit?: number;
|
|
123
|
+
cursor?: string;
|
|
124
|
+
}): Promise<{
|
|
125
|
+
keys: Array<{
|
|
126
|
+
name: string;
|
|
127
|
+
expiration?: number;
|
|
128
|
+
metadata?: unknown;
|
|
129
|
+
}>;
|
|
130
|
+
list_complete: boolean;
|
|
131
|
+
cursor?: string;
|
|
132
|
+
}>;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Minimal interface representing Cloudflare Durable Objects storage binding (state.storage).
|
|
136
|
+
*/
|
|
137
|
+
interface CloudflareDOStorage {
|
|
138
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
139
|
+
get<T = unknown>(keys: string[]): Promise<Map<string, T>>;
|
|
140
|
+
put<T = unknown>(key: string, value: T): Promise<void>;
|
|
141
|
+
put<T = unknown>(entries: Record<string, T>): Promise<void>;
|
|
142
|
+
delete(key: string): Promise<boolean>;
|
|
143
|
+
delete(keys: string[]): Promise<number>;
|
|
144
|
+
list?<T = unknown>(options?: {
|
|
145
|
+
prefix?: string;
|
|
146
|
+
limit?: number;
|
|
147
|
+
}): Promise<Map<string, T>>;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Minimal interface representing a Cloudflare R2 object returned by R2Bucket.get().
|
|
151
|
+
*/
|
|
152
|
+
interface CloudflareR2Object {
|
|
153
|
+
text(): Promise<string>;
|
|
154
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
155
|
+
json?<T = unknown>(): Promise<T>;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Minimal interface representing Cloudflare R2 Bucket binding (env.MY_BUCKET).
|
|
159
|
+
*/
|
|
160
|
+
interface CloudflareR2Bucket {
|
|
161
|
+
get(key: string): Promise<CloudflareR2Object | null>;
|
|
162
|
+
put(key: string, value: string | ArrayBuffer | ArrayBufferView | Blob | ReadableStream, options?: unknown): Promise<unknown>;
|
|
163
|
+
delete?(key: string | string[]): Promise<void>;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Generic source for edge snapshot hydration (R2 bucket binding, custom loader object, raw string, or ArrayBuffer).
|
|
167
|
+
*/
|
|
168
|
+
type EdgeSnapshotSource = CloudflareR2Bucket | {
|
|
169
|
+
get(key: string): Promise<CloudflareR2Object | string | ArrayBuffer | Uint8Array | null>;
|
|
170
|
+
} | string | ArrayBuffer | Uint8Array;
|
|
171
|
+
/**
|
|
172
|
+
* Configuration options for EdgeCacheService.hydrate().
|
|
173
|
+
*/
|
|
174
|
+
interface EdgeHydrateOptions {
|
|
175
|
+
/**
|
|
176
|
+
* Object key or filename in the R2 bucket. Default: 'tricache-edge.snap'
|
|
177
|
+
*/
|
|
178
|
+
key?: string;
|
|
179
|
+
/**
|
|
180
|
+
* Maximum acceptable age of snapshot in milliseconds before rejecting as stale.
|
|
181
|
+
* Default: 7,200,000 ms (2 hours).
|
|
182
|
+
*/
|
|
183
|
+
maxAgeMs?: number;
|
|
184
|
+
/**
|
|
185
|
+
* Acceptable clock skew tolerance in milliseconds for future timestamps.
|
|
186
|
+
* Default: 250 ms.
|
|
187
|
+
*/
|
|
188
|
+
clockSkewToleranceMs?: number;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Configuration options for EdgeCacheService.exportSnapshot().
|
|
192
|
+
*/
|
|
193
|
+
interface EdgeExportSnapshotOptions {
|
|
194
|
+
/**
|
|
195
|
+
* Whether to encrypt the exported snapshot using the configured Web Crypto AEAD key.
|
|
196
|
+
* Default: true (when encryption is configured).
|
|
197
|
+
*/
|
|
198
|
+
encrypt?: boolean;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Serialized representation of edge cache snapshot payload.
|
|
202
|
+
*/
|
|
203
|
+
interface EdgeSnapshotPayload {
|
|
204
|
+
version: number;
|
|
205
|
+
writtenAt: number;
|
|
206
|
+
entries: Array<{
|
|
207
|
+
key: string;
|
|
208
|
+
value: unknown;
|
|
209
|
+
expiresAt: number;
|
|
210
|
+
staleUntil: number;
|
|
211
|
+
tags?: string[];
|
|
212
|
+
tagVersions?: Record<string, number>;
|
|
213
|
+
}>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Enterprise-grade cache service designed specifically for pure V8 Edge Isolates
|
|
218
|
+
* (Cloudflare Workers, Fastly Compute, Vercel Edge, Next.js Edge Runtime, Deno).
|
|
219
|
+
*
|
|
220
|
+
* Characteristics:
|
|
221
|
+
* - Zero Node.js dependencies (no node:fs, node:v8, node:net, worker_threads)
|
|
222
|
+
* - Dual-bounded LRU with zero background intervals (allows isolates to suspend cleanly)
|
|
223
|
+
* - In-flight Promise Coalescing (prevents thundering herd on edge cold starts)
|
|
224
|
+
* - Edge-safe Stale-While-Revalidate with ctx.waitUntil() isolation fence
|
|
225
|
+
* - Web Crypto AEAD at-rest encryption cross-compatible with Node.js
|
|
226
|
+
* - OpenTelemetry semantic conventions instrumentation
|
|
227
|
+
*/
|
|
228
|
+
declare class EdgeCacheService {
|
|
229
|
+
private readonly maxKeys;
|
|
230
|
+
private readonly maxBytes;
|
|
231
|
+
private readonly defaultTtl;
|
|
232
|
+
private readonly namespace;
|
|
233
|
+
private readonly remoteStorage;
|
|
234
|
+
private readonly enc;
|
|
235
|
+
private readonly tracer;
|
|
236
|
+
private readonly bloomFilter;
|
|
237
|
+
private readonly l1;
|
|
238
|
+
private currentBytes;
|
|
239
|
+
private readonly inflight;
|
|
240
|
+
private readonly tagIndex;
|
|
241
|
+
private readonly tagVersionCache;
|
|
242
|
+
private readonly tagVersionTtlMs;
|
|
243
|
+
constructor(options?: EdgeCacheOptions);
|
|
244
|
+
/**
|
|
245
|
+
* Active Bloom filter instance defending against cold miss penetration, or null.
|
|
246
|
+
*/
|
|
247
|
+
get bloom(): IEdgeBloomFilter | null;
|
|
248
|
+
private nk;
|
|
249
|
+
private _estimateBytes;
|
|
250
|
+
private _evictIfNeeded;
|
|
251
|
+
private _deleteL1;
|
|
252
|
+
private _startSpan;
|
|
253
|
+
private _getTagVersion;
|
|
254
|
+
private _batchGetTagVersions;
|
|
255
|
+
/**
|
|
256
|
+
* Reads or fetches a value by key.
|
|
257
|
+
*/
|
|
258
|
+
get<T>(key: string, fetchFn?: () => Promise<T>, ttlSeconds?: number, options?: EdgeGetOptions): Promise<T | null>;
|
|
259
|
+
private _revalidate;
|
|
260
|
+
/**
|
|
261
|
+
* Sets a value in the cache with an optional TTL and tags.
|
|
262
|
+
*/
|
|
263
|
+
set<T>(key: string, value: T, ttlSeconds?: number, options?: {
|
|
264
|
+
tags?: string[];
|
|
265
|
+
swr?: number;
|
|
266
|
+
}): Promise<void>;
|
|
267
|
+
/**
|
|
268
|
+
* Deletes a key from all tiers.
|
|
269
|
+
*/
|
|
270
|
+
delete(key: string): Promise<void>;
|
|
271
|
+
/**
|
|
272
|
+
* Invalidates all cached entries associated with a tag.
|
|
273
|
+
*/
|
|
274
|
+
invalidateTag(tag: string): Promise<void>;
|
|
275
|
+
/**
|
|
276
|
+
* Clears all entries from the edge cache.
|
|
277
|
+
*/
|
|
278
|
+
clear(): Promise<void>;
|
|
279
|
+
/**
|
|
280
|
+
* Batch get with miss-fetching.
|
|
281
|
+
*/
|
|
282
|
+
mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>, ttlSeconds?: number): Promise<(T | null)[]>;
|
|
283
|
+
/**
|
|
284
|
+
* Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
|
|
285
|
+
* Ideal for persisting Edge state to Cloudflare R2 before worker restart.
|
|
286
|
+
*/
|
|
287
|
+
exportSnapshot(options?: EdgeExportSnapshotOptions): Promise<string>;
|
|
288
|
+
/**
|
|
289
|
+
* Hydrates L1 memory and primes the Bloom filter directly from Cloudflare R2 or snapshot sources on edge isolate initialization.
|
|
290
|
+
*
|
|
291
|
+
* @param source Cloudflare R2 bucket binding (env.MY_BUCKET), reader object, snapshot string, or ArrayBuffer.
|
|
292
|
+
* @param options Configuration options (key, maxAgeMs, clockSkewToleranceMs).
|
|
293
|
+
* @returns Number of cache entries successfully restored into L1.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* // In Cloudflare Worker:
|
|
297
|
+
* export default {
|
|
298
|
+
* async fetch(request, env, ctx) {
|
|
299
|
+
* await edgeCache.hydrate(env.CACHE_R2_BUCKET);
|
|
300
|
+
* return handleRequest(request);
|
|
301
|
+
* }
|
|
302
|
+
* }
|
|
303
|
+
*/
|
|
304
|
+
hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number>;
|
|
305
|
+
/**
|
|
306
|
+
* Diagnostic snapshot of edge cache memory usage.
|
|
307
|
+
*/
|
|
308
|
+
stats(): {
|
|
309
|
+
keys: number;
|
|
310
|
+
bytes: number;
|
|
311
|
+
maxKeys: number;
|
|
312
|
+
maxBytes: number;
|
|
313
|
+
tags: number;
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
interface HonoEdgeCacheOptions {
|
|
318
|
+
/** EdgeCacheService instance. If omitted, requires explicit cache passing. */
|
|
319
|
+
cache?: EdgeCacheService | any;
|
|
320
|
+
/** Custom key generator. Defaults to deterministic method + URL + sorted query string. */
|
|
321
|
+
keyGenerator?: (c: any) => string;
|
|
322
|
+
/** Optional list of header names to include in the cache key. */
|
|
323
|
+
headerWhitelist?: string[];
|
|
324
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
325
|
+
etag?: boolean;
|
|
326
|
+
/** TTL in seconds. Default: 300. */
|
|
327
|
+
ttl?: number;
|
|
328
|
+
/** Stale-While-Revalidate window in seconds. Default: undefined. */
|
|
329
|
+
swr?: number;
|
|
330
|
+
/** Cache tags for invalidation. */
|
|
331
|
+
tags?: string[] | ((c: any) => string[]);
|
|
332
|
+
/** Predicate to skip caching dynamically. */
|
|
333
|
+
skipCache?: (c: any) => boolean;
|
|
334
|
+
}
|
|
335
|
+
interface CachedEdgeHttpResponse {
|
|
336
|
+
body: string;
|
|
337
|
+
contentType: string;
|
|
338
|
+
headers?: Record<string, string>;
|
|
339
|
+
etag?: string;
|
|
340
|
+
status: number;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Computes a weak ETag using Web Crypto API (crypto.subtle) without importing Node.js modules.
|
|
344
|
+
*/
|
|
345
|
+
declare function computeEdgeETag(text: string): Promise<string>;
|
|
346
|
+
/**
|
|
347
|
+
* Generates a deterministic cache key from standard Web Request / Hono context.
|
|
348
|
+
*/
|
|
349
|
+
declare function buildEdgeDeterministicKey(c: any, options?: {
|
|
350
|
+
keyGenerator?: (c: any) => string;
|
|
351
|
+
headerWhitelist?: string[];
|
|
352
|
+
}): string;
|
|
353
|
+
/**
|
|
354
|
+
* Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
|
|
355
|
+
*
|
|
356
|
+
* Operates strictly with Web Request/Response and Web Crypto APIs.
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* import { Hono } from 'hono';
|
|
360
|
+
* import { EdgeCacheService, honoEdgeCache } from 'tricache/edge';
|
|
361
|
+
*
|
|
362
|
+
* const app = new Hono();
|
|
363
|
+
* const cache = new EdgeCacheService({ maxKeys: 10_000 });
|
|
364
|
+
*
|
|
365
|
+
* app.get('/api/feed', honoEdgeCache({ cache, ttl: 60 }), async (c) => {
|
|
366
|
+
* return c.json({ status: 'ok', timestamp: Date.now() });
|
|
367
|
+
* });
|
|
368
|
+
*/
|
|
369
|
+
declare function honoEdgeCache(options?: HonoEdgeCacheOptions): (c: any, next: () => Promise<void>) => Promise<void | Response>;
|
|
370
|
+
|
|
371
|
+
export { type CachedEdgeHttpResponse as C, type EdgeCacheOptions as E, type HonoEdgeCacheOptions as H, type IEdgeRemoteStorage as I, type UpstashRedisOptions as U, type CloudflareKVNamespace as a, buildEdgeDeterministicKey as b, computeEdgeETag as c, type CloudflareDOStorage as d, type CloudflareR2Bucket as e, type CloudflareR2Object as f, EdgeCacheService as g, honoEdgeCache as h, type EdgeExportSnapshotOptions as i, type EdgeGetOptions as j, type EdgeHydrateOptions as k, type EdgeSnapshotPayload as l, type EdgeSnapshotSource as m, type IEdgeBloomFilter as n };
|