tricache 1.0.1 → 2.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.
Files changed (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,93 @@
1
+ import { C as CacheService } from '../cache-service-BV5T8-20.cjs';
2
+ import { W as WrapOptions } from '../types-F8vRWMrE.cjs';
3
+ import { K as KeyDerivationOptions } from '../utils-Bvzn-rKS.cjs';
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: (...args: any[]) => any;
44
+ executionCtx?: unknown;
45
+ }
46
+ type HonoNext = () => Promise<void>;
47
+ type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<Response | void>;
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
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
60
+ swr?: number;
61
+ }
62
+ interface CachedHonoResponse {
63
+ body: string;
64
+ contentType?: string;
65
+ headers?: Record<string, string>;
66
+ etag?: string;
67
+ status: number;
68
+ }
69
+ /**
70
+ * Creates a Hono middleware that caches GET/HEAD responses through Node
71
+ * `CacheService`, with Express-aligned ttl/tags/SWR options, weak ETags, and
72
+ * RFC 7232 `If-None-Match` → `304 Not Modified`. Non-2xx, 206 Partial Content,
73
+ * private/no-store, and streaming SSE responses are never kept.
74
+ *
75
+ * @example
76
+ * import { Hono } from 'hono';
77
+ * import { CacheService } from 'tricache';
78
+ * import { cacheMiddleware } from 'tricache/hono';
79
+ *
80
+ * const app = new Hono();
81
+ * const cache = CacheService.create();
82
+ *
83
+ * app.get(
84
+ * '/api/posts',
85
+ * cacheMiddleware({ cache, ttl: 300, tags: ['posts'] }),
86
+ * (c) => c.json({ data: '...' }),
87
+ * );
88
+ */
89
+ declare function cacheMiddleware(options?: HonoCacheOptions): HonoMiddleware;
90
+ /** Alias matching `createExpressMiddleware` / `createKoaMiddleware` naming. */
91
+ declare const createHonoMiddleware: typeof cacheMiddleware;
92
+
93
+ export { type CachedHonoResponse, type HonoCacheContext, type HonoCacheOptions, type HonoMiddleware, type HonoNext, cacheMiddleware, createHonoMiddleware };
@@ -1,6 +1,6 @@
1
- import { C as CacheService } from '../cache-service-CREOp7MM.js';
2
- import { W as WrapOptions } from '../types-Dyip5wAl.js';
3
- import { K as KeyDerivationOptions } from '../utils-CEsU_Z0s.js';
1
+ import { C as CacheService } from '../cache-service-tpyrXvlH.js';
2
+ import { W as WrapOptions } from '../types-F8vRWMrE.js';
3
+ import { K as KeyDerivationOptions } from '../utils-Bvzn-rKS.js';
4
4
  import 'crypto';
5
5
 
6
6
  /**
@@ -40,11 +40,11 @@ interface HonoCacheContext {
40
40
  };
41
41
  body?: unknown;
42
42
  };
43
- body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
43
+ body: (...args: any[]) => any;
44
44
  executionCtx?: unknown;
45
45
  }
46
46
  type HonoNext = () => Promise<void>;
47
- type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
47
+ type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<Response | void>;
48
48
  interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
49
49
  /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
50
50
  cache?: CacheService;
@@ -56,6 +56,8 @@ interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivation
56
56
  skipCache?: (c: HonoCacheContext) => boolean;
57
57
  /** Dynamic tags derivation from the Hono context. */
58
58
  tags?: string[] | ((c: HonoCacheContext) => string[]);
59
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
60
+ swr?: number;
59
61
  }
60
62
  interface CachedHonoResponse {
61
63
  body: string;
@@ -1,14 +1,16 @@
1
1
  import {
2
2
  buildDeterministicKey,
3
3
  generateETag,
4
+ isShareableHttpResponse,
5
+ matchesETag,
4
6
  shouldSkipCache
5
- } from "../chunk-BQRURGGD.js";
7
+ } from "../chunk-RBJRTGFK.js";
6
8
 
7
9
  // src/hono/index.ts
8
10
  function readRequestHeader(c, name) {
9
11
  const headerFn = c.req.header;
10
12
  if (typeof headerFn === "function") {
11
- const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
13
+ const viaFn = headerFn.call(c.req, name) ?? headerFn.call(c.req, name.toLowerCase());
12
14
  if (viaFn !== void 0 && viaFn !== null && viaFn !== "") {
13
15
  return viaFn;
14
16
  }
@@ -28,6 +30,10 @@ function toRequestLike(c, headerWhitelist) {
28
30
  const headers = {};
29
31
  const cacheControl = readRequestHeader(c, "cache-control");
30
32
  const ifNoneMatch = readRequestHeader(c, "if-none-match");
33
+ for (const name of ["authorization", "cookie", "range", "x-api-key", "x-auth-token"]) {
34
+ const value = readRequestHeader(c, name);
35
+ if (value) headers[name] = value;
36
+ }
31
37
  if (cacheControl) {
32
38
  headers["cache-control"] = cacheControl;
33
39
  headers["Cache-Control"] = cacheControl;
@@ -56,7 +62,7 @@ function hasNoStoreDirective(cacheControl) {
56
62
  return lower.includes("no-store") || lower.includes("no-cache") || lower.includes("private");
57
63
  }
58
64
  function applyHonoCachedResponse(c, cached, ifNoneMatch) {
59
- if (cached.etag && ifNoneMatch === cached.etag) {
65
+ if (cached.etag && matchesETag(ifNoneMatch, cached.etag)) {
60
66
  const notModifiedHeaders = { ETag: cached.etag };
61
67
  if (cached.headers?.["cache-control"]) notModifiedHeaders["Cache-Control"] = cached.headers["cache-control"];
62
68
  if (cached.headers?.["vary"]) notModifiedHeaders["Vary"] = cached.headers["vary"];
@@ -75,7 +81,7 @@ function applyHonoCachedResponse(c, cached, ifNoneMatch) {
75
81
  }
76
82
  return result;
77
83
  }
78
- async function snapshotHonoResponse(c, etag) {
84
+ async function snapshotHonoResponse(c, etag, options) {
79
85
  const res = c.res;
80
86
  if (!res) {
81
87
  return { body: "", status: 0 };
@@ -89,6 +95,7 @@ async function snapshotHonoResponse(c, etag) {
89
95
  return { body: "", contentType, status: 0 };
90
96
  }
91
97
  const status = res.status ?? 200;
98
+ if (!isShareableHttpResponse(status, (name) => res.headers?.get?.(name), options)) return { body: "", contentType, status: 0 };
92
99
  if (!isCacheableStatus(status)) {
93
100
  return { body: "", contentType, status };
94
101
  }
@@ -126,7 +133,6 @@ function cacheMiddleware(options = {}) {
126
133
  cache,
127
134
  etag = true,
128
135
  ttl = 300,
129
- swr,
130
136
  tags,
131
137
  skipCache,
132
138
  keyGenerator,
@@ -139,11 +145,11 @@ function cacheMiddleware(options = {}) {
139
145
  return await next();
140
146
  }
141
147
  const reqLike = toRequestLike(c, headerWhitelist);
142
- if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : void 0)) {
148
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : void 0, { ...options, keyGenerator: keyGenerator ? () => keyGenerator(c) : void 0 })) {
143
149
  return await next();
144
150
  }
145
151
  if (!resolvedCache) {
146
- const { CacheService } = await import("../cache-service-MG7PN6MX.js");
152
+ const { CacheService } = await import("../cache-service-UZXOQGEY.js");
147
153
  resolvedCache = CacheService.create();
148
154
  }
149
155
  const activeCache = resolvedCache;
@@ -157,14 +163,15 @@ function cacheMiddleware(options = {}) {
157
163
  async () => {
158
164
  ranNext = true;
159
165
  await next();
160
- const snapshot = await snapshotHonoResponse(c, etag);
166
+ const snapshot = await snapshotHonoResponse(c, etag, { headerWhitelist, keyGenerator: keyGenerator ? () => keyGenerator(c) : void 0 });
161
167
  if (!isCacheableStatus(snapshot.status)) {
162
168
  throw new NonCacheableHonoResponseError(snapshot);
163
169
  }
164
170
  return snapshot;
165
171
  },
166
172
  ttl,
167
- { swr, tags: resolvedTags }
173
+ // Never invoke a completed Hono next() chain from background work.
174
+ { swr: 0, tags: resolvedTags }
168
175
  );
169
176
  return applyHonoCachedResponse(c, cached, ifNoneMatch);
170
177
  } catch (err) {
@@ -0,0 +1,404 @@
1
+ import { I as ICacheTracer, a as InvalidateTagOptions } from './types-F8vRWMrE.cjs';
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
+ /** Enumerate complete keys under a literal prefix in bounded pages. Required for remote wildcard tags. */
20
+ scanKeys?(prefix: string): AsyncIterable<string>;
21
+ /** Counter semantics; Workers KV is eventually consistent, not an atomic authority. */
22
+ readonly tagConsistency?: 'atomic' | 'eventual';
23
+ /** Optional atomic or monotonic tag increment. The service supplies the complete typed storage key; adapters must use it unchanged. */
24
+ incrementTagVersion?(tag: string): Promise<number>;
25
+ /** Optional tag version retrieval by complete typed storage key. */
26
+ getTagVersion?(tag: string): Promise<number>;
27
+ /** Optional batch tag retrieval; result keys must match the complete supplied storage keys. */
28
+ batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
29
+ }
30
+ /**
31
+ * Options for cache read operations in Edge environments.
32
+ */
33
+ interface EdgeGetOptions {
34
+ /** Cache tags associated with this entry for bulk invalidation. */
35
+ tags?: string[];
36
+ /**
37
+ * Stale-While-Revalidate window in seconds.
38
+ * If entry is older than TTL but within (TTL + swr), stale data is returned
39
+ * immediately while a background fetcher runs to refresh the cache.
40
+ */
41
+ swr?: number;
42
+ /**
43
+ * Execution context provided by Edge platforms (Cloudflare Workers, Vercel Edge).
44
+ * Critical: In edge isolates, background tasks spawned without ctx.waitUntil()
45
+ * are terminated as soon as the HTTP response terminates.
46
+ */
47
+ ctx?: {
48
+ waitUntil: (promise: Promise<unknown>) => void;
49
+ };
50
+ }
51
+ /**
52
+ * Options for configuring the EdgeCacheService.
53
+ */
54
+ interface EdgeCacheOptions {
55
+ /**
56
+ * Maximum number of keys held in L1 in-memory LRU. Default: 10,000.
57
+ */
58
+ maxKeys?: number;
59
+ /**
60
+ * Approximate maximum memory in bytes for L1 cache (calculated via UTF-8 length * 2).
61
+ * Default: 32 MB (33,554,432 bytes).
62
+ */
63
+ maxBytes?: number;
64
+ /** Default TTL in seconds when not specified on get/set. Default: 300 (5 min). */
65
+ defaultTtlSeconds?: number;
66
+ /** Optional remote L2 storage adapter (Upstash, Cloudflare KV, Cloudflare DO). */
67
+ remoteStorage?: IEdgeRemoteStorage;
68
+ /** Optional at-rest encryption configuration via Web Crypto (AES-GCM). */
69
+ encryption?: {
70
+ keyBase64: string;
71
+ prevKeyBase64?: string;
72
+ mode?: 'aes-256-gcm' | 'aes-128-gcm';
73
+ };
74
+ /** Namespace encoded into a v3 storage keyspace with disjoint data/tag domains. Upgrades start cold; coordinate writers. Use a separate namespace from Node, whose value format differs. */
75
+ namespace?: string;
76
+ /** OpenTelemetry-compatible tracer for distributed tracing. */
77
+ tracer?: ICacheTracer;
78
+ /**
79
+ * Optional Bloom filter to defend against remote storage penetration on guaranteed misses.
80
+ * - `true`: automatically instantiates a default `WasmBloomFilter` (or `Murmur3BloomFilter` fallback).
81
+ * - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
82
+ */
83
+ bloomFilter?: boolean | IEdgeBloomFilter;
84
+ /** Only enable when the filter is an externally maintained, complete remote key set. Default: false. */
85
+ bloomFilterAuthoritative?: boolean;
86
+ }
87
+ /**
88
+ * Common contract for Edge-compatible Bloom filters (WASM or pure TypeScript Murmur3).
89
+ */
90
+ interface IEdgeBloomFilter {
91
+ add(key: string): void;
92
+ mightContain(key: string): boolean;
93
+ reset(): void;
94
+ rebuild?(keys: Iterable<string>): void;
95
+ readonly insertions?: number;
96
+ readonly maxCapacity?: number;
97
+ readonly stats?: {
98
+ bitsSet: number;
99
+ fillFactor: number;
100
+ };
101
+ }
102
+ /**
103
+ * Configuration for Upstash REST Redis adapter.
104
+ */
105
+ interface UpstashRedisOptions {
106
+ /** Upstash REST URL (e.g. "https://us1-clean-slug-12345.upstash.io"). */
107
+ url: string;
108
+ /** Upstash REST bearer token. */
109
+ token: string;
110
+ /** Optional custom fetch implementation (defaults to globalThis.fetch). */
111
+ fetch?: typeof globalThis.fetch;
112
+ /** Allow an explicit unscoped clear() to execute FLUSHDB. Default: false. */
113
+ dangerouslyFlushDatabase?: boolean;
114
+ }
115
+ /**
116
+ * Minimal interface representing Cloudflare Workers KVNamespace binding.
117
+ */
118
+ interface CloudflareKVNamespace {
119
+ get(key: string, options?: {
120
+ type?: 'text' | 'json' | 'arrayBuffer' | 'stream';
121
+ cacheTtl?: number;
122
+ }): Promise<string | null>;
123
+ put(key: string, value: string, options?: {
124
+ expirationTtl?: number;
125
+ metadata?: unknown;
126
+ }): Promise<void>;
127
+ delete(key: string): Promise<void>;
128
+ list?(options?: {
129
+ prefix?: string;
130
+ limit?: number;
131
+ cursor?: string;
132
+ }): Promise<{
133
+ keys: Array<{
134
+ name: string;
135
+ expiration?: number;
136
+ metadata?: unknown;
137
+ }>;
138
+ list_complete: boolean;
139
+ cursor?: string;
140
+ }>;
141
+ }
142
+ /**
143
+ * Minimal interface representing Cloudflare Durable Objects storage binding (state.storage).
144
+ */
145
+ interface CloudflareDOStorage {
146
+ get<T = unknown>(key: string): Promise<T | undefined>;
147
+ get<T = unknown>(keys: string[]): Promise<Map<string, T>>;
148
+ put<T = unknown>(key: string, value: T): Promise<void>;
149
+ put<T = unknown>(entries: Record<string, T>): Promise<void>;
150
+ delete(key: string): Promise<boolean>;
151
+ delete(keys: string[]): Promise<number>;
152
+ list?<T = unknown>(options?: {
153
+ prefix?: string;
154
+ limit?: number;
155
+ startAfter?: string;
156
+ }): Promise<Map<string, T>>;
157
+ }
158
+ /**
159
+ * Minimal interface representing a Cloudflare R2 object returned by R2Bucket.get().
160
+ */
161
+ interface CloudflareR2Object {
162
+ text(): Promise<string>;
163
+ arrayBuffer(): Promise<ArrayBuffer>;
164
+ json?<T = unknown>(): Promise<T>;
165
+ }
166
+ /**
167
+ * Minimal interface representing Cloudflare R2 Bucket binding (env.MY_BUCKET).
168
+ */
169
+ interface CloudflareR2Bucket {
170
+ get(key: string): Promise<CloudflareR2Object | null>;
171
+ put(key: string, value: string | ArrayBuffer | ArrayBufferView | Blob | ReadableStream, options?: unknown): Promise<unknown>;
172
+ delete?(key: string | string[]): Promise<void>;
173
+ }
174
+ /**
175
+ * Generic source for edge snapshot hydration (R2 bucket binding, custom loader object, raw string, or ArrayBuffer).
176
+ */
177
+ type EdgeSnapshotSource = CloudflareR2Bucket | {
178
+ get(key: string): Promise<CloudflareR2Object | string | ArrayBuffer | Uint8Array | null>;
179
+ } | string | ArrayBuffer | Uint8Array;
180
+ /**
181
+ * Configuration options for EdgeCacheService.hydrate().
182
+ */
183
+ interface EdgeHydrateOptions {
184
+ /**
185
+ * Object key or filename in the R2 bucket. Default: 'tricache-edge.snap'
186
+ */
187
+ key?: string;
188
+ /**
189
+ * Maximum acceptable age of snapshot in milliseconds before rejecting as stale.
190
+ * Default: 7,200,000 ms (2 hours).
191
+ */
192
+ maxAgeMs?: number;
193
+ /**
194
+ * Acceptable clock skew tolerance in milliseconds for future timestamps.
195
+ * Default: 250 ms.
196
+ */
197
+ clockSkewToleranceMs?: number;
198
+ }
199
+ /**
200
+ * Configuration options for EdgeCacheService.exportSnapshot().
201
+ */
202
+ interface EdgeExportSnapshotOptions {
203
+ /**
204
+ * Whether to encrypt the exported snapshot using the configured Web Crypto AEAD key.
205
+ * Default: true (when encryption is configured).
206
+ */
207
+ encrypt?: boolean;
208
+ }
209
+ /**
210
+ * Serialized representation of edge cache snapshot payload.
211
+ */
212
+ interface EdgeSnapshotPayload {
213
+ version: number;
214
+ /** Encoded storage namespace identity, not the raw namespace option. */
215
+ namespace: string;
216
+ writtenAt: number;
217
+ entries: Array<{
218
+ key: string;
219
+ value: unknown;
220
+ expiresAt: number;
221
+ staleUntil: number;
222
+ tags?: string[];
223
+ tagVersions?: Record<string, number>;
224
+ }>;
225
+ }
226
+
227
+ /**
228
+ * Enterprise-grade cache service designed specifically for pure V8 Edge Isolates
229
+ * (Cloudflare Workers, Fastly Compute, Vercel Edge, Next.js Edge Runtime, Deno).
230
+ *
231
+ * Characteristics:
232
+ * - Zero Node.js dependencies (no node:fs, node:v8, node:net, worker_threads)
233
+ * - Dual-bounded LRU with zero background intervals (allows isolates to suspend cleanly)
234
+ * - In-flight Promise Coalescing (prevents thundering herd on edge cold starts)
235
+ * - Edge-safe Stale-While-Revalidate with ctx.waitUntil() isolation fence
236
+ * - Web Crypto AEAD at-rest encryption cross-compatible with Node.js
237
+ * - OpenTelemetry semantic conventions instrumentation
238
+ */
239
+ declare class EdgeCacheService {
240
+ private readonly maxKeys;
241
+ private readonly maxBytes;
242
+ private readonly defaultTtl;
243
+ private readonly namespace;
244
+ private readonly namespacePrefix;
245
+ private readonly dataPrefix;
246
+ private readonly tagVersionPrefix;
247
+ private readonly remoteStorage;
248
+ private readonly enc;
249
+ private readonly tracer;
250
+ private readonly bloomFilter;
251
+ private readonly bloomAuthoritative;
252
+ private globalEpoch;
253
+ private lastGlobalMutationAt;
254
+ private readonly keyEpochs;
255
+ private readonly l1;
256
+ private currentBytes;
257
+ private readonly inflight;
258
+ private readonly tagIndex;
259
+ private static readonly MAX_TAG_VERSION_CACHE;
260
+ private readonly tagVersionCache;
261
+ private readonly tagVersionTtlMs;
262
+ constructor(options?: EdgeCacheOptions);
263
+ /**
264
+ * Active Bloom filter instance defending against cold miss penetration, or null.
265
+ */
266
+ get bloom(): IEdgeBloomFilter | null;
267
+ private nk;
268
+ private tagVersionKey;
269
+ private _estimateBytes;
270
+ private fence;
271
+ private mutate;
272
+ private invalidateWork;
273
+ private storeL1;
274
+ private commit;
275
+ private _evictIfNeeded;
276
+ private _deleteL1;
277
+ private _startSpan;
278
+ private _setTagVersionCache;
279
+ private _getTagVersion;
280
+ private _batchGetTagVersions;
281
+ /**
282
+ * Reads or fetches a value by key.
283
+ */
284
+ get<T>(key: string, fetchFn?: () => Promise<T>, ttlSeconds?: number, options?: EdgeGetOptions): Promise<T | null>;
285
+ private _revalidate;
286
+ /**
287
+ * Sets a value in the cache with an optional TTL and tags.
288
+ */
289
+ set<T>(key: string, value: T, ttlSeconds?: number, options?: {
290
+ tags?: string[];
291
+ swr?: number;
292
+ } | string[]): Promise<void>;
293
+ /**
294
+ * Deletes a key from all tiers.
295
+ */
296
+ delete(key: string): Promise<void>;
297
+ /**
298
+ * Executes invalidation for a single already-resolved concrete tag without
299
+ * re-entering wildcard/cascade resolution.
300
+ */
301
+ private _invalidateConcreteTag;
302
+ /**
303
+ * Invalidates all cached entries associated with a tag.
304
+ */
305
+ invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
306
+ /**
307
+ * Clears all entries from the edge cache.
308
+ */
309
+ clear(): Promise<void>;
310
+ /**
311
+ * Batch get with miss-fetching.
312
+ */
313
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttlSeconds?: number): Promise<(T | null)[]>;
314
+ /**
315
+ * Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
316
+ * Ideal for persisting Edge state to Cloudflare R2 before worker restart.
317
+ */
318
+ exportSnapshot(options?: EdgeExportSnapshotOptions): Promise<string>;
319
+ /**
320
+ * Hydrates L1 memory and primes the Bloom filter directly from Cloudflare R2 or snapshot sources on edge isolate initialization.
321
+ *
322
+ * @param source Cloudflare R2 bucket binding (env.MY_BUCKET), reader object, snapshot string, or ArrayBuffer.
323
+ * @param options Configuration options (key, maxAgeMs, clockSkewToleranceMs).
324
+ * @returns Number of cache entries successfully restored into L1.
325
+ *
326
+ * @example
327
+ * // In Cloudflare Worker:
328
+ * export default {
329
+ * async fetch(request, env, ctx) {
330
+ * await edgeCache.hydrate(env.CACHE_R2_BUCKET);
331
+ * return handleRequest(request);
332
+ * }
333
+ * }
334
+ */
335
+ hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number>;
336
+ /**
337
+ * Diagnostic snapshot of edge cache memory usage.
338
+ */
339
+ stats(): {
340
+ keys: number;
341
+ bytes: number;
342
+ maxKeys: number;
343
+ maxBytes: number;
344
+ tags: number;
345
+ };
346
+ }
347
+
348
+ interface HonoEdgeCacheOptions {
349
+ /** EdgeCacheService instance. If omitted, requires explicit cache passing. */
350
+ cache?: EdgeCacheService | any;
351
+ /** Custom key generator. Defaults to deterministic method + URL + sorted query string. */
352
+ keyGenerator?: (c: any) => string;
353
+ /** Optional list of header names to include in the cache key. */
354
+ headerWhitelist?: string[];
355
+ /** Whether to generate and evaluate weak ETags. Default: true. */
356
+ etag?: boolean;
357
+ /** TTL in seconds. Default: 300. */
358
+ ttl?: number;
359
+ /** Cache tags for invalidation. */
360
+ tags?: string[] | ((c: any) => string[]);
361
+ /** Predicate to skip caching dynamically. */
362
+ skipCache?: (c: any) => boolean;
363
+ /** Authenticated responses require explicit opt-in and an identity-aware key. */
364
+ cacheAuthenticated?: boolean;
365
+ /** @deprecated Response refreshes run on live requests. Use EdgeCacheService.get() for data-level SWR. */
366
+ swr?: number;
367
+ }
368
+ interface CachedEdgeHttpResponse {
369
+ body: string;
370
+ contentType: string;
371
+ headers?: Record<string, string>;
372
+ etag?: string;
373
+ status: number;
374
+ }
375
+ /**
376
+ * Computes a weak ETag using Web Crypto API (crypto.subtle) without importing Node.js modules.
377
+ */
378
+ declare function computeEdgeETag(text: string): Promise<string>;
379
+ /**
380
+ * Generates a deterministic cache key from standard Web Request / Hono context.
381
+ */
382
+ declare function buildEdgeDeterministicKey(c: any, options?: {
383
+ keyGenerator?: (c: any) => string;
384
+ headerWhitelist?: string[];
385
+ }): string;
386
+ /**
387
+ * Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
388
+ *
389
+ * Operates strictly with Web Request/Response and Web Crypto APIs.
390
+ *
391
+ * @example
392
+ * import { Hono } from 'hono';
393
+ * import { EdgeCacheService, honoEdgeCache } from 'tricache/edge';
394
+ *
395
+ * const app = new Hono();
396
+ * const cache = new EdgeCacheService({ maxKeys: 10_000 });
397
+ *
398
+ * app.get('/api/feed', honoEdgeCache({ cache, ttl: 60 }), async (c) => {
399
+ * return c.json({ status: 'ok', timestamp: Date.now() });
400
+ * });
401
+ */
402
+ declare function honoEdgeCache(options?: HonoEdgeCacheOptions): (c: any, next: () => Promise<void>) => Promise<void | Response>;
403
+
404
+ 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 };