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 `<img>` tags, as the path does not change anymore.
This commit is contained in:
+2
-2
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
+22
-5
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
});
|
||||
+10
-14
@@ -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 = <Data = undefined>(
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
+1
-1
@@ -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");
|
||||
|
||||
+2
-2
@@ -137,7 +137,7 @@ Deno.test("/static page prerender", async () => {
|
||||
assert(!body.includes(`main.js`));
|
||||
assert(!body.includes(`island-test.js`));
|
||||
assertStringIncludes(body, "<p>This is a static page.</p>");
|
||||
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(
|
||||
|
||||
Reference in New Issue
Block a user