| 1 | use std::collections::HashSet; |
| 2 | use std::fs; |
| 3 | use std::path::PathBuf; |
| 4 | use std::process::Command; |
| 5 | use std::time::Instant; |
| 6 | |
| 7 | use anyhow::{Context, Result, bail}; |
| 8 | |
| 9 | mod e2e; |
| 10 | mod stress; |
| 11 | |
| 12 | const 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 | |
| 14 | fn 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 | |
| 33 | fn 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 | |
| 40 | let mut build = Command::new(&cargo); |
| 41 | build |
| 42 | .args(["build", "-p", "editor", "--lib", "--target", "wasm32-unknown-unknown"]) |
| 43 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 154 | fn short_hash(bytes: &[u8]) -> String { |
| 155 | let hex = blake3::hash(bytes).to_hex(); |
| 156 | hex[..16].to_string() |
| 157 | } |
| 158 | |
| 159 | |
| 160 | fn 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 | |
| 173 | fn default_export_name(glue: &str) -> Result<String> { |
| 174 | for line in glue.lines() { |
| 175 | |
| 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 | |
| 200 | fn workspace_root() -> Result<PathBuf> { |
| 201 | json_field(&cargo_metadata()?, "workspace_root").map(PathBuf::from) |
| 202 | } |
| 203 | |
| 204 | fn target_dir() -> Result<PathBuf> { |
| 205 | json_field(&cargo_metadata()?, "target_directory").map(PathBuf::from) |
| 206 | } |
| 207 | |
| 208 | fn 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 | |
| 221 | |
| 222 | fn 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 | } |