1use axum::{
2 body::Body,
3 http::{HeaderValue, Request, Response, StatusCode, header},
4};
5use rust_embed::RustEmbed;
6use sha2::{Digest, Sha256};
7use std::{
8 collections::HashMap,
9 convert::Infallible,
10 sync::{LazyLock, Mutex},
11 task::{Context, Poll},
12 time::{Duration, Instant},
13};
14use tower::Service;
15
16#[derive(RustEmbed, Clone)]
17#[folder = "$CARGO_MANIFEST_DIR/assets"]
18pub(crate) struct Assets;
19
20const IMMUTABLE: &str = "public, max-age=31536000, immutable";
21const NO_CACHE: &str = "no-cache";
22
23const PROBE_TTL: Duration = Duration::from_secs(1);
26
27const STAMPS: &[(&str, &[(&str, &str)])] = &[
33 (
34 "/static/css/app.css",
35 &[
36 (
37 "/static/vendor/fonts/geist.woff2",
38 "/static/vendor/fonts/geist.woff2",
39 ),
40 (
41 "/static/vendor/fonts/geist-mono.woff2",
42 "/static/vendor/fonts/geist-mono.woff2",
43 ),
44 ],
45 ),
46 (
47 "/static/vendor/phosphor/regular.css",
48 &[("./Phosphor.woff2", "/static/vendor/phosphor/Phosphor.woff2")],
49 ),
50 (
51 "/static/vendor/phosphor/fill.css",
52 &[(
53 "./Phosphor-Fill.woff2",
54 "/static/vendor/phosphor/Phosphor-Fill.woff2",
55 )],
56 ),
57 (
58 "/static/manifest.webmanifest",
59 &[
60 (
61 "/static/img/app-icon-192.png",
62 "/static/img/app-icon-192.png",
63 ),
64 (
65 "/static/img/app-icon-512.png",
66 "/static/img/app-icon-512.png",
67 ),
68 ],
69 ),
70];
71
72struct HashMemo {
74 fingerprints: Vec<[u8; 32]>,
79 probed: Instant,
82 digest: [u8; 32],
84}
85
86static HASHES: LazyLock<Mutex<HashMap<String, HashMemo>>> =
87 LazyLock::new(|| Mutex::new(HashMap::new()));
88
89#[derive(Clone)]
90pub struct StaticAssetService;
91
92impl Service<Request<Body>> for StaticAssetService {
93 type Response = Response<Body>;
94 type Error = Infallible;
95 type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
96
97 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
98 Poll::Ready(Ok(()))
99 }
100
101 fn call(&mut self, req: Request<Body>) -> Self::Future {
102 let req_path = req.uri().path().trim_start_matches('/');
103 let url_path = format!("/static/{req_path}");
104
105 let Some(data) = served_bytes(&url_path) else {
106 let resp = Response::builder()
107 .status(StatusCode::NOT_FOUND)
108 .body(Body::from("not found"))
109 .unwrap();
110 return std::future::ready(Ok(resp));
111 };
112
113 let mime = mime_guess::from_path(req_path).first_or_octet_stream();
114
115 let digest = served_digest(&url_path).unwrap_or_else(|| Sha256::digest(&data).into());
118 let etag = format!("\"{}\"", hex(&digest));
119 let cache_control = if url_has_current_version(&req, &digest) {
120 IMMUTABLE
121 } else {
122 NO_CACHE
123 };
124
125 if let Some(if_none_match) = req.headers().get(header::IF_NONE_MATCH)
126 && let Ok(val) = if_none_match.to_str()
127 && val == etag
128 {
129 let resp = Response::builder()
130 .status(StatusCode::NOT_MODIFIED)
131 .header(
132 header::CACHE_CONTROL,
133 HeaderValue::from_str(cache_control).unwrap(),
134 )
135 .body(Body::empty())
136 .unwrap();
137 return std::future::ready(Ok(resp));
138 }
139
140 let resp = Response::builder()
141 .status(StatusCode::OK)
142 .header(
143 header::CONTENT_TYPE,
144 HeaderValue::from_str(mime.as_ref()).unwrap(),
145 )
146 .header(header::ETAG, HeaderValue::from_str(&etag).unwrap())
147 .header(
148 header::CACHE_CONTROL,
149 HeaderValue::from_str(cache_control).unwrap(),
150 )
151 .body(Body::from(data))
152 .unwrap();
153
154 std::future::ready(Ok(resp))
155 }
156}
157
158pub fn versioned(url_path: &str) -> String {
161 if !url_path.starts_with("/static/") {
162 return url_path.to_string();
163 }
164 match served_digest(url_path) {
165 Some(digest) => format!("{url_path}?v={}", hex16(&digest)),
166 None => url_path.to_string(), }
168}
169
170fn fs_path(url_path: &str) -> String {
171 format!("static/{}", &url_path["/static/".len()..])
172}
173
174fn served_bytes(url_path: &str) -> Option<Vec<u8>> {
176 let file = Assets::get(&fs_path(url_path))?;
177 let Some((_, pairs)) = STAMPS.iter().find(|(path, _)| *path == url_path) else {
178 return Some(file.data.into_owned());
179 };
180
181 let mut text = match String::from_utf8(file.data.into_owned()) {
182 Ok(text) => text,
183 Err(e) => return Some(e.into_bytes()),
184 };
185 for (haystack, leaf) in *pairs {
186 let Some(version) = served_digest(leaf).map(|digest| hex16(&digest)) else {
187 continue;
188 };
189 text = text.replace(haystack, &format!("{haystack}?v={version}"));
190 }
191 Some(text.into_bytes())
192}
193
194fn served_digest(url_path: &str) -> Option<[u8; 32]> {
199 {
200 let memo = HASHES.lock().expect("hash memo");
201 if let Some(entry) = memo.get(url_path)
202 && entry.probed.elapsed() < PROBE_TTL
203 {
204 return Some(entry.digest);
205 }
206 }
207
208 let fingerprints = fingerprints(url_path)?;
209
210 {
211 let mut memo = HASHES.lock().expect("hash memo");
212 if let Some(entry) = memo.get_mut(url_path)
213 && entry.fingerprints == fingerprints
214 {
215 entry.probed = Instant::now();
216 return Some(entry.digest);
217 }
218 }
219
220 let data = served_bytes(url_path)?;
221 let digest: [u8; 32] = Sha256::digest(&data).into();
222 HASHES.lock().expect("hash memo").insert(
223 url_path.to_string(),
224 HashMemo {
225 fingerprints,
226 probed: Instant::now(),
227 digest,
228 },
229 );
230 Some(digest)
231}
232
233fn fingerprints(url_path: &str) -> Option<Vec<[u8; 32]>> {
237 let mut fingerprints = vec![raw_hash(url_path)?];
238 if let Some((_, pairs)) = STAMPS.iter().find(|(path, _)| *path == url_path) {
239 for (_, leaf) in *pairs {
240 fingerprints.push(raw_hash(leaf).unwrap_or([0u8; 32]));
241 }
242 }
243 Some(fingerprints)
244}
245
246fn raw_hash(url_path: &str) -> Option<[u8; 32]> {
248 let file = Assets::get(&fs_path(url_path))?;
249 let digest: [u8; 32] = Sha256::digest(&*file.data).into();
250 Some(digest)
251}
252
253fn url_has_current_version(req: &Request<Body>, digest: &[u8; 32]) -> bool {
256 req.uri().query().is_some_and(|query| {
257 query
258 .split('&')
259 .any(|kv| kv == format!("v={}", hex16(digest)))
260 })
261}
262
263fn hex16(digest: &[u8; 32]) -> String {
264 hex(&digest[..8])
265}
266
267fn hex(bytes: &[u8]) -> String {
268 bytes
269 .iter()
270 .fold(String::with_capacity(bytes.len() * 2), |mut hex, byte| {
271 use std::fmt::Write;
272 let _ = write!(hex, "{byte:02x}");
273 hex
274 })
275}