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.
- package/README.md +89 -93
- package/dashboards/tricache-alerts.yaml +80 -4
- package/dashboards/tricache-grafana.json +54 -1
- package/dashboards/tricache-inventory.rules.yml +21 -0
- package/dist/cache-service-BV5T8-20.d.cts +1064 -0
- package/dist/cache-service-UZXOQGEY.js +14 -0
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
- package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
- package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
- package/dist/chunk-RBJRTGFK.js +94 -0
- package/dist/chunk-S5N65I45.js +17 -0
- package/dist/cli.cjs +3694 -1070
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +210 -14
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +3578 -1068
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +6 -2
- package/dist/edge/index.cjs +368 -162
- package/dist/edge/index.d.cts +134 -0
- package/dist/edge/index.d.ts +11 -4
- package/dist/edge/index.js +314 -155
- package/dist/hono/index.cjs +3614 -1087
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/hono-CMv2VdQ6.d.cts +404 -0
- package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
- package/dist/http/index.cjs +3712 -1124
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +4067 -1252
- package/dist/index.d.cts +1071 -0
- package/dist/index.d.ts +123 -27
- package/dist/index.js +878 -21
- package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
- package/dist/murmur3-DF8BFRnu.d.ts +99 -0
- package/dist/nestjs/index.cjs +3635 -1112
- package/dist/nestjs/index.d.cts +299 -0
- package/dist/nestjs/index.d.ts +120 -33
- package/dist/nestjs/index.js +132 -43
- package/dist/next/index.cjs +3704 -1175
- package/dist/next/index.d.cts +238 -0
- package/dist/next/index.d.ts +39 -11
- package/dist/next/index.js +202 -102
- package/dist/prisma/index.cjs +29 -18
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +17 -18
- package/dist/serialize-worker.cjs +162 -39
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.js +9 -7
- package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
- package/dist/types-F8vRWMrE.d.ts +1636 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +116 -37
- package/src/adapters/auto-pipeliner.ts +150 -26
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +2215 -793
- package/src/cli.ts +25 -14
- package/src/codec.ts +3 -3
- package/src/compression.ts +39 -16
- package/src/cross-region.ts +22 -4
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +448 -102
- package/src/drizzle/index.ts +2 -1
- package/src/edge/adapters/cloudflare-do.ts +25 -10
- package/src/edge/adapters/cloudflare-kv.ts +12 -9
- package/src/edge/adapters/upstash.ts +27 -11
- package/src/edge/cache.ts +200 -110
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +17 -5
- package/src/encryption.ts +50 -18
- package/src/env.d.ts +1 -1
- package/src/errors.ts +12 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +60 -20
- package/src/index.ts +6 -0
- package/src/ipc-telemetry.ts +35 -9
- package/src/latency-watchdog.ts +5 -1
- package/src/nestjs/decorators.ts +11 -6
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +15 -12
- package/src/nestjs/tricache.store.ts +69 -26
- package/src/nestjs/types.ts +30 -16
- package/src/next/cache-handler.ts +151 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +25 -0
- package/src/origin-capacity.ts +134 -0
- package/src/prisma/index.ts +17 -24
- package/src/remote-snapshot.ts +37 -27
- package/src/serialize-worker.ts +8 -5
- package/src/sigv4-snapshot-adapter.ts +37 -27
- package/src/smart-memory-cache.ts +121 -44
- package/src/types.ts +117 -37
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/config-comparison.ts +29 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/lz4-size.ts +74 -0
- package/src/utils/namespace-key.ts +48 -0
- package/src/utils/query-key.ts +13 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/utils/snapshot-transfer.ts +83 -0
- package/src/utils/work-limits.ts +73 -0
- package/src/utils/write-revision.ts +4 -0
- package/src/wasm/bloom-filter-wasm.ts +25 -5
- package/src/worker-pool.ts +44 -15
- package/src/wtiny-lfu.ts +82 -20
- package/dist/cache-service-MG7PN6MX.js +0 -12
- package/dist/chunk-3I5L7K6I.js +0 -704
- package/dist/chunk-BQRURGGD.js +0 -60
package/src/edge/cache.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { WebCryptoEncryption } from './crypto';
|
|
|
14
14
|
import { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
|
|
15
15
|
import { Murmur3BloomFilter } from './utils/murmur3';
|
|
16
16
|
import { isWildcardTag, matchesTagPattern, isChildTag } from '../utils/tag-matcher';
|
|
17
|
+
import { namespaceDomainPrefix, namespaceKeyPrefix } from '../utils/namespace-key';
|
|
17
18
|
|
|
18
19
|
interface EdgeL1Entry<T = unknown> {
|
|
19
20
|
value: T;
|
|
@@ -25,6 +26,8 @@ interface EdgeL1Entry<T = unknown> {
|
|
|
25
26
|
tagVersions?: Record<string, number>;
|
|
26
27
|
}
|
|
27
28
|
|
|
29
|
+
const NAMESPACE_TAG = '_tricache_namespace_';
|
|
30
|
+
|
|
28
31
|
/**
|
|
29
32
|
* Enterprise-grade cache service designed specifically for pure V8 Edge Isolates
|
|
30
33
|
* (Cloudflare Workers, Fastly Compute, Vercel Edge, Next.js Edge Runtime, Deno).
|
|
@@ -42,10 +45,17 @@ export class EdgeCacheService {
|
|
|
42
45
|
private readonly maxBytes: number;
|
|
43
46
|
private readonly defaultTtl: number;
|
|
44
47
|
private readonly namespace: string;
|
|
48
|
+
private readonly namespacePrefix: string;
|
|
49
|
+
private readonly dataPrefix: string;
|
|
50
|
+
private readonly tagVersionPrefix: string;
|
|
45
51
|
private readonly remoteStorage: IEdgeRemoteStorage | null;
|
|
46
52
|
private readonly enc: WebCryptoEncryption;
|
|
47
53
|
private readonly tracer: ICacheTracer | null;
|
|
48
54
|
private readonly bloomFilter: IEdgeBloomFilter | null;
|
|
55
|
+
private readonly bloomAuthoritative: boolean;
|
|
56
|
+
private globalEpoch = 0;
|
|
57
|
+
private lastGlobalMutationAt = 0;
|
|
58
|
+
private readonly keyEpochs = new Map<string, number>();
|
|
49
59
|
|
|
50
60
|
// L1 Dual-bounded LRU
|
|
51
61
|
private readonly l1 = new Map<string, EdgeL1Entry>();
|
|
@@ -67,9 +77,15 @@ export class EdgeCacheService {
|
|
|
67
77
|
this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024; // 32 MB
|
|
68
78
|
this.defaultTtl = options?.defaultTtlSeconds ?? 300;
|
|
69
79
|
this.namespace = options?.namespace?.trim() ?? '';
|
|
80
|
+
this.namespacePrefix = namespaceKeyPrefix(this.namespace);
|
|
81
|
+
this.dataPrefix = namespaceDomainPrefix(this.namespace, 'data');
|
|
82
|
+
this.tagVersionPrefix = namespaceDomainPrefix(this.namespace, 'tag-version');
|
|
70
83
|
this.remoteStorage = options?.remoteStorage ?? null;
|
|
71
84
|
this.tracer = options?.tracer ?? null;
|
|
72
85
|
this.enc = new WebCryptoEncryption(options?.encryption);
|
|
86
|
+
this.bloomAuthoritative = options?.bloomFilterAuthoritative ?? false;
|
|
87
|
+
if (!Number.isInteger(this.maxKeys) || this.maxKeys < 0 || !Number.isFinite(this.maxBytes) || this.maxBytes < 0 ||
|
|
88
|
+
!Number.isFinite(this.defaultTtl) || this.defaultTtl < 0) throw new Error('Edge cache limits and TTL must be finite non-negative values');
|
|
73
89
|
|
|
74
90
|
if (options?.bloomFilter === true) {
|
|
75
91
|
try {
|
|
@@ -92,7 +108,11 @@ export class EdgeCacheService {
|
|
|
92
108
|
}
|
|
93
109
|
|
|
94
110
|
private nk(key: string): string {
|
|
95
|
-
return
|
|
111
|
+
return `${this.dataPrefix}${key}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private tagVersionKey(tag: string): string {
|
|
115
|
+
return `${this.tagVersionPrefix}${tag}`;
|
|
96
116
|
}
|
|
97
117
|
|
|
98
118
|
private _estimateBytes(key: string, serialized: string): number {
|
|
@@ -100,6 +120,56 @@ export class EdgeCacheService {
|
|
|
100
120
|
return (key.length + serialized.length) * 2 + 64;
|
|
101
121
|
}
|
|
102
122
|
|
|
123
|
+
private fence(key: string): string { return `${this.globalEpoch}:${this.keyEpochs.get(key) ?? 0}`; }
|
|
124
|
+
private mutate(key: string): void {
|
|
125
|
+
this.keyEpochs.set(key, (this.keyEpochs.get(key) ?? 0) + 1);
|
|
126
|
+
this.inflight.delete(key);
|
|
127
|
+
if (this.keyEpochs.size > 50000) { this.globalEpoch++; this.keyEpochs.clear(); }
|
|
128
|
+
}
|
|
129
|
+
private invalidateWork(): void {
|
|
130
|
+
this.globalEpoch++;
|
|
131
|
+
this.lastGlobalMutationAt = Date.now();
|
|
132
|
+
this.inflight.clear();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private storeL1(key: string, entry: EdgeL1Entry): boolean {
|
|
136
|
+
this._deleteL1(key);
|
|
137
|
+
if (entry.bytes > this.maxBytes || this.maxKeys === 0 || entry.staleUntil <= Date.now()) return false;
|
|
138
|
+
this._evictIfNeeded(entry.bytes);
|
|
139
|
+
this.l1.set(key, entry);
|
|
140
|
+
this.currentBytes += entry.bytes;
|
|
141
|
+
for (const tag of entry.tags ?? []) {
|
|
142
|
+
const members = this.tagIndex.get(tag) ?? new Set<string>();
|
|
143
|
+
members.add(key);
|
|
144
|
+
this.tagIndex.set(tag, members);
|
|
145
|
+
}
|
|
146
|
+
this.bloomFilter?.add(key);
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private async commit<T>(key: string, value: T, ttl: number, options: EdgeGetOptions | undefined,
|
|
151
|
+
versions: Record<string, number>, epoch: string): Promise<void> {
|
|
152
|
+
const namespaced = this.nk(key);
|
|
153
|
+
if (this.fence(namespaced) !== epoch) return;
|
|
154
|
+
const serialized = JSON.stringify(value);
|
|
155
|
+
if (serialized === undefined) return; // Undefined is not a JSON cache value.
|
|
156
|
+
const now = Date.now();
|
|
157
|
+
const entry: EdgeL1Entry<T> = { value, serialized, bytes: this._estimateBytes(namespaced, serialized),
|
|
158
|
+
expiresAt: now + ttl * 1000, staleUntil: now + (ttl + (options?.swr ?? 0)) * 1000,
|
|
159
|
+
tags: options?.tags ? [...new Set(options.tags)] : undefined, tagVersions: versions };
|
|
160
|
+
this.storeL1(namespaced, entry);
|
|
161
|
+
if (this.remoteStorage) {
|
|
162
|
+
// Independent immutable markers never overwrite a concurrent generation.
|
|
163
|
+
const registry = namespaceDomainPrefix(this.namespace, 'tag-registry');
|
|
164
|
+
for (const tag of entry.tags ?? []) await this.remoteStorage.set(`${registry}${tag}`, '1');
|
|
165
|
+
const envelope = JSON.stringify({ __t_edge: 2, __t_val: value, __t_tv: versions, __t_exp: entry.expiresAt,
|
|
166
|
+
__t_stale: entry.staleUntil, __t_tags: entry.tags });
|
|
167
|
+
const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
|
|
168
|
+
if (this.fence(namespaced) !== epoch) return;
|
|
169
|
+
await this.remoteStorage.set(namespaced, payload, ttl + (options?.swr ?? 0));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
103
173
|
private _evictIfNeeded(newBytes: number): void {
|
|
104
174
|
// 1. Evict based on byte ceiling
|
|
105
175
|
while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
|
|
@@ -161,7 +231,8 @@ export class EdgeCacheService {
|
|
|
161
231
|
if (oldestKey !== undefined) this.tagVersionCache.delete(oldestKey);
|
|
162
232
|
}
|
|
163
233
|
}
|
|
164
|
-
this.tagVersionCache.
|
|
234
|
+
const known = this.tagVersionCache.get(tag)?.version ?? 0;
|
|
235
|
+
this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
|
|
165
236
|
}
|
|
166
237
|
|
|
167
238
|
private async _getTagVersion(tag: string): Promise<number> {
|
|
@@ -174,9 +245,9 @@ export class EdgeCacheService {
|
|
|
174
245
|
if (this.remoteStorage) {
|
|
175
246
|
try {
|
|
176
247
|
if (typeof this.remoteStorage.getTagVersion === 'function') {
|
|
177
|
-
version = await this.remoteStorage.getTagVersion(this.
|
|
248
|
+
version = await this.remoteStorage.getTagVersion(this.tagVersionKey(tag));
|
|
178
249
|
} else {
|
|
179
|
-
const raw = await this.remoteStorage.get(this.
|
|
250
|
+
const raw = await this.remoteStorage.get(this.tagVersionKey(tag));
|
|
180
251
|
version = raw ? parseInt(raw, 10) || 1 : 1;
|
|
181
252
|
}
|
|
182
253
|
} catch {
|
|
@@ -186,12 +257,12 @@ export class EdgeCacheService {
|
|
|
186
257
|
version = cached?.version ?? 1;
|
|
187
258
|
}
|
|
188
259
|
this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
|
|
189
|
-
return version;
|
|
260
|
+
return this.tagVersionCache.get(tag)?.version ?? version;
|
|
190
261
|
}
|
|
191
262
|
|
|
192
263
|
private async _batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
|
|
193
264
|
const now = Date.now();
|
|
194
|
-
const result: Record<string, number> =
|
|
265
|
+
const result: Record<string, number> = Object.create(null);
|
|
195
266
|
const missingTags: string[] = [];
|
|
196
267
|
|
|
197
268
|
for (const t of tags) {
|
|
@@ -206,12 +277,12 @@ export class EdgeCacheService {
|
|
|
206
277
|
if (missingTags.length > 0 && this.remoteStorage) {
|
|
207
278
|
try {
|
|
208
279
|
if (typeof this.remoteStorage.batchGetTagVersions === 'function') {
|
|
209
|
-
const nsTags = missingTags.map(t => this.
|
|
280
|
+
const nsTags = missingTags.map(t => this.tagVersionKey(t));
|
|
210
281
|
const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
|
|
211
282
|
for (let i = 0; i < missingTags.length; i++) {
|
|
212
283
|
const t = missingTags[i];
|
|
213
|
-
const v = remoteVersions[this.
|
|
214
|
-
result[t] = v;
|
|
284
|
+
const v = remoteVersions[this.tagVersionKey(t)] ?? 1;
|
|
285
|
+
result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
|
|
215
286
|
this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
|
|
216
287
|
}
|
|
217
288
|
} else {
|
|
@@ -246,7 +317,7 @@ export class EdgeCacheService {
|
|
|
246
317
|
const span = this._startSpan('tricache.get');
|
|
247
318
|
span.setAttribute('cache.key', key);
|
|
248
319
|
const nsKey = this.nk(key);
|
|
249
|
-
|
|
320
|
+
let now = Date.now();
|
|
250
321
|
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
251
322
|
|
|
252
323
|
try {
|
|
@@ -265,6 +336,7 @@ export class EdgeCacheService {
|
|
|
265
336
|
}
|
|
266
337
|
}
|
|
267
338
|
}
|
|
339
|
+
now = Date.now();
|
|
268
340
|
|
|
269
341
|
if (isTagStale) {
|
|
270
342
|
this._deleteL1(nsKey);
|
|
@@ -281,14 +353,14 @@ export class EdgeCacheService {
|
|
|
281
353
|
return l1Entry.value as T;
|
|
282
354
|
}
|
|
283
355
|
|
|
284
|
-
if (l1Entry.staleUntil > now && fetchFn) {
|
|
356
|
+
if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
|
|
285
357
|
// Stale hit — trigger background revalidation
|
|
286
358
|
span.setAttribute('cache.hit', true);
|
|
287
359
|
span.setAttribute('cache.item.tier', 'memory');
|
|
288
360
|
span.setAttribute('cache.hit_tier', 'l1');
|
|
289
361
|
span.setAttribute('cache.stale', true);
|
|
290
362
|
|
|
291
|
-
const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
|
|
363
|
+
const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
|
|
292
364
|
if (options?.ctx?.waitUntil) {
|
|
293
365
|
options.ctx.waitUntil(revalPromise);
|
|
294
366
|
}
|
|
@@ -296,13 +368,21 @@ export class EdgeCacheService {
|
|
|
296
368
|
}
|
|
297
369
|
|
|
298
370
|
// Hard expired in L1
|
|
299
|
-
this._deleteL1(nsKey);
|
|
371
|
+
if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
|
|
300
372
|
}
|
|
301
373
|
}
|
|
302
374
|
|
|
303
|
-
|
|
375
|
+
const existing = this.inflight.get(nsKey);
|
|
376
|
+
if (existing) {
|
|
377
|
+
span.setAttribute('cache.stampede_coalesced', true);
|
|
378
|
+
return await existing as T;
|
|
379
|
+
}
|
|
380
|
+
const epoch = this.fence(nsKey);
|
|
381
|
+
const execution: Promise<T | null> = Promise.resolve().then(async () => {
|
|
382
|
+
try {
|
|
383
|
+
// A local Bloom filter cannot prove that another isolate's remote key is absent.
|
|
304
384
|
if (this.remoteStorage) {
|
|
305
|
-
if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
|
|
385
|
+
if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
|
|
306
386
|
span.setAttribute('cache.bloom.filtered', true);
|
|
307
387
|
} else {
|
|
308
388
|
try {
|
|
@@ -317,6 +397,8 @@ export class EdgeCacheService {
|
|
|
317
397
|
if (parsedJson && typeof parsedJson === 'object' && '__t_val' in parsedJson && '__t_tv' in parsedJson) {
|
|
318
398
|
parsed = parsedJson.__t_val as T;
|
|
319
399
|
activeTagVersions = parsedJson.__t_tv as Record<string, number>;
|
|
400
|
+
if (!activeTagVersions || typeof activeTagVersions !== 'object' || Array.isArray(activeTagVersions) ||
|
|
401
|
+
Object.values(activeTagVersions).some(version => !Number.isSafeInteger(version) || version < 0)) throw new Error('Invalid remote tag versions');
|
|
320
402
|
const tagNames = Object.keys(activeTagVersions);
|
|
321
403
|
const currentVers = await this._batchGetTagVersions(tagNames);
|
|
322
404
|
for (const tag of tagNames) {
|
|
@@ -330,13 +412,30 @@ export class EdgeCacheService {
|
|
|
330
412
|
}
|
|
331
413
|
|
|
332
414
|
if (!isStaleRemote) {
|
|
333
|
-
|
|
334
|
-
|
|
415
|
+
const freshUntil = Number(parsedJson?.__t_exp);
|
|
416
|
+
const staleUntil = Number(parsedJson?.__t_stale);
|
|
417
|
+
const versioned = parsedJson?.__t_edge === 2 && Number.isFinite(freshUntil) && Number.isFinite(staleUntil) && staleUntil >= freshUntil;
|
|
418
|
+
if (versioned && (staleUntil <= Date.now() || freshUntil <= Date.now() && (!(options?.swr ?? 0) || !fetchFn))) {
|
|
419
|
+
isStaleRemote = true;
|
|
420
|
+
} else {
|
|
421
|
+
// Promote without rewriting Redis/KV, resetting expiry, or discarding tags.
|
|
422
|
+
if (versioned && this.fence(nsKey) === epoch) {
|
|
423
|
+
const serialized = JSON.stringify(parsed);
|
|
424
|
+
const tags = Array.isArray(parsedJson.__t_tags) ? parsedJson.__t_tags : Object.keys(activeTagVersions ?? {}).filter(tag => tag !== NAMESPACE_TAG);
|
|
425
|
+
this.storeL1(nsKey, { value: parsed, serialized, bytes: this._estimateBytes(nsKey, serialized),
|
|
426
|
+
expiresAt: freshUntil, staleUntil, tags, tagVersions: activeTagVersions });
|
|
427
|
+
if (freshUntil <= Date.now() && fetchFn) {
|
|
428
|
+
const refresh = execution.then(() => this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags }));
|
|
429
|
+
options?.ctx?.waitUntil(refresh);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
// Legacy raw JSON has no trustworthy remaining TTL: read it but do not promote it.
|
|
335
433
|
|
|
336
434
|
span.setAttribute('cache.hit', true);
|
|
337
435
|
span.setAttribute('cache.item.tier', 'remote');
|
|
338
436
|
span.setAttribute('cache.hit_tier', 'l2');
|
|
339
437
|
return parsed;
|
|
438
|
+
}
|
|
340
439
|
}
|
|
341
440
|
}
|
|
342
441
|
} catch (remoteErr) {
|
|
@@ -352,30 +451,22 @@ export class EdgeCacheService {
|
|
|
352
451
|
return null;
|
|
353
452
|
}
|
|
354
453
|
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
try {
|
|
363
|
-
const fresh = await fetchFn();
|
|
364
|
-
await this.set(key, fresh, resolvedTtl, options);
|
|
365
|
-
return fresh;
|
|
366
|
-
} finally {
|
|
367
|
-
this.inflight.delete(nsKey);
|
|
368
|
-
}
|
|
369
|
-
})();
|
|
370
|
-
this.inflight.set(nsKey, inflightPromise);
|
|
454
|
+
const tags = [...new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
|
|
455
|
+
const versions = await this._batchGetTagVersions(tags);
|
|
456
|
+
const fresh = await fetchFn();
|
|
457
|
+
const current = await this._batchGetTagVersions(tags);
|
|
458
|
+
if (this.fence(nsKey) === epoch && tags.every(tag => current[tag] === versions[tag])) {
|
|
459
|
+
try { await this.commit(key, fresh, resolvedTtl, options, versions, epoch); }
|
|
460
|
+
catch (error) { span.recordException?.(error); } // Origin reads remain available during cache outages.
|
|
371
461
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
462
|
+
span.setAttribute('cache.hit', false).setAttribute('cache.hit_tier', 'miss');
|
|
463
|
+
return fresh;
|
|
464
|
+
} finally {
|
|
465
|
+
if (this.inflight.get(nsKey) === execution) this.inflight.delete(nsKey);
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
this.inflight.set(nsKey, execution);
|
|
469
|
+
return await execution;
|
|
379
470
|
} catch (err) {
|
|
380
471
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
381
472
|
span.recordException?.(err);
|
|
@@ -394,16 +485,20 @@ export class EdgeCacheService {
|
|
|
394
485
|
const nsKey = this.nk(key);
|
|
395
486
|
if (this.inflight.has(nsKey)) return;
|
|
396
487
|
|
|
397
|
-
const
|
|
488
|
+
const epoch = this.fence(nsKey);
|
|
489
|
+
const task = Promise.resolve().then(async () => {
|
|
398
490
|
try {
|
|
491
|
+
const tags = [...new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
|
|
492
|
+
const versions = await this._batchGetTagVersions(tags);
|
|
399
493
|
const fresh = await fetchFn();
|
|
400
|
-
await this.
|
|
494
|
+
const current = await this._batchGetTagVersions(tags);
|
|
495
|
+
if (this.fence(nsKey) === epoch && tags.every(tag => current[tag] === versions[tag])) await this.commit(key, fresh, ttl, options, versions, epoch);
|
|
401
496
|
} catch {
|
|
402
497
|
// Suppress background revalidation error to prevent unhandled rejection
|
|
403
498
|
} finally {
|
|
404
|
-
this.inflight.delete(nsKey);
|
|
499
|
+
if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
|
|
405
500
|
}
|
|
406
|
-
})
|
|
501
|
+
});
|
|
407
502
|
|
|
408
503
|
this.inflight.set(nsKey, task);
|
|
409
504
|
await task;
|
|
@@ -421,62 +516,16 @@ export class EdgeCacheService {
|
|
|
421
516
|
const span = this._startSpan('tricache.set');
|
|
422
517
|
span.setAttribute('cache.key', key);
|
|
423
518
|
const nsKey = this.nk(key);
|
|
519
|
+
this.mutate(nsKey);
|
|
520
|
+
const epoch = this.fence(nsKey);
|
|
424
521
|
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
425
|
-
const now = Date.now();
|
|
426
522
|
const optObj = Array.isArray(options) ? { tags: options } : options;
|
|
427
523
|
const swrSeconds = optObj?.swr ?? 0;
|
|
428
524
|
|
|
429
525
|
try {
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const serialized = JSON.stringify(value);
|
|
436
|
-
const bytes = this._estimateBytes(nsKey, serialized);
|
|
437
|
-
|
|
438
|
-
// Clean old entry if updating
|
|
439
|
-
this._deleteL1(nsKey);
|
|
440
|
-
this._evictIfNeeded(bytes);
|
|
441
|
-
|
|
442
|
-
const entry: EdgeL1Entry<T> = {
|
|
443
|
-
value,
|
|
444
|
-
serialized,
|
|
445
|
-
bytes,
|
|
446
|
-
expiresAt: now + resolvedTtl * 1000,
|
|
447
|
-
staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
|
|
448
|
-
tags: optObj?.tags,
|
|
449
|
-
tagVersions: activeTagVersions,
|
|
450
|
-
};
|
|
451
|
-
|
|
452
|
-
this.l1.set(nsKey, entry);
|
|
453
|
-
this.currentBytes += bytes;
|
|
454
|
-
|
|
455
|
-
// Index tags
|
|
456
|
-
if (optObj?.tags) {
|
|
457
|
-
for (const tag of optObj.tags) {
|
|
458
|
-
let s = this.tagIndex.get(tag);
|
|
459
|
-
if (!s) {
|
|
460
|
-
s = new Set<string>();
|
|
461
|
-
this.tagIndex.set(tag, s);
|
|
462
|
-
}
|
|
463
|
-
s.add(nsKey);
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// Write to L2 Remote Storage if configured
|
|
468
|
-
if (this.remoteStorage) {
|
|
469
|
-
const toStoreRaw = activeTagVersions
|
|
470
|
-
? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions })
|
|
471
|
-
: serialized;
|
|
472
|
-
const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
|
|
473
|
-
await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// Register in Bloom filter
|
|
477
|
-
if (this.bloomFilter) {
|
|
478
|
-
this.bloomFilter.add(nsKey);
|
|
479
|
-
}
|
|
526
|
+
if (!Number.isFinite(resolvedTtl) || resolvedTtl < 0 || !Number.isFinite(swrSeconds) || swrSeconds < 0) throw new Error('Edge TTL and SWR must be finite non-negative values');
|
|
527
|
+
const versions = await this._batchGetTagVersions([...new Set([NAMESPACE_TAG, ...optObj?.tags ?? []])]);
|
|
528
|
+
await this.commit(key, value, resolvedTtl, optObj, versions, epoch);
|
|
480
529
|
} catch (err) {
|
|
481
530
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
482
531
|
span.recordException?.(err);
|
|
@@ -495,6 +544,7 @@ export class EdgeCacheService {
|
|
|
495
544
|
const nsKey = this.nk(key);
|
|
496
545
|
|
|
497
546
|
try {
|
|
547
|
+
this.mutate(nsKey);
|
|
498
548
|
this._deleteL1(nsKey);
|
|
499
549
|
if (this.remoteStorage) {
|
|
500
550
|
await this.remoteStorage.delete(nsKey);
|
|
@@ -513,13 +563,17 @@ export class EdgeCacheService {
|
|
|
513
563
|
* re-entering wildcard/cascade resolution.
|
|
514
564
|
*/
|
|
515
565
|
private async _invalidateConcreteTag(tag: string): Promise<void> {
|
|
566
|
+
this.invalidateWork();
|
|
567
|
+
const previous = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
516
568
|
let newVer = 1;
|
|
517
569
|
if (this.remoteStorage) {
|
|
518
570
|
try {
|
|
519
571
|
if (typeof this.remoteStorage.incrementTagVersion === 'function') {
|
|
520
|
-
newVer = await this.remoteStorage.incrementTagVersion(this.
|
|
572
|
+
newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
|
|
573
|
+
if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
|
|
574
|
+
newVer = Math.max(previous + 1, newVer);
|
|
521
575
|
} else {
|
|
522
|
-
const key = this.
|
|
576
|
+
const key = this.tagVersionKey(tag);
|
|
523
577
|
const current = await this._getTagVersion(tag);
|
|
524
578
|
newVer = Math.max(current + 1, Date.now());
|
|
525
579
|
await this.remoteStorage.set(key, String(newVer));
|
|
@@ -533,8 +587,7 @@ export class EdgeCacheService {
|
|
|
533
587
|
newVer = current + 1;
|
|
534
588
|
}
|
|
535
589
|
|
|
536
|
-
|
|
537
|
-
this._setTagVersionCache(tag, newVer, Date.now() + 60_000);
|
|
590
|
+
this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
|
|
538
591
|
|
|
539
592
|
// Invalidate local L1 entries
|
|
540
593
|
const keys = this.tagIndex.get(tag);
|
|
@@ -559,6 +612,9 @@ export class EdgeCacheService {
|
|
|
559
612
|
const isPattern = isWildcardTag(tag);
|
|
560
613
|
const shouldCascade = Boolean(opts?.cascade);
|
|
561
614
|
if (isPattern || shouldCascade) {
|
|
615
|
+
if (this.remoteStorage && !this.remoteStorage.scanKeys) {
|
|
616
|
+
throw new Error('Remote wildcard/cascade tag invalidation requires an adapter with scanKeys');
|
|
617
|
+
}
|
|
562
618
|
const matched = new Set<string>();
|
|
563
619
|
const tagMatches = (t: string) => {
|
|
564
620
|
if (t === tag) return true;
|
|
@@ -572,6 +628,14 @@ export class EdgeCacheService {
|
|
|
572
628
|
for (const t of this.tagVersionCache.keys()) {
|
|
573
629
|
if (tagMatches(t)) matched.add(t);
|
|
574
630
|
}
|
|
631
|
+
if (this.remoteStorage?.scanKeys) {
|
|
632
|
+
const registry = namespaceDomainPrefix(this.namespace, 'tag-registry');
|
|
633
|
+
for await (const key of this.remoteStorage.scanKeys(registry)) {
|
|
634
|
+
if (!key.startsWith(registry)) continue;
|
|
635
|
+
const concrete = key.slice(registry.length);
|
|
636
|
+
if (tagMatches(concrete)) matched.add(concrete);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
575
639
|
if (shouldCascade && !isPattern) matched.add(tag);
|
|
576
640
|
for (const t of matched) {
|
|
577
641
|
await this._invalidateConcreteTag(t);
|
|
@@ -595,6 +659,8 @@ export class EdgeCacheService {
|
|
|
595
659
|
async clear(): Promise<void> {
|
|
596
660
|
const span = this._startSpan('tricache.clear');
|
|
597
661
|
try {
|
|
662
|
+
const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
|
|
663
|
+
this.invalidateWork();
|
|
598
664
|
this.l1.clear();
|
|
599
665
|
this.currentBytes = 0;
|
|
600
666
|
this.tagIndex.clear();
|
|
@@ -603,8 +669,10 @@ export class EdgeCacheService {
|
|
|
603
669
|
this.bloomFilter.reset();
|
|
604
670
|
}
|
|
605
671
|
if (this.remoteStorage) {
|
|
606
|
-
await this.remoteStorage.clear?.(this.
|
|
672
|
+
await this.remoteStorage.clear?.(this.dataPrefix);
|
|
607
673
|
}
|
|
674
|
+
this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
|
|
675
|
+
await this._invalidateConcreteTag(NAMESPACE_TAG);
|
|
608
676
|
} catch (err) {
|
|
609
677
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
610
678
|
span.recordException?.(err);
|
|
@@ -623,6 +691,7 @@ export class EdgeCacheService {
|
|
|
623
691
|
ttlSeconds?: number,
|
|
624
692
|
): Promise<(T | null)[]> {
|
|
625
693
|
const span = this._startSpan('tricache.mget');
|
|
694
|
+
const epochs = new Map(keys.map(key => [key, this.fence(this.nk(key))]));
|
|
626
695
|
span.setAttribute('cache.batch.size', keys.length);
|
|
627
696
|
|
|
628
697
|
try {
|
|
@@ -648,10 +717,10 @@ export class EdgeCacheService {
|
|
|
648
717
|
const isMap = fetchedMap instanceof Map;
|
|
649
718
|
for (let j = 0; j < missKeys.length; j++) {
|
|
650
719
|
const k = missKeys[j];
|
|
651
|
-
const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : (fetchedMap as Record<string, T>)[k];
|
|
720
|
+
const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : Object.hasOwn(fetchedMap, k) ? (fetchedMap as Record<string, T>)[k] : undefined;
|
|
652
721
|
if (fetchedVal !== undefined) {
|
|
653
722
|
results[missIndices[j]] = fetchedVal;
|
|
654
|
-
await this.set(k, fetchedVal, ttlSeconds);
|
|
723
|
+
if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
|
|
655
724
|
}
|
|
656
725
|
}
|
|
657
726
|
}
|
|
@@ -676,9 +745,8 @@ export class EdgeCacheService {
|
|
|
676
745
|
|
|
677
746
|
for (const [nsKey, entry] of this.l1.entries()) {
|
|
678
747
|
if (entry.expiresAt > now || entry.staleUntil > now) {
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
: nsKey;
|
|
748
|
+
if (!nsKey.startsWith(this.dataPrefix)) continue;
|
|
749
|
+
const cleanKey = nsKey.slice(this.dataPrefix.length);
|
|
682
750
|
|
|
683
751
|
entries.push({
|
|
684
752
|
key: cleanKey,
|
|
@@ -692,7 +760,8 @@ export class EdgeCacheService {
|
|
|
692
760
|
}
|
|
693
761
|
|
|
694
762
|
const payload: EdgeSnapshotPayload = {
|
|
695
|
-
version:
|
|
763
|
+
version: 3,
|
|
764
|
+
namespace: this.namespacePrefix,
|
|
696
765
|
writtenAt: now,
|
|
697
766
|
entries,
|
|
698
767
|
};
|
|
@@ -722,6 +791,7 @@ export class EdgeCacheService {
|
|
|
722
791
|
* }
|
|
723
792
|
*/
|
|
724
793
|
async hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number> {
|
|
794
|
+
const epoch = this.globalEpoch;
|
|
725
795
|
let rawStr: string | null = null;
|
|
726
796
|
|
|
727
797
|
if (source && typeof source === 'object') {
|
|
@@ -767,7 +837,8 @@ export class EdgeCacheService {
|
|
|
767
837
|
return 0; // Malformed JSON -> fallback cold
|
|
768
838
|
}
|
|
769
839
|
|
|
770
|
-
if (!payload ||
|
|
840
|
+
if (!payload || payload.version !== 3 || payload.namespace !== this.namespacePrefix ||
|
|
841
|
+
!Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
|
|
771
842
|
return 0;
|
|
772
843
|
}
|
|
773
844
|
|
|
@@ -775,6 +846,7 @@ export class EdgeCacheService {
|
|
|
775
846
|
const maxAgeMs = options?.maxAgeMs ?? 7_200_000;
|
|
776
847
|
const tolerance = options?.clockSkewToleranceMs ?? 250;
|
|
777
848
|
const writtenAt = payload.writtenAt ?? 0;
|
|
849
|
+
if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
|
|
778
850
|
|
|
779
851
|
// Reject future timestamp exceeding clock skew tolerance
|
|
780
852
|
if (writtenAt - now > tolerance) {
|
|
@@ -789,13 +861,31 @@ export class EdgeCacheService {
|
|
|
789
861
|
|
|
790
862
|
let imported = 0;
|
|
791
863
|
for (const item of payload.entries) {
|
|
864
|
+
// Malformed entries are skipped individually and never mutate resident
|
|
865
|
+
// state. Validation happens before the size estimate, which previously
|
|
866
|
+
// threw on a missing value after earlier entries had already imported.
|
|
792
867
|
if (!item || typeof item.key !== 'string') continue;
|
|
793
|
-
|
|
868
|
+
if (!Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
|
|
794
869
|
if (item.expiresAt <= now && item.staleUntil <= now) continue;
|
|
870
|
+
if (item.value === undefined) continue;
|
|
871
|
+
if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.some(tag => typeof tag !== 'string'))) continue;
|
|
872
|
+
if (item.tagVersions !== undefined &&
|
|
873
|
+
(typeof item.tagVersions !== 'object' || item.tagVersions === null || Array.isArray(item.tagVersions) ||
|
|
874
|
+
Object.values(item.tagVersions).some(version => !Number.isFinite(version)))) continue;
|
|
875
|
+
|
|
876
|
+
let serialized: string;
|
|
877
|
+
try {
|
|
878
|
+
const encoded = JSON.stringify(item.value);
|
|
879
|
+
if (typeof encoded !== 'string') continue;
|
|
880
|
+
serialized = encoded;
|
|
881
|
+
} catch {
|
|
882
|
+
continue; // Unencodable values (cycles, BigInt) are skipped, not fatal.
|
|
883
|
+
}
|
|
795
884
|
|
|
796
885
|
const nsKey = this.nk(item.key);
|
|
797
|
-
|
|
886
|
+
if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey)) continue;
|
|
798
887
|
const bytes = this._estimateBytes(nsKey, serialized);
|
|
888
|
+
if (bytes > this.maxBytes || this.maxKeys === 0) continue;
|
|
799
889
|
|
|
800
890
|
this._deleteL1(nsKey);
|
|
801
891
|
this._evictIfNeeded(bytes);
|
|
@@ -825,7 +915,7 @@ export class EdgeCacheService {
|
|
|
825
915
|
}
|
|
826
916
|
|
|
827
917
|
if (this.bloomFilter) {
|
|
828
|
-
this.bloomFilter.add(
|
|
918
|
+
this.bloomFilter.add(nsKey);
|
|
829
919
|
}
|
|
830
920
|
|
|
831
921
|
imported++;
|
package/src/edge/hono.ts
CHANGED
|
@@ -11,12 +11,14 @@ export interface HonoEdgeCacheOptions {
|
|
|
11
11
|
etag?: boolean;
|
|
12
12
|
/** TTL in seconds. Default: 300. */
|
|
13
13
|
ttl?: number;
|
|
14
|
-
/** Stale-While-Revalidate window in seconds. Default: undefined. */
|
|
15
|
-
swr?: number;
|
|
16
14
|
/** Cache tags for invalidation. */
|
|
17
15
|
tags?: string[] | ((c: any) => string[]);
|
|
18
16
|
/** Predicate to skip caching dynamically. */
|
|
19
17
|
skipCache?: (c: any) => boolean;
|
|
18
|
+
/** Authenticated responses require explicit opt-in and an identity-aware key. */
|
|
19
|
+
cacheAuthenticated?: boolean;
|
|
20
|
+
/** @deprecated Response refreshes run on live requests. Use EdgeCacheService.get() for data-level SWR. */
|
|
21
|
+
swr?: number;
|
|
20
22
|
}
|
|
21
23
|
|
|
22
24
|
export interface CachedEdgeHttpResponse {
|
|
@@ -125,7 +127,6 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
125
127
|
cache,
|
|
126
128
|
etag = true,
|
|
127
129
|
ttl = 300,
|
|
128
|
-
swr,
|
|
129
130
|
tags,
|
|
130
131
|
skipCache,
|
|
131
132
|
keyGenerator,
|
|
@@ -141,6 +142,9 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
141
142
|
if (skipCache && skipCache(c)) {
|
|
142
143
|
return await next();
|
|
143
144
|
}
|
|
145
|
+
const credentials = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'].filter(name => c.req.header?.(name));
|
|
146
|
+
if (c.req.header?.('range') || credentials.length > 0 && (!options.cacheAuthenticated ||
|
|
147
|
+
!keyGenerator && !credentials.every(name => headerWhitelist?.some(header => header.toLowerCase() === name)))) return await next();
|
|
144
148
|
|
|
145
149
|
const cc = c.req.header?.('cache-control') || c.req.header?.('Cache-Control');
|
|
146
150
|
if (typeof cc === 'string') {
|
|
@@ -155,7 +159,12 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
155
159
|
return await next();
|
|
156
160
|
}
|
|
157
161
|
|
|
158
|
-
|
|
162
|
+
let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
|
|
163
|
+
if (credentials.length) {
|
|
164
|
+
if (!globalThis.crypto?.subtle) return await next();
|
|
165
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key));
|
|
166
|
+
key = `edge:http:identity:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
167
|
+
}
|
|
159
168
|
const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
|
|
160
169
|
const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
|
|
161
170
|
|
|
@@ -181,6 +190,10 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
181
190
|
}
|
|
182
191
|
|
|
183
192
|
const cc = res.headers?.get?.('cache-control');
|
|
193
|
+
const vary = String(res.headers?.get?.('vary') ?? '').split(',').map(name => name.trim().toLowerCase()).filter(Boolean);
|
|
194
|
+
if (res.headers?.get?.('set-cookie') || vary.includes('*') || !keyGenerator && vary.some(name => !headerWhitelist?.some(header => header.toLowerCase() === name))) {
|
|
195
|
+
throw new NonCacheableEdgeResponseError({ body: '', contentType, status: 0 });
|
|
196
|
+
}
|
|
184
197
|
if (cc) {
|
|
185
198
|
const lowerCc = cc.toLowerCase();
|
|
186
199
|
if (lowerCc.includes('no-store') || lowerCc.includes('no-cache') || lowerCc.includes('private')) {
|
|
@@ -233,9 +246,9 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
233
246
|
},
|
|
234
247
|
ttl,
|
|
235
248
|
{
|
|
236
|
-
swr,
|
|
249
|
+
swr: 0,
|
|
237
250
|
tags: resolvedTags,
|
|
238
|
-
ctx: c
|
|
251
|
+
ctx: readExecutionContext(c),
|
|
239
252
|
}
|
|
240
253
|
);
|
|
241
254
|
|
|
@@ -267,6 +280,10 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
|
267
280
|
};
|
|
268
281
|
}
|
|
269
282
|
|
|
283
|
+
function readExecutionContext(c: any): { waitUntil(promise: Promise<unknown>): void } | undefined {
|
|
284
|
+
try { return c.executionCtx; } catch { return undefined; }
|
|
285
|
+
}
|
|
286
|
+
|
|
270
287
|
/**
|
|
271
288
|
* Hono's `compose` ignores a middleware return value once `next()` has set
|
|
272
289
|
* `c.res` (`finalized === true`). Assigning `c.res` replaces the downstream
|