Skip to content

Commit

Permalink
Don't cache responses that don't have a stale-while-revalidate cache-…
Browse files Browse the repository at this point in the history
…control header set

The whole point of this proxy is to implement swr. It's purpose is not a (ideally blazing fast) CDN proxy.

Our file-system based cache backend is quite slow, bypassing is usually (much) faster.

If you need a fast CDN cache, use a CDN. If the CDN doesn't support swr, use this project additionally.
  • Loading branch information
nsams committed Oct 24, 2023
1 parent 03a1d56 commit 046ee5d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/__tests__/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,20 @@ describe("Proxy Server E2E Tests", () => {
expect(res.status).toBe(200);
expect(res.text).toBe("OK");
});

it("cacheable with max-age but without stale-while-revalidate should not cache", async () => {
{
const res = await request(`http://localhost:${proxyServerPort}`).get("/no-swr");
expect(res.status).toBe(200);
expect(res.text).toBe("0");
expect(res.header["x-cache"]).toBe("BYPASS");
}
await timeout(100);
{
const res = await request(`http://localhost:${proxyServerPort}`).get("/no-swr");
expect(res.status).toBe(200);
expect(res.text).toBe("1");
expect(res.header["x-cache"]).toBe("BYPASS");
}
});
});
4 changes: 2 additions & 2 deletions src/handleRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,11 @@ export async function handleRequest(req: IncomingMessage, res: ServerResponse, {

// Cache the response
const meta = parseMeta(response);
if (meta) {
//if null it's uncachable
if (meta && meta.staleWhileRevalidate) {
cache.set(cacheKey, body2, meta); //don't await
res.appendHeader("X-Cache", "MISS");
} else {
//if null it's uncachable, if no swr header also don't cache
res.appendHeader("X-Cache", "BYPASS");
}

Expand Down
6 changes: 6 additions & 0 deletions src/test/test-origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ app.all("/long2", async (req, res) => {
res.appendHeader("Cache-Control", "max-age=60, stale-while-revalidate=120");
res.send("long2");
});

app.get("/no-swr", async (req, res) => {
res.appendHeader("Cache-Control", "max-age=100");
res.send(String(count++));
});

app.listen(port, () => {
console.log(`test origin server is running on port ${port}`);
});

0 comments on commit 046ee5d

Please sign in to comment.