forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

main.rs232 lines, 8.4 KiBHistoryRawDownload
1use std::collections::HashSet;
2use std::fs;
3use std::path::PathBuf;
4use std::process::Command;
5use std::time::Instant;
6
7use anyhow::{Context, Result, bail};
8
9mod e2e;
10mod stress;
11
12const USAGE: &str = "usage: cargo xtask editor [--dev] | cargo xtask e2e | cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--only CASE] [--keep]";
13
14fn main() -> Result<()> {
15 let args: Vec<String> = std::env::args().skip(1).collect();
16 match args.first().map(String::as_str) {
17 Some("editor") => {
18 let mut dev = false;
19 for arg in &args[1..] {
20 match arg.as_str() {
21 "--dev" => dev = true,
22 other => bail!("unknown argument `{other}`\n{USAGE}"),
23 }
24 }
25 build_editor(!dev)
26 }
27 Some("e2e") => e2e::run(&workspace_root()?, &target_dir()?),
28 Some("stress") => stress::run(&workspace_root()?, &target_dir()?, &args[1..]),
29 _ => bail!("{USAGE}"),
30 }
31}
32
33fn build_editor(release: bool) -> Result<()> {
34 let started = Instant::now();
35 let root = workspace_root()?;
36 let target = target_dir()?;
37 let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
38
39 // 1. Build the wasm library.
40 let mut build = Command::new(&cargo);
41 build
42 .args(["build", "-p", "editor", "--lib", "--target", "wasm32-unknown-unknown"])
43 // SIMD: byte scans (UTF-8 counts, memchr, lz4) on 100 MB notes. Every current browser has it.
44 .env("CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS", "-C target-feature=+simd128")
45 .current_dir(&root);
46 if release {
47 build.args(["--profile", "editor"]);
48 }
49 let status = build.status().context("failed to spawn cargo build")?;
50 if !status.success() {
51 bail!("cargo build -p editor failed with {status}");
52 }
53
54 let profile = if release { "editor" } else { "debug" };
55 let raw_wasm = target
56 .join("wasm32-unknown-unknown")
57 .join(profile)
58 .join("editor.wasm");
59 if !raw_wasm.is_file() {
60 bail!("expected wasm at {}", raw_wasm.display());
61 }
62
63 // 2. Run wasm-bindgen as a library.
64 let out_dir = target.join("xtask-editor");
65 fs::create_dir_all(&out_dir)?;
66 wasm_bindgen_cli_support::Bindgen::new()
67 .input_path(&raw_wasm)
68 .web(true)?
69 .typescript(false)
70 .generate(&out_dir)
71 .context("wasm-bindgen generate failed")?;
72 let bg_wasm_path = out_dir.join("editor_bg.wasm");
73 let glue_path = out_dir.join("editor.js");
74
75 // 3. Optimize the wasm in release mode.
76 let mut wasm_bytes = fs::read(&bg_wasm_path)
77 .with_context(|| format!("reading {}", bg_wasm_path.display()))?;
78 if release {
79 let opt_path = out_dir.join("editor_bg.opt.wasm");
80 // The features rustc's wasm32 target emits by default, plus SIMD.
81 use wasm_opt::Feature;
82 wasm_opt::OptimizationOptions::new_opt_level_3()
83 .enable_feature(Feature::Simd)
84 .enable_feature(Feature::BulkMemory)
85 .enable_feature(Feature::SignExt)
86 .enable_feature(Feature::TruncSat)
87 .enable_feature(Feature::MutableGlobals)
88 .enable_feature(Feature::ReferenceTypes)
89 .enable_feature(Feature::Multivalue)
90 // EDITOR_NAMES=1 (with CARGO_PROFILE_EDITOR_STRIP=false) keeps function names for profiling.
91 .debug_info(std::env::var_os("EDITOR_NAMES").is_some())
92 .run(&bg_wasm_path, &opt_path)
93 .context("wasm-opt failed")?;
94 wasm_bytes = fs::read(&opt_path)?;
95 }
96
97 // 4. Content-hash the wasm, then patch and hash the JS glue.
98 let wasm_name = format!("editor-{}.wasm", short_hash(&wasm_bytes));
99 let glue = fs::read_to_string(&glue_path)
100 .with_context(|| format!("reading {}", glue_path.display()))?;
101 let init_name = default_export_name(&glue)?;
102 let mut js = glue;
103 if !js.ends_with('\n') {
104 js.push('\n');
105 }
106 js.push_str(&format!(
107 "await {init_name}({{ module_or_path: new URL(\"./{wasm_name}\", import.meta.url) }});\n"
108 ));
109 let js_name = format!("editor-{}.js", short_hash(js.as_bytes()));
110
111 // 5. Write outputs and manifest into assets/.
112 let assets = root.join("assets");
113 fs::create_dir_all(&assets)?;
114 let js_path = assets.join(&js_name);
115 let wasm_path = assets.join(&wasm_name);
116 let manifest_path = assets.join("editor.manifest");
117 fs::write(&js_path, js.as_bytes())?;
118 fs::write(&wasm_path, &wasm_bytes)?;
119 fs::write(
120 &manifest_path,
121 format!("js={js_name}\nwasm={wasm_name}\n"),
122 )?;
123
124 // 6. Remove older hashed outputs (exact pattern only).
125 let keep: HashSet<&str> = [js_name.as_str(), wasm_name.as_str()].into_iter().collect();
126 for entry in fs::read_dir(&assets)? {
127 let entry = entry?;
128 let file_name = entry.file_name();
129 let Some(name) = file_name.to_str() else { continue };
130 if is_generated_name(name) && !keep.contains(name) && entry.file_type()?.is_file() {
131 fs::remove_file(entry.path())
132 .with_context(|| format!("removing {}", entry.path().display()))?;
133 println!("removed old output {name}");
134 }
135 }
136
137 // 7. Report.
138 println!("init function: {init_name}");
139 for path in [&js_path, &wasm_path, &manifest_path] {
140 let size = fs::metadata(path)?.len();
141 println!(
142 "{}\t{} bytes",
143 path.file_name().unwrap_or_default().to_string_lossy(),
144 size
145 );
146 }
147 println!(
148 "profile: {profile}, elapsed: {:.2}s",
149 started.elapsed().as_secs_f64()
150 );
151 Ok(())
152}
153
154fn short_hash(bytes: &[u8]) -> String {
155 let hex = blake3::hash(bytes).to_hex();
156 hex[..16].to_string()
157}
158
159/// Matches `editor-<16 lowercase hex>.js` or `editor-<16 lowercase hex>.wasm`.
160fn is_generated_name(name: &str) -> bool {
161 let Some(rest) = name.strip_prefix("editor-") else {
162 return false;
163 };
164 if rest.len() < 16 {
165 return false;
166 }
167 let (hash, ext) = rest.split_at(16);
168 (ext == ".js" || ext == ".wasm")
169 && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
170}
171
172/// Finds the name of the default export in the wasm-bindgen glue, e.g. `__wbg_init`.
173fn default_export_name(glue: &str) -> Result<String> {
174 for line in glue.lines() {
175 // wasm-bindgen web output: `export { initSync, __wbg_init as default };`
176 if let Some(idx) = line.find(" as default") {
177 let name = line[..idx]
178 .rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
179 .next()
180 .unwrap_or_default();
181 if line.trim_start().starts_with("export {") && !name.is_empty() {
182 return Ok(name.to_string());
183 }
184 }
185 if let Some(rest) = line.strip_prefix("export default ") {
186 let name: String = rest
187 .trim_end_matches(';')
188 .trim()
189 .chars()
190 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
191 .collect();
192 if !name.is_empty() {
193 return Ok(name);
194 }
195 }
196 }
197 bail!("could not find `export default <init>` in wasm-bindgen output")
198}
199
200fn workspace_root() -> Result<PathBuf> {
201 json_field(&cargo_metadata()?, "workspace_root").map(PathBuf::from)
202}
203
204fn target_dir() -> Result<PathBuf> {
205 json_field(&cargo_metadata()?, "target_directory").map(PathBuf::from)
206}
207
208fn cargo_metadata() -> Result<String> {
209 let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
210 let output = Command::new(cargo)
211 .args(["metadata", "--format-version", "1", "--no-deps"])
212 .output()
213 .context("failed to run cargo metadata")?;
214 if !output.status.success() {
215 bail!("cargo metadata failed");
216 }
217 Ok(String::from_utf8(output.stdout)?)
218}
219
220/// Extracts a top-level string field from cargo metadata JSON without a JSON parser.
221/// Paths on this machine contain no escape sequences, so a plain scan is enough.
222fn json_field(json: &str, key: &str) -> Result<String> {
223 let needle = format!("\"{key}\":\"");
224 let start = json
225 .find(&needle)
226 .with_context(|| format!("`{key}` missing from cargo metadata"))?
227 + needle.len();
228 let end = json[start..]
229 .find('"')
230 .with_context(|| format!("unterminated `{key}`"))?;
231 Ok(json[start..start + end].to_string())
232}