Public: anyone can read this; the crew can change it.

A pushed style change is on the page at once: the stylesheet is content-addressed #469

Closed opened this
Closed without merging

scout/forge:scout/113-a-pushed-style-change-is-on-the-page-at → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +85 −32
src/http/server.ts +14 −22
@@ -26,8 +26,12 @@ import { rmSync } from "node:fs";
2626 import { join } from "node:path";
2727 import type { App } from "../app.ts";
2828 import { sha256 } from "../kernel/hash.ts";
29 import { css } from "../web/style.ts";
30 import { assetResponse, highlightAsset } from "../web/asset.ts";
29 import {
30 assetResponse,
31 highlightAsset,
32 stylesheetAsset,
33 stylesheetResponse,
34 } from "../web/asset.ts";
3135 import { isThemeName } from "../design/themes.ts";
3236 import {
3337 home,
@@ -315,30 +319,18 @@ const gitChallenge = () =>
315319
316320 // ---- the public server ----
317321
318 const CSS_ETAG = `"${sha256(css).slice(0, 16)}"`;
319
320 function stylesheet(ctx: Ctx): Response {
321 if (ctx.request.headers.get("if-none-match") === CSS_ETAG) {
322 return new Response(null, { status: 304, headers: { etag: CSS_ETAG } });
323 }
324 return new Response(css, {
325 headers: {
326 "content-type": "text/css; charset=utf-8",
327 etag: CSS_ETAG,
328 "cache-control": "public, max-age=300",
329 },
330 });
331 }
332
333322 export function buildRouter(): Router<Handler> {
334323 const router = new Router<Handler>();
335324
336325 // Literal-prefix routes come before parameterized repo routes; the router
337 // matches in insertion order.
338 router.add("GET", "/assets/forge.css", stylesheet);
339 // The highlighter bundle, content-addressed. A stale hash is a 404 rather
340 // than a redirect: the page that asked for it names the hash it was built
341 // with, so a miss means an old tab, and an old tab should reload.
326 // matches in insertion order. The stylesheet and the highlighter bundle are
327 // both content-addressed: a stale hash is a 404 rather than a redirect, the
328 // page that asked for it names the hash it was built with, so a miss means
329 // an old tab, and an old tab should reload.
330 router.add("GET", "/assets/:name.css", (ctx) => {
331 if (ctx.params.name !== stylesheetAsset().name) return notFound();
332 return stylesheetResponse();
333 });
342334 router.add("GET", "/assets/:name.js", async (ctx) => {
343335 const asset = await highlightAsset();
344336 if (asset === null || ctx.params.name !== asset.name) return notFound();
src/web/asset.ts +30
@@ -18,6 +18,7 @@
1818
1919 import { sha256 } from "../kernel/hash.ts";
2020 import { createLog } from "../kernel/log.ts";
21 import { css } from "./style.ts";
2122
2223 const log = createLog("web");
2324
@@ -69,3 +70,32 @@ export function assetResponse(asset: BuiltAsset): Response {
6970 },
7071 });
7172 }
73
74 /** The stylesheet, content-addressed the same way. Hashed once per process. */
75 export interface CssAsset {
76 /** The URL path it is served from, content-hashed. */
77 path: string;
78 /** The `:name` the route matches, i.e. the path's basename without `.css`. */
79 name: string;
80 }
81
82 let cssAsset: CssAsset | null = null;
83
84 export function stylesheetAsset(): CssAsset {
85 if (cssAsset === null) {
86 const name = `forge-${sha256(css).slice(0, 16)}`;
87 cssAsset = { path: `/assets/${name}.css`, name };
88 }
89 return cssAsset;
90 }
91
92 /** The response for a hit on the stylesheet: immutable, because it is. */
93 export function stylesheetResponse(): Response {
94 return new Response(css, {
95 headers: {
96 "content-type": "text/css; charset=utf-8",
97 "cache-control": "public, max-age=31536000, immutable",
98 "x-content-type-options": "nosniff",
99 },
100 });
101 }
src/web/layout.ts +5 −1
@@ -19,6 +19,7 @@ import {
1919 THEMES,
2020 type ThemeName,
2121 } from "../design/themes.ts";
22 import { stylesheetAsset } from "./asset.ts";
2223 import { shellJs } from "./client.ts";
2324 import {
2425 clearFlashCookie,
@@ -482,7 +483,7 @@ export function page(options: PageOptions, status = 200): Response {
482483 rel="icon"
483484 href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%232563eb'/%3E%3Cstop offset='1' stop-color='%237c3aed'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='url(%23g)'/%3E%3C/svg%3E"
484485 />
485 <link rel="stylesheet" href="/assets/forge.css" />
486 <link rel="stylesheet" href="${stylesheetAsset().path}" />
486487 ${when(
487488 options.scriptAsset,
488489 (src) => html`<script type="module" src="${src}"></script>`,
@@ -510,6 +511,9 @@ export function page(options: PageOptions, status = 200): Response {
510511 "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}; connect-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
511512 "referrer-policy": "same-origin",
512513 "x-content-type-options": "nosniff",
514 // Markup is revalidated every time; only the hashed assets it names are
515 // cached, so no cache can pair new HTML with an old stylesheet.
516 "cache-control": "no-cache",
513517 });
514518 // A flash is shown exactly once: rendering it is also what clears it.
515519 if (flash) headers.append("set-cookie", clearFlashCookie(ctx.url));
test/web.test.ts +36 −9
@@ -5,9 +5,22 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { health } from "../src/http/health.ts";
77 import { serve, type Servers } from "../src/http/server.ts";
8 import { stylesheetAsset } from "../src/web/asset.ts";
89 import { escapeHtml, html, raw, when } from "../src/web/html.ts";
910 import { renderMarkdown } from "../src/web/markdown.ts";
1011 import { THEME_NAMES } from "../src/design/themes.ts";
12 import { sha256 } from "../src/kernel/hash.ts";
13 import { css } from "../src/web/style.ts";
14
15 describe("stylesheet asset", () => {
16 test("its path is a hash over the css, so changing the css moves it", () => {
17 const expected = `/assets/forge-${sha256(css).slice(0, 16)}.css`;
18 expect(stylesheetAsset().path).toBe(expected);
19 expect(stylesheetAsset().path).not.toBe(
20 `/assets/forge-${sha256(css + " ").slice(0, 16)}.css`,
21 );
22 });
23 });
1124
1225 describe("html template", () => {
1326 test("escapes interpolations by default", () => {
@@ -190,14 +203,26 @@ describe("web pages end to end", () => {
190203 expect(text).toContain("function openModal(");
191204 });
192205
193 test("stylesheet is served with an etag", async () => {
194 const first = await fetch(`${base}/assets/forge.css`);
195 expect(first.headers.get("content-type")).toContain("text/css");
196 const etag = first.headers.get("etag")!;
197 const second = await fetch(`${base}/assets/forge.css`, {
198 headers: { "if-none-match": etag },
199 });
200 expect(second.status).toBe(304);
206 test("stylesheet is content-addressed and immutable, at the path the page names", async () => {
207 const homeText = await (await fetch(base, { headers: { cookie } })).text();
208 const match = homeText.match(/href="(\/assets\/forge-[0-9a-f]+\.css)"/);
209 expect(match).not.toBeNull();
210 const path = match![1]!;
211 expect(
212 (await fetch(base, { headers: { cookie } })).headers.get("cache-control"),
213 ).toBe("no-cache");
214
215 const response = await fetch(`${base}${path}`);
216 expect(response.status).toBe(200);
217 expect(response.headers.get("content-type")).toContain("text/css");
218 expect(response.headers.get("cache-control")).toBe(
219 "public, max-age=31536000, immutable",
220 );
221
222 // A stale hash — an old tab's cached URL after a deploy — is a 404, not
223 // a redirect, the same rule the highlighter bundle already follows.
224 const stale = await fetch(`${base}/assets/forge-0000000000000000.css`);
225 expect(stale.status).toBe(404);
201226 });
202227
203228 test("new repo via the form, empty state renders", async () => {
@@ -324,7 +349,9 @@ describe("themes", () => {
324349 });
325350
326351 test("stylesheet carries every premade theme", async () => {
327 const css = await (await fetch(`${base}/assets/forge.css`)).text();
352 const css = await (
353 await fetch(`${base}${stylesheetAsset().path}`)
354 ).text();
328355 for (const name of THEME_NAMES) {
329356 expect(css).toContain(`:root[data-theme="${name}"]`);
330357 expect(css).toContain(`.swatch[data-t="${name}"]`);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs