Skip to content

Commit 239e6e6

Browse files
authored
chore: cloudflare worker cache (#344)
1 parent 80aebf2 commit 239e6e6

2 files changed

Lines changed: 27 additions & 6 deletions

File tree

cloudflare-workers/backblaze-proxy/index.ts

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export default {
5151
S3_ENDPOINT: string;
5252
ALLOWED_HEADERS?: string;
5353
},
54+
ctx: ExecutionContext,
5455
) {
5556
if (request.method === "OPTIONS") {
5657
return new Response(null, {
@@ -66,6 +67,18 @@ export default {
6667
});
6768
}
6869

70+
// Edge-cache short-circuit: serve repeat hits without re-running SigV4
71+
// or making a B2 subrequest. Range requests fall through so the existing
72+
// cf.cacheEverything path handles slicing from the cached full object.
73+
const cache = caches.default;
74+
const cacheKey = new Request(request.url, { method: "GET" });
75+
const skipEdgeCache =
76+
request.method !== "GET" || request.headers.has("range");
77+
if (!skipEdgeCache) {
78+
const cached = await cache.match(cacheKey);
79+
if (cached) return cached;
80+
}
81+
6982
const url = new URL(request.url);
7083
const key = resolveKey(url);
7184
if (!key) {
@@ -101,7 +114,6 @@ export default {
101114
headers: signedRequest.headers,
102115
cf: {
103116
cacheEverything: true,
104-
cacheTtl: 2592000,
105117
cacheTtlByStatus: { "200-299": 2592000, "404": 60, "500-599": 0 },
106118
},
107119
});
@@ -133,18 +145,24 @@ export default {
133145
if (!headers.has("Accept-Ranges")) {
134146
headers.set("Accept-Ranges", "bytes");
135147
}
136-
if (!headers.has("Cache-Control")) {
137-
headers.set("Cache-Control", "public, max-age=2592000, immutable");
138-
}
148+
// Force long browser cache regardless of what B2 returned — second view
149+
// of a clip serves from the user's disk cache and never hits the Worker.
150+
headers.set("Cache-Control", "public, max-age=2592000, immutable");
139151
for (const [k, v] of Object.entries(corsHeaders())) {
140152
headers.set(k, v);
141153
}
142154

143-
return new Response(upstream.body, {
155+
const response = new Response(upstream.body, {
144156
headers,
145157
status: upstream.status,
146158
statusText: upstream.statusText,
147159
});
160+
161+
if (!skipEdgeCache && response.status === 200) {
162+
ctx.waitUntil(cache.put(cacheKey, response.clone()));
163+
}
164+
165+
return response;
148166
},
149167
};
150168

cloudflare-workers/backblaze-proxy/wrangler.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88

99
name = "5stack"
1010
main = "index.ts"
11-
compatibility_date = "2024-09-01"
11+
compatibility_date = "2025-04-29"
12+
13+
[observability]
14+
enabled = true
1215

1316
[vars]
1417
BUCKET_NAME = "5stack"

0 commit comments

Comments
 (0)