Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-edge/blob/main/src/site.rs # aien-edge aien-dev/aien-edge Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-edge / src / site.rs` 305 lines ยท 9517 bytes Raw Blame History 1 //! In-memory site store. Every file is read once at load, precompressed, and 2 //! hashed, so serving a request never touches the disk. 3 4 use bytes::Bytes; 5 use std::collections::HashMap; 6 use std::io::Write; 7 use std::path::Path; 8 9 /// Files smaller than this are served uncompressed; the headers would cost more than the savings. 10 const COMPRESS_MIN: usize = 1024; 11 12 #[derive(Debug)] 13 pub struct Asset { 14 pub body: Bytes, 15 pub br: Option, 16 pub gzip: Option, 17 pub content_type: String, 18 pub etag: String, 19 pub cache_control: &'static str, 20 } 21 22 #[derive(Debug)] 23 pub struct SiteFiles { 24 /// Keyed by URL path without the leading slash, for example "assets/index-abc.js". 25 pub files: HashMap, 26 pub spa: bool, 27 pub bytes_raw: usize, 28 } 29 30 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 31 pub enum Encoding { 32 Brotli, 33 Gzip, 34 Identity, 35 } 36 37 impl SiteFiles { 38 pub fn load(root: &Path, spa: bool) -> Result { 39 let mut files = HashMap::new(); 40 let mut bytes_raw = 0; 41 walk(root, root, &mut files, &mut bytes_raw)?; 42 if !files.contains_key("index.html") { 43 return Err(format!("{} has no index.html", root.display())); 44 } 45 Ok(SiteFiles { 46 files, 47 spa, 48 bytes_raw, 49 }) 50 } 51 52 /// Resolve a request path to an asset and the status to serve it with. 53 /// Returns None when nothing matches and the site has no 404 page. 54 pub fn resolve(&self, path: &str) -> Option<(&Asset, u16)> { 55 let key = normalize(path)?; 56 let candidates = [ 57 key.clone(), 58 if key.is_empty() { 59 "index.html".into() 60 } else { 61 format!("{key}/index.html") 62 }, 63 format!("{key}.html"), 64 ]; 65 for c in candidates.iter() { 66 if let Some(a) = self.files.get(c.trim_start_matches('/')) { 67 return Some((a, 200)); 68 } 69 } 70 if self.spa { 71 return self.files.get("index.html").map(|a| (a, 200)); 72 } 73 self.files.get("404.html").map(|a| (a, 404)) 74 } 75 } 76 77 /// Decode and normalize a URL path. Rejects traversal and anything outside the site. 78 pub fn normalize(path: &str) -> Option { 79 let path = path.split(['?', '#']).next().unwrap_or(""); 80 let decoded = percent_decode(path)?; 81 let mut parts: Vec<&str> = Vec::new(); 82 for seg in decoded.split('/') { 83 match seg { 84 "" | "." => {} 85 ".." => return None, 86 s if s.contains('\\') || s.contains('\0') => return None, 87 s => parts.push(s), 88 } 89 } 90 Some(parts.join("/")) 91 } 92 93 fn percent_decode(s: &str) -> Option { 94 let bytes = s.as_bytes(); 95 let mut out = Vec::with_capacity(bytes.len()); 96 let mut i = 0; 97 while i < bytes.len() { 98 if bytes[i] == b'%' { 99 let hex = s.get(i + 1..i + 3)?; 100 out.push(u8::from_str_radix(hex, 16).ok()?); 101 i += 3; 102 } else { 103 out.push(bytes[i]); 104 i += 1; 105 } 106 } 107 String::from_utf8(out).ok() 108 } 109 110 pub fn pick_encoding(accept: Option<&str>, asset: &Asset) -> Encoding { 111 let Some(accept) = accept else { 112 return Encoding::Identity; 113 }; 114 let allows = |name: &str| { 115 accept.split(',').any(|tok| { 116 let mut it = tok.trim().split(';'); 117 let coding = it.next().unwrap_or("").trim(); 118 let q_zero = it.any(|p| { 119 let p = p.trim(); 120 p == "q=0" || p == "q=0.0" || p == "q=0.00" || p == "q=0.000" 121 }); 122 coding.eq_ignore_ascii_case(name) && !q_zero 123 }) 124 }; 125 if asset.br.is_some() && allows("br") { 126 Encoding::Brotli 127 } else if asset.gzip.is_some() && allows("gzip") { 128 Encoding::Gzip 129 } else { 130 Encoding::Identity 131 } 132 } 133 134 fn walk( 135 root: &Path, 136 dir: &Path, 137 out: &mut HashMap, 138 total: &mut usize, 139 ) -> Result<(), String> { 140 let entries = std::fs::read_dir(dir).map_err(|e| format!("read_dir {}: {e}", dir.display()))?; 141 for entry in entries { 142 let entry = entry.map_err(|e| e.to_string())?; 143 let path = entry.path(); 144 let ft = entry.file_type().map_err(|e| e.to_string())?; 145 if ft.is_symlink() { 146 continue; 147 } 148 if ft.is_dir() { 149 walk(root, &path, out, total)?; 150 continue; 151 } 152 let rel = path 153 .strip_prefix(root) 154 .map_err(|e| e.to_string())? 155 .to_string_lossy() 156 .replace('\\', "/"); 157 if rel.ends_with(".map") 158 || rel 159 .split('/') 160 .any(|s| s.starts_with('.') && s != ".well-known") 161 { 162 continue; 163 } 164 let body = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()))?; 165 *total += body.len(); 166 out.insert(rel.clone(), build_asset(&rel, body)); 167 } 168 Ok(()) 169 } 170 171 fn build_asset(rel: &str, body: Vec) -> Asset { 172 let mime = mime_guess::from_path(rel).first_or_octet_stream(); 173 let text_like = mime.type_() == "text" 174 || matches!( 175 mime.subtype().as_str(), 176 "javascript" | "json" | "xml" | "svg" 177 ) 178 || mime.essence_str() == "image/svg+xml" 179 || rel.ends_with(".webmanifest"); 180 let content_type = if mime.type_() == "text" || mime.subtype() == "javascript" { 181 format!("{}; charset=utf-8", mime.essence_str()) 182 } else { 183 mime.essence_str().to_string() 184 }; 185 let (br, gzip) = if text_like && body.len() >= COMPRESS_MIN { 186 let br = brotli_bytes(&body); 187 let gz = gzip_bytes(&body); 188 ( 189 (br.len() < body.len()).then(|| Bytes::from(br)), 190 (gz.len() < body.len()).then(|| Bytes::from(gz)), 191 ) 192 } else { 193 (None, None) 194 }; 195 let etag = format!("\"{}\"", &blake3::hash(&body).to_hex()[..20]); 196 // Vite emits content-hashed names under assets/, so they can be cached forever. 197 let cache_control = if rel.starts_with("assets/") { 198 "public, max-age=`31536000`, immutable" 199 } else if rel.ends_with(".html") { 200 "public, max-age=0, must-revalidate" 201 } else { 202 "public, max-age=3600" 203 }; 204 Asset { 205 body: Bytes::from(body), 206 br, 207 gzip, 208 content_type, 209 etag, 210 cache_control, 211 } 212 } 213 214 fn brotli_bytes(data: &[u8]) -> Vec { 215 let mut out = Vec::with_capacity(data.len() / 3); 216 { 217 let mut w = brotli::CompressorWriter::new(&mut out, 4096, 11, 22); 218 w.write_all(data).expect("brotli write to Vec"); 219 } 220 out 221 } 222 223 fn gzip_bytes(data: &[u8]) -> Vec { 224 let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); 225 enc.write_all(data).expect("gzip write to Vec"); 226 enc.finish().expect("gzip finish") 227 } 228 229 #[cfg(test)] 230 mod tests { 231 use super::*; 232 233 fn site(files: &[(&str, &str)], spa: bool) -> (tempfile::TempDir, SiteFiles) { 234 let dir = tempfile::tempdir().unwrap(); 235 for (p, c) in files { 236 let full = dir.path().join(p); 237 std::fs::create_dir_all(full.parent().unwrap()).unwrap(); 238 std::fs::write(full, c).unwrap(); 239 } 240 let s = SiteFiles::load(dir.path(), spa).unwrap(); 241 (dir, s) 242 } 243 244 #[test] 245 fn normalize_rejects_traversal() { 246 assert_eq!(normalize("/a/../b"), None); 247 assert_eq!(normalize("/%2e%2e/etc/passwd"), None); 248 assert_eq!(normalize("/a%5cb"), None); 249 assert_eq!(normalize("/a//b/./c?x=1"), Some("a/b/c".into())); 250 assert_eq!(normalize("/"), Some("".into())); 251 } 252 253 #[test] 254 fn resolves_prerendered_routes_and_404() { 255 let (_d, s) = site( 256 &[ 257 ("index.html", "home"), 258 ("dad/index.html", "dad"), 259 ("404.html", "nf"), 260 ], 261 false, 262 ); 263 assert_eq!(s.resolve("/").unwrap().1, 200); 264 assert_eq!(&s.resolve("/dad").unwrap().0.body[..], b"dad"); 265 assert_eq!(&s.resolve("/dad/").unwrap().0.body[..], b"dad"); 266 let (a, code) = s.resolve("/missing").unwrap(); 267 assert_eq!((&a.body[..], code), (&b"nf"[..], 404)); 268 } 269 270 #[test] 271 fn spa_falls_back_to_index() { 272 let (_d, s) = site(&[("index.html", "app")], true); 273 let (a, code) = s.resolve("/deep/link").unwrap(); 274 assert_eq!((&a.body[..], code), (&b"app"[..], 200)); 275 } 276 277 #[test] 278 fn hidden_files_and_sourcemaps_are_not_served() { 279 let (_d, s) = site( 280 &[ 281 ("index.html", "x"), 282 (".env", "secret"), 283 ("assets/a.js.map", "{}"), 284 ], 285 false, 286 ); 287 assert!(!s.files.contains_key(".env")); 288 assert!(!s.files.contains_key("assets/a.js.map")); 289 } 290 291 #[test] 292 fn encoding_negotiation() { 293 let big = "x".repeat(4096); 294 let (_d, s) = site(&[("index.html", &big)], false); 295 let a = s.files.get("index.html").unwrap(); 296 assert_eq!( 297 pick_encoding(Some("gzip, deflate, br"), a), 298 Encoding::Brotli 299 ); 300 assert_eq!(pick_encoding(Some("gzip"), a), Encoding::Gzip); 301 assert_eq!(pick_encoding(Some("br;q=0, gzip"), a), Encoding::Gzip); 302 assert_eq!(pick_encoding(None, a), Encoding::Identity); 303 assert_eq!(a.cache_control, "public, max-age=0, must-revalidate"); 304 } 305 }