Skip to content

Commit

Permalink
Improve output of re_build_web_viewer (rerun-io#5913)
Browse files Browse the repository at this point in the history
### What
…and catch failure to run wasm-opt

Review ignoring whitespace changes

### Checklist
* [x] I have read and agree to [Contributor
Guide](https://github.com/rerun-io/rerun/blob/main/CONTRIBUTING.md) and
the [Code of
Conduct](https://github.com/rerun-io/rerun/blob/main/CODE_OF_CONDUCT.md)
* [x] I've included a screenshot or gif (if applicable)
* [x] I have tested the web demo (if applicable):
* Using newly built examples:
[rerun.io/viewer](https://rerun.io/viewer/pr/5913)
* Using examples from latest `main` build:
[rerun.io/viewer](https://rerun.io/viewer/pr/5913?manifest_url=https://app.rerun.io/version/main/examples_manifest.json)
* Using full set of examples from `nightly` build:
[rerun.io/viewer](https://rerun.io/viewer/pr/5913?manifest_url=https://app.rerun.io/version/nightly/examples_manifest.json)
* [x] The PR title and labels are set such as to maximize their
usefulness for the next release's CHANGELOG
* [x] If applicable, add a new check to the [release
checklist](https://github.com/rerun-io/rerun/blob/main/tests/python/release_checklist)!

- [PR Build Summary](https://build.rerun.io/pr/5913)
- [Recent benchmark results](https://build.rerun.io/graphs/crates.html)
- [Wasm size tracking](https://build.rerun.io/graphs/sizes.html)
  • Loading branch information
emilk authored Apr 11, 2024
1 parent fe326a2 commit 53116cf
Showing 1 changed file with 96 additions and 75 deletions.
171 changes: 96 additions & 75 deletions crates/re_build_web_viewer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

//! Build the Rerun web-viewer .wasm and generate the .js bindings for it.
use std::time::Instant;

use anyhow::Context as _;
use cargo_metadata::camino::{Utf8Path, Utf8PathBuf};

Expand Down Expand Up @@ -61,7 +63,7 @@ pub fn build(
) -> anyhow::Result<()> {
std::env::set_current_dir(workspace_root())?;

eprintln!("Building web viewer wasm…");
eprintln!("Building web viewer\n");

let crate_name = "re_viewer";

Expand Down Expand Up @@ -89,88 +91,102 @@ pub fn build(
std::fs::remove_file(wasm_path.clone()).ok();
std::fs::remove_file(js_path).ok();

// --------------------------------------------------------------------------------
eprintln!("Compiling rust to wasm in {target_wasm_dir}…");

let mut cmd = std::process::Command::new("cargo");
cmd.args([
"build",
"--quiet",
"--package",
crate_name,
"--lib",
"--target",
"wasm32-unknown-unknown",
"--target-dir",
target_wasm_dir.as_str(),
"--no-default-features",
"--features=analytics",
]);
if profile == Profile::Release {
cmd.arg("--release");
}
{
eprintln!("Compiling Rust to wasm in {target_wasm_dir}…");
let start_time = Instant::now();

let mut cmd = std::process::Command::new("cargo");
cmd.args([
"build",
"--quiet",
"--package",
crate_name,
"--lib",
"--target",
"wasm32-unknown-unknown",
"--target-dir",
target_wasm_dir.as_str(),
"--no-default-features",
"--features=analytics",
]);
if profile == Profile::Release {
cmd.arg("--release");
}

// This is required to enable the web_sys clipboard API which egui_web uses
// https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Clipboard.html
// https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
// Furthermore, it's necessary for unstable WebGPU apis to work.
cmd.env("RUSTFLAGS", "--cfg=web_sys_unstable_apis");

// When executing this script from a Rust build script, do _not_, under any circumstances,
// allow pre-encoded `RUSTFLAGS` to leak into the current environment.
// These pre-encoded flags are generally generated by Cargo itself when loading its
// configuration from e.g. `$CARGO_HOME/config.toml`; which means they will contain
// values that only make sense for the native target host, not for a wasm build.
cmd.env("CARGO_ENCODED_RUSTFLAGS", "--cfg=web_sys_unstable_apis");

eprintln!("{root_dir}> {cmd:?}");
let status = cmd
.current_dir(root_dir)
.status()
.context("Failed to build Wasm")?;
assert!(status.success(), "Failed to build Wasm");
// This is required to enable the web_sys clipboard API which egui_web uses
// https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Clipboard.html
// https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
// Furthermore, it's necessary for unstable WebGPU apis to work.
cmd.env("RUSTFLAGS", "--cfg=web_sys_unstable_apis");

// --------------------------------------------------------------------------------
eprintln!("Generating JS bindings for wasm…");

let build = profile.as_str();

let target_wasm_path = target_wasm_dir
.join("wasm32-unknown-unknown")
.join(build)
.join(format!("{crate_name}.wasm"));

let mut bindgen_cmd = wasm_bindgen_cli_support::Bindgen::new();
bindgen_cmd
.input_path(target_wasm_path.as_str())
.out_name(crate_name);
match target {
Target::Browser => bindgen_cmd.no_modules(true)?.typescript(false),
Target::Module => bindgen_cmd.no_modules(false)?.typescript(true),
};
if let Err(err) = bindgen_cmd.generate(build_dir.as_str()) {
if err
.to_string()
.starts_with("cannot import from modules (`env`")
{
// Very common error: "cannot import from modules (`env`) with `--no-modules`"
anyhow::bail!(
// When executing this script from a Rust build script, do _not_, under any circumstances,
// allow pre-encoded `RUSTFLAGS` to leak into the current environment.
// These pre-encoded flags are generally generated by Cargo itself when loading its
// configuration from e.g. `$CARGO_HOME/config.toml`; which means they will contain
// values that only make sense for the native target host, not for a wasm build.
cmd.env("CARGO_ENCODED_RUSTFLAGS", "--cfg=web_sys_unstable_apis");

eprintln!("{root_dir}> {cmd:?}");
let status = cmd
.current_dir(root_dir)
.status()
.context("Failed to build Wasm")?;

anyhow::ensure!(status.success(), "Failed to build Wasm");

eprintln!(
"Web viewer .wasm built in {:.1}s\n",
start_time.elapsed().as_secs_f32()
);
}

{
eprintln!("Generating JS bindings for wasm…");
let start_time = Instant::now();

let build = profile.as_str();

let target_wasm_path = target_wasm_dir
.join("wasm32-unknown-unknown")
.join(build)
.join(format!("{crate_name}.wasm"));

let mut bindgen_cmd = wasm_bindgen_cli_support::Bindgen::new();
bindgen_cmd
.input_path(target_wasm_path.as_str())
.out_name(crate_name);
match target {
Target::Browser => bindgen_cmd.no_modules(true)?.typescript(false),
Target::Module => bindgen_cmd.no_modules(false)?.typescript(true),
};
if let Err(err) = bindgen_cmd.generate(build_dir.as_str()) {
if err
.to_string()
.starts_with("cannot import from modules (`env`")
{
// Very common error: "cannot import from modules (`env`) with `--no-modules`"
anyhow::bail!(
"Failed to run wasm-bindgen: {err}. This is often because some dependency is calling `std::time::Instant::now()` or similar. You can try diagnosing this with:\n\
wasm2wat {target_wasm_path} | rg '\"env\"'\n\
wasm2wat {target_wasm_path} | rg 'call .now\\b' -B 20\n\
\n\
You can also try https://rustwasm.github.io/twiggy/usage/command-line-interface/paths.html#twiggy-paths
"
);
} else {
return Err(err.context("Failed to run wasm-bindgen"));
} else {
return Err(err.context("Failed to run wasm-bindgen"));
}
}
}

// --------------------------------------------------------------------------------
eprintln!(
"Generated JS bindings in {:.1}s\n",
start_time.elapsed().as_secs_f32()
);
}

if profile == Profile::Release {
eprintln!("Optimizing wasm with wasm-opt…");
let start_time = Instant::now();

// to get wasm-opt: apt/brew/dnf install binaryen
let mut cmd = std::process::Command::new("wasm-opt");
Expand All @@ -186,12 +202,17 @@ pub fn build(
.current_dir(root_dir)
.output()
.context("Failed to run wasm-opt, it may not be installed")?;
if !output.status.success() {
eprintln!(
"Failed to run wasm-opt:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}

anyhow::ensure!(
output.status.success(),
"Failed to run wasm-opt:\n{}",
String::from_utf8_lossy(&output.stderr),
);

eprintln!(
"Optimized wasm in {:.1}s\n",
start_time.elapsed().as_secs_f32()
);
}

// --------------------------------------------------------------------------------
Expand Down

0 comments on commit 53116cf

Please sign in to comment.