From cf438a787989f840e31a65c5998c79e80b40465d Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Mon, 16 May 2022 19:39:22 +0200 Subject: [PATCH] refactor: asset caching via query param (#192) This updates the asset caching to use a cache busting query string, rather than a totally separate path. This makes it safer to apply caching automatically to things like `` tags, as the path does not change anymore. --- deno.jsonc | 4 ++-- src/runtime/utils.ts | 27 ++++++++++++++++++++++----- src/runtime/utils_test.ts | 19 +++++++++++++++++++ src/server/context.ts | 24 ++++++++++-------------- tests/cli_test.ts | 2 +- tests/main_test.ts | 4 ++-- 6 files changed, 56 insertions(+), 24 deletions(-) create mode 100644 src/runtime/utils_test.ts diff --git a/deno.jsonc b/deno.jsonc index 352224b1..d2149874 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -1,7 +1,7 @@ { "tasks": { "test": "deno test -A --no-check=remote --watch", - "fixture": "deno run -A --no-check=remote --watch ./tests/fixture/main.ts", - "doc": "deno run -A --no-check=remote --watch=www/static,src/,docs/ www/main.ts" + "fixture": "deno run -A --watch ./tests/fixture/main.ts", + "doc": "deno run -A --watch=www/static,src/,docs/ www/main.ts" } } diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index b69d2e4b..d8c5ea49 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -1,13 +1,30 @@ export const INTERNAL_PREFIX = "/_frsh"; -export const STATIC_PREFIX = `/static`; +export const ASSET_CACHE_BUST_KEY = "__frsh_c"; export const IS_BROWSER = typeof document !== "undefined"; /** - * Return a path "hashed" with the BUILD_ID. of a static file - * Such path will be served by the server with a Cache-Control of 1 year. - * @param path a path to a file in the static folder asset. e.g. /style.css + * Create a "locked" asset path. This differs from a plain path in that it is + * specific to the current version of the application, and as such can be safely + * served with a very long cache lifetime (1 year). */ export function asset(path: string) { - return `${INTERNAL_PREFIX}${STATIC_PREFIX}/${__FRSH_BUILD_ID}${path}`; + if (!path.startsWith("/") || path.startsWith("//")) return path; + try { + const url = new URL(path, "https://freshassetcache.local"); + if ( + url.protocol !== "https:" || url.host !== "freshassetcache.local" || + url.searchParams.has(ASSET_CACHE_BUST_KEY) + ) { + return path; + } + url.searchParams.set(ASSET_CACHE_BUST_KEY, __FRSH_BUILD_ID); + return url.pathname + url.search + url.hash; + } catch (err) { + console.warn( + `Failed to create asset() URL, falling back to regular path ('${path}'):`, + err, + ); + return path; + } } diff --git a/src/runtime/utils_test.ts b/src/runtime/utils_test.ts new file mode 100644 index 00000000..fc11bb90 --- /dev/null +++ b/src/runtime/utils_test.ts @@ -0,0 +1,19 @@ +import { assertEquals } from "../../tests/deps.ts"; +import { asset } from "./utils.ts"; + +globalThis.__FRSH_BUILD_ID = "ID123"; + +Deno.test("asset", () => { + assertEquals(asset("/test.png"), "/test.png?__frsh_c=ID123"); + assertEquals(asset("/test?f=1"), "/test?f=1&__frsh_c=ID123"); + assertEquals(asset("/test#foo"), "/test?__frsh_c=ID123#foo"); + assertEquals(asset("/test?f=1#foo"), "/test?f=1&__frsh_c=ID123#foo"); + + assertEquals(asset("./test.png"), "./test.png"); + assertEquals(asset("//example.com/logo.png"), "//example.com/logo.png"); + assertEquals(asset("/test.png?__frsh_c=1"), "/test.png?__frsh_c=1"); + assertEquals( + asset("https://example.com/logo.png"), + "https://example.com/logo.png", + ); +}); diff --git a/src/server/context.ts b/src/server/context.ts index fe09a957..1af111c3 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -33,7 +33,7 @@ import { import { render as internalRender } from "./render.tsx"; import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts"; import { h } from "../runtime/deps.ts"; -import { asset, INTERNAL_PREFIX } from "../runtime/utils.ts"; +import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts"; interface StaticFile { /** The URL to the static file on disk. */ @@ -374,15 +374,6 @@ export class ServerContext { contentType, etag, ); - - const hashedRoute = sanitizePathToRegex(asset(path)); - routes[`GET@${hashedRoute}`] = this.#staticFileHandler( - localUrl, - size, - contentType, - etag, - true, - ); } const genRender = ( @@ -503,9 +494,16 @@ export class ServerContext { size: number, contentType: string, etag: string, - isCacheable?: boolean, ): router.MatchHandler { return async (req: Request) => { + const url = new URL(req.url); + const key = url.searchParams.get(ASSET_CACHE_BUST_KEY); + if (key !== null && BUILD_ID !== key) { + return new Response("Not Found", { + status: 404, + headers: { "content-type": "text/plain" }, + }); + } if (req.headers.get("if-none-match") === etag) { return new Response(null, { status: 304 }); } else { @@ -515,11 +513,9 @@ export class ServerContext { "content-length": String(size), "etag": etag, }); - - if (isCacheable) { + if (key !== null) { headers.set("Cache-Control", "public, max-age=31536000, immutable"); } - return new Response(resp.body, { headers, }); diff --git a/tests/cli_test.ts b/tests/cli_test.ts index 9d6a81ce..f494ab94 100644 --- a/tests/cli_test.ts +++ b/tests/cli_test.ts @@ -134,7 +134,7 @@ Deno.test({ assertEquals(res.status, 200); // verify the island is revived. - const browser = await puppeteer.launch(); + const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); await page.goto("http://localhost:8000"); diff --git a/tests/main_test.ts b/tests/main_test.ts index fa663d0f..289aff8d 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -137,7 +137,7 @@ Deno.test("/static page prerender", async () => { assert(!body.includes(`main.js`)); assert(!body.includes(`island-test.js`)); assertStringIncludes(body, "

This is a static page.

"); - assertStringIncludes(body, `src="/_frsh/static`); + assertStringIncludes(body, `src="/image.png?__frsh_c=`); assert(!body.includes("__FRSH_ISLAND_PROPS")); }); @@ -205,7 +205,7 @@ Deno.test("static file - by 'hashed' path", async () => { const body = await resp.text(); const imgFilePath = body.match(/img src="(.*?)"/)?.[1]; assert(imgFilePath); - assert(imgFilePath.includes(globalThis.__FRSH_BUILD_ID)); + assert(imgFilePath.includes(`?__frsh_c=${globalThis.__FRSH_BUILD_ID}`)); // check the static file is served corectly under its cacheable route const resp2 = await router(