1use std::collections::HashMap;
10use std::sync::OnceLock;
11
12use crate::http::{HttpRequest, HttpResponse};
13
14const STYLESHEET: &[u8] = include_bytes!("../../web_ui.css");
15const HTMX_JS: &[u8] = include_bytes!("../../assets/htmx.min.js");
16const DIFF2HTML_JS: &[u8] = include_bytes!("../../assets/diff2html.min.js");
17const DIFF2HTML_CSS: &[u8] = include_bytes!("../../assets/diff2html.min.css");
18const APP_JS: &[u8] = include_bytes!("../../assets/app.js");
19const THEME_INIT_JS: &[u8] = include_bytes!("../../assets/theme-init.js");
20const FAVICON_SVG: &[u8] = include_bytes!("../../assets/favicon.svg");
21const ICONS_SVG: &[u8] = include_bytes!("../../assets/icons.svg");
22
23#[derive(Debug, Clone, Copy)]
25pub struct EmbeddedAsset {
26 pub path: &'static str,
27 pub content_type: &'static str,
28 pub bytes: &'static [u8],
29 pub immutable: bool,
30}
31
32impl EmbeddedAsset {
33 pub fn fingerprint(&self) -> String {
35 format!("{:016x}", fnv1a64(self.bytes))
36 }
37
38 pub fn fingerprinted_path(&self) -> String {
41 let fp = self.fingerprint();
42 insert_fingerprint(self.path, &fp)
43 }
44
45 pub fn weak_etag(&self) -> String {
47 let hash = fnv1a64(self.bytes);
48 format!("W/\"{hash:016x}\"")
49 }
50}
51
52fn insert_fingerprint(path: &str, fp: &str) -> String {
53 let slash_idx = path.rfind('/').unwrap_or(0);
54 if let Some(rel_dot) = path[slash_idx..].rfind('.') {
55 let dot_idx = slash_idx + rel_dot;
56 format!("{}.{fp}{}", &path[..dot_idx], &path[dot_idx..])
57 } else {
58 format!("{path}.{fp}")
59 }
60}
61
62pub const CORE_ASSETS: &[EmbeddedAsset] = &[
64 EmbeddedAsset {
65 path: "/style.css",
66 content_type: "text/css; charset=utf-8",
67 bytes: STYLESHEET,
68 immutable: true,
69 },
70 EmbeddedAsset {
71 path: "/assets/htmx.min.js",
72 content_type: "application/javascript; charset=utf-8",
73 bytes: HTMX_JS,
74 immutable: true,
75 },
76 EmbeddedAsset {
77 path: "/assets/diff2html.min.js",
78 content_type: "application/javascript; charset=utf-8",
79 bytes: DIFF2HTML_JS,
80 immutable: true,
81 },
82 EmbeddedAsset {
83 path: "/assets/diff2html.min.css",
84 content_type: "text/css; charset=utf-8",
85 bytes: DIFF2HTML_CSS,
86 immutable: true,
87 },
88 EmbeddedAsset {
89 path: "/assets/app.js",
90 content_type: "application/javascript; charset=utf-8",
91 bytes: APP_JS,
92 immutable: true,
93 },
94 EmbeddedAsset {
95 path: "/assets/theme-init.js",
96 content_type: "application/javascript; charset=utf-8",
97 bytes: THEME_INIT_JS,
98 immutable: true,
99 },
100 EmbeddedAsset {
101 path: "/favicon.svg",
102 content_type: "image/svg+xml",
103 bytes: FAVICON_SVG,
104 immutable: true,
105 },
106 EmbeddedAsset {
107 path: "/assets/icons.svg",
108 content_type: "image/svg+xml",
109 bytes: ICONS_SVG,
110 immutable: true,
111 },
112];
113
114struct CoreAssetManifest {
115 canonical_to_fingerprinted: HashMap<&'static str, String>,
116 fingerprinted_to_idx: HashMap<String, usize>,
117 canonical_to_idx: HashMap<&'static str, usize>,
118}
119
120fn core_manifest() -> &'static CoreAssetManifest {
121 static MANIFEST: OnceLock<CoreAssetManifest> = OnceLock::new();
122 MANIFEST.get_or_init(|| {
123 let mut canonical_to_fingerprinted = HashMap::with_capacity(CORE_ASSETS.len());
124 let mut fingerprinted_to_idx = HashMap::with_capacity(CORE_ASSETS.len());
125 let mut canonical_to_idx = HashMap::with_capacity(CORE_ASSETS.len());
126 for (idx, asset) in CORE_ASSETS.iter().enumerate() {
127 let fp = asset.fingerprinted_path();
128 canonical_to_fingerprinted.insert(asset.path, fp.clone());
129 fingerprinted_to_idx.insert(fp, idx);
130 canonical_to_idx.insert(asset.path, idx);
131 }
132 CoreAssetManifest {
133 canonical_to_fingerprinted,
134 fingerprinted_to_idx,
135 canonical_to_idx,
136 }
137 })
138}
139
140pub fn core_asset_url(canonical_path: &str) -> &str {
143 core_manifest()
144 .canonical_to_fingerprinted
145 .get(canonical_path)
146 .map(String::as_str)
147 .unwrap_or(canonical_path)
148}
149
150pub fn core_manifest_hash() -> String {
152 let mut acc = 0xcbf2_9ce4_8422_2325u64;
153 for asset in CORE_ASSETS {
154 let h = fnv1a64(asset.bytes);
155 acc ^= h;
156 acc = acc.wrapping_mul(0x0100_0000_01b3);
157 }
158 format!("{acc:016x}")
159}
160
161#[derive(Debug, Clone, Default)]
164pub struct AssetRegistry {
165 extra: Vec<EmbeddedAsset>,
166}
167
168impl AssetRegistry {
169 pub fn with_core() -> Self {
170 Self { extra: Vec::new() }
171 }
172
173 pub fn register(&mut self, asset: EmbeddedAsset) -> &mut Self {
174 self.extra.push(asset);
175 self
176 }
177
178 pub fn find(&self, path: &str) -> Option<&EmbeddedAsset> {
179 self.find_with_kind(path).map(|(a, _)| a)
180 }
181
182 fn find_with_kind(&self, path: &str) -> Option<(&EmbeddedAsset, bool)> {
183 for asset in &self.extra {
184 if asset.fingerprinted_path() == path {
185 return Some((asset, true));
186 }
187 if asset.path == path {
188 return Some((asset, false));
189 }
190 }
191 find_core_asset_with_kind(path)
192 }
193
194 pub fn serve(&self, req: &HttpRequest) -> Option<HttpResponse> {
196 if !matches!(req.method.as_str(), "GET" | "HEAD") {
197 return None;
198 }
199 let (asset, is_fingerprinted) = self.find_with_kind(req.path.as_str())?;
200 Some(build_asset_response(asset, req, is_fingerprinted))
201 }
202}
203
204fn find_core_asset_with_kind(path: &str) -> Option<(&'static EmbeddedAsset, bool)> {
205 let manifest = core_manifest();
206 if let Some(&idx) = manifest.fingerprinted_to_idx.get(path) {
207 return Some((&CORE_ASSETS[idx], true));
208 }
209 if let Some(&idx) = manifest.canonical_to_idx.get(path) {
210 return Some((&CORE_ASSETS[idx], false));
211 }
212 None
213}
214
215pub const fn core_assets() -> &'static [EmbeddedAsset] {
217 CORE_ASSETS
218}
219
220pub fn has_core_asset(path: &str) -> bool {
222 find_core_asset_with_kind(path).is_some()
223}
224
225pub fn serve_core_asset(req: &HttpRequest) -> Option<HttpResponse> {
227 if req.method == "OPTIONS" && has_core_asset(req.path.as_str()) {
228 return Some(HttpResponse {
229 status: 204,
230 content_type: "text/plain; charset=utf-8".into(),
231 body: Vec::new(),
232 www_authenticate: None,
233 extra_headers: vec![("Allow".into(), "GET, HEAD, OPTIONS".into())],
234 });
235 }
236 if !matches!(req.method.as_str(), "GET" | "HEAD") {
237 return None;
238 }
239 let (asset, is_fingerprinted) = find_core_asset_with_kind(req.path.as_str())?;
240 Some(build_asset_response(asset, req, is_fingerprinted))
241}
242
243fn build_asset_response(
244 asset: &EmbeddedAsset,
245 req: &HttpRequest,
246 is_fingerprinted: bool,
247) -> HttpResponse {
248 let etag = asset.weak_etag();
249 let cache = if is_fingerprinted && asset.immutable {
251 "public, max-age=31536000, immutable"
252 } else {
253 "no-cache"
254 };
255 if let Some(inm) = req.header("if-none-match") {
256 let matched = inm
257 .split(',')
258 .any(|tag| tag.trim() == etag || tag.trim() == "*");
259 if matched {
260 return HttpResponse {
261 status: 304,
262 content_type: asset.content_type.into(),
263 body: Vec::new(),
264 www_authenticate: None,
265 extra_headers: vec![
266 ("ETag".into(), etag),
267 ("Cache-Control".into(), cache.into()),
268 ("X-Content-Type-Options".into(), "nosniff".into()),
269 ],
270 };
271 }
272 }
273 let body = if req.method == "HEAD" {
274 Vec::new()
275 } else {
276 asset.bytes.to_vec()
277 };
278 HttpResponse {
279 status: 200,
280 content_type: asset.content_type.into(),
281 body,
282 www_authenticate: None,
283 extra_headers: vec![
284 ("ETag".into(), etag),
285 ("Cache-Control".into(), cache.into()),
286 ("X-Content-Type-Options".into(), "nosniff".into()),
287 ],
288 }
289}
290
291fn fnv1a64(bytes: &[u8]) -> u64 {
292 const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
293 const PRIME: u64 = 0x0100_0000_01b3;
294 let mut hash = OFFSET;
295 for &b in bytes {
296 hash ^= u64::from(b);
297 hash = hash.wrapping_mul(PRIME);
298 }
299 hash
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn core_assets_serve_200_and_304_on_matching_etag() {
308 let req = HttpRequest::new("GET", "/assets/app.js", "", Vec::new());
309 let resp = serve_core_asset(&req).expect("app.js must be served");
310 assert_eq!(resp.status, 200);
311 assert!(!resp.body.is_empty());
312 let etag = resp
313 .extra_headers
314 .iter()
315 .find(|(k, _)| k == "ETag")
316 .map(|(_, v)| v.clone())
317 .expect("ETag header missing");
318 let cc = resp
319 .extra_headers
320 .iter()
321 .find(|(k, _)| k == "Cache-Control")
322 .map(|(_, v)| v.as_str())
323 .expect("Cache-Control missing");
324 assert_eq!(cc, "no-cache", "unhashed URL must not be immutable");
325
326 let req_304 = HttpRequest::new("GET", "/assets/app.js", "", Vec::new())
327 .with_header("If-None-Match", etag);
328 let resp_304 = serve_core_asset(&req_304).expect("304 expected");
329 assert_eq!(resp_304.status, 304);
330 assert!(resp_304.body.is_empty());
331 }
332
333 #[test]
334 fn fingerprinted_asset_url_is_immutable_and_head_has_empty_body() {
335 let fp_url = core_asset_url("/style.css");
336 assert!(fp_url.starts_with("/style."));
337 assert!(fp_url.ends_with(".css"));
338 assert_ne!(fp_url, "/style.css");
339
340 let get_req = HttpRequest::new("GET", fp_url, "", Vec::new());
341 let get_resp = serve_core_asset(&get_req).expect("fingerprinted style.css served");
342 assert_eq!(get_resp.status, 200);
343 assert!(!get_resp.body.is_empty());
344 let cc = get_resp
345 .extra_headers
346 .iter()
347 .find(|(k, _)| k == "Cache-Control")
348 .map(|(_, v)| v.as_str())
349 .unwrap();
350 assert_eq!(cc, "public, max-age=31536000, immutable");
351
352 let head_req = HttpRequest::new("HEAD", fp_url, "", Vec::new());
353 let head_resp = serve_core_asset(&head_req).expect("HEAD fingerprinted asset served");
354 assert_eq!(head_resp.status, 200);
355 assert!(head_resp.body.is_empty());
356 }
357
358 #[test]
359 fn registry_supports_v2_extension_assets() {
360 let mut reg = AssetRegistry::with_core();
361 reg.register(EmbeddedAsset {
362 path: "/assets/kinetic_graph.js",
363 content_type: "application/javascript; charset=utf-8",
364 bytes: b"// kinetic",
365 immutable: true,
366 });
367 let req = HttpRequest::new("GET", "/assets/kinetic_graph.js", "", Vec::new());
368 let resp = reg.serve(&req).expect("extension asset served");
369 assert_eq!(resp.status, 200);
370 assert_eq!(resp.body, b"// kinetic");
371 }
372}