Skip to main content

max / makenotwork

6.5 KB · 164 lines History Blame Raw
1 use std::collections::hash_map::DefaultHasher;
2 use std::fs;
3 use std::hash::{Hash, Hasher};
4 use std::path::Path;
5 use std::process::Command;
6
7 fn main() {
8 build_frontend();
9 fingerprint_assets();
10 }
11
12 /// Content-hash the served static files and emit the template partials that
13 /// carry a `?v=<hash>` cache-buster on every asset URL.
14 ///
15 /// Runs after `build_frontend` so the hash covers the JS that was just emitted
16 /// into `static/dist/`, not the previous build's.
17 ///
18 /// One global version rather than a per-file hash: an upgrade to any watched
19 /// file re-fetches all of them, which costs a handful of requests once and
20 /// keeps the templates free of per-asset bookkeeping. What it buys is that a
21 /// redeployed file can never be served stale from browser cache, for a chat
22 /// island that would mean old protocol logic talking to a new server, which
23 /// presents as "chat is broken for some people" rather than as a cache bug.
24 ///
25 /// The generated partials are gitignored build output. They are written only
26 /// when their content changes, so a no-op build does not retrigger Askama.
27 fn fingerprint_assets() {
28 let static_files = ["static/style.css", "static/htmx.min.js", "static/mt.js"];
29
30 let mut hasher = DefaultHasher::new();
31 for path in &static_files {
32 println!("cargo::rerun-if-changed={path}");
33 if let Ok(content) = fs::read(path) {
34 content.hash(&mut hasher);
35 }
36 }
37 // Fold the emitted bundles in so `?v=` also busts when the TypeScript
38 // changes. Read-only: `frontend/src` is the watched trigger (in
39 // build_frontend); watching the outputs we generate would loop.
40 hash_dir_js(Path::new("static/dist"), &mut hasher);
41 let version = &format!("{:016x}", hasher.finish())[..8];
42
43 // Included by base.html's <head>.
44 let head = format!(
45 r#" <link rel="stylesheet" href="/static/style.css?v={version}">
46 <script src="/static/htmx.min.js?v={version}"></script>"#
47 );
48 write_if_changed(Path::new("templates/_head_assets.html"), &head);
49
50 // Included at the end of base.html's <body>. Kept separate from the head
51 // partial because mt.js is a classic (non-deferred) script and has to keep
52 // running after the document is parsed.
53 let scripts = format!(r#" <script src="/static/mt.js?v={version}"></script>"#);
54 write_if_changed(Path::new("templates/_body_scripts.html"), &scripts);
55
56 // Per-page island loader, for the compiled ESM under static/dist/. Used as
57 // `{% import "_island.html" as island %}{% call island::island("chat") %}`
58 // and cache-busted by the same content hash as the head assets.
59 let island = r#"{% macro island(name) -%}
60 <script type="module" src="/static/dist/{{ name }}.js?v=__VER__"></script>
61 {%- endmacro %}
62 "#
63 .replace("__VER__", version);
64 write_if_changed(Path::new("templates/_island.html"), &island);
65 }
66
67 /// Write `contents` to `path` only if it differs, to avoid needless rebuilds.
68 fn write_if_changed(path: &Path, contents: &str) {
69 let needs_write = fs::read_to_string(path).map_or(true, |existing| existing != contents);
70 if needs_write {
71 fs::write(path, contents)
72 .unwrap_or_else(|e| panic!("failed to write {}: {e}", path.display()));
73 }
74 }
75
76 /// Recursively hash every `.js` file under `dir` into `hasher`, in a
77 /// deterministic order. A missing directory is a no-op, the first build on a
78 /// fresh checkout runs before the frontend has been compiled.
79 fn hash_dir_js(dir: &Path, hasher: &mut DefaultHasher) {
80 let Ok(entries) = fs::read_dir(dir) else {
81 return;
82 };
83 let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
84 paths.sort();
85 for path in paths {
86 if path.is_dir() {
87 hash_dir_js(&path, hasher);
88 } else if path.extension().and_then(|e| e.to_str()) == Some("js")
89 && let Ok(content) = fs::read(&path)
90 {
91 content.hash(hasher);
92 }
93 }
94 }
95
96 /// Compile the TypeScript frontend (`frontend/`) to browser ESM in
97 /// `static/dist/` via `npm run build` (which runs `tsc`).
98 ///
99 /// This runs from `cargo build` on purpose. `static/dist/` is gitignored
100 /// regenerable output, so a fresh checkout has no JS at all, and the deploy path
101 /// builds on astra rather than on the machine that edited the TypeScript. Making
102 /// it a build script means there is no "remember to run npm build first" step
103 /// standing between an edit and a working deploy.
104 ///
105 /// Self-contained: on a host without `node_modules` it runs `npm ci` first.
106 ///
107 /// Best-effort and non-fatal. A missing Node or a compile error emits a
108 /// `cargo::warning` and lets the Rust build succeed against whatever
109 /// `static/dist/` already holds, because a type error in a chat widget should
110 /// not be able to stop the forum from building. The Sando `code_smoke` tier is
111 /// where a frontend failure is meant to be fatal.
112 ///
113 /// Set `MT_SKIP_FRONTEND_BUILD=1` to opt out entirely.
114 fn build_frontend() {
115 println!("cargo::rerun-if-changed=frontend/src");
116 println!("cargo::rerun-if-changed=frontend/package.json");
117 println!("cargo::rerun-if-changed=frontend/package-lock.json");
118 println!("cargo::rerun-if-changed=frontend/tsconfig.json");
119
120 if std::env::var_os("MT_SKIP_FRONTEND_BUILD").is_some() {
121 println!("cargo::warning=frontend build skipped (MT_SKIP_FRONTEND_BUILD set)");
122 return;
123 }
124
125 if !Path::new("frontend/node_modules").is_dir() {
126 match Command::new("npm")
127 .args(["ci"])
128 .current_dir("frontend")
129 .status()
130 {
131 Ok(s) if s.success() => {}
132 Ok(s) => {
133 println!(
134 "cargo::warning=npm ci failed (exit {:?}); skipping frontend build (serving existing static/dist)",
135 s.code()
136 );
137 return;
138 }
139 Err(e) => {
140 println!(
141 "cargo::warning=could not run npm ({e}); is Node installed? skipping frontend build (serving existing static/dist)"
142 );
143 return;
144 }
145 }
146 }
147
148 match Command::new("npm")
149 .args(["run", "build"])
150 .current_dir("frontend")
151 .status()
152 {
153 Ok(s) if s.success() => {}
154 Ok(s) => println!(
155 "cargo::warning=frontend build failed (npm run build exit {:?}); serving stale static/dist",
156 s.code()
157 ),
158 Err(e) => println!(
159 "cargo::warning=could not run npm for the frontend build ({e}); is Node installed? \
160 skipping (serving existing static/dist)"
161 ),
162 }
163 }
164