feat(wasm): C5 release-wasm size profile and build reporting

Add opt-level=z/LTO strip profile, print KiB from marqdo wasm build,
optional wasm-opt, and document tree-only browser sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-01 10:58:42 +08:00
1 parent ab52db2037
commit 04890e0c73
9 files changed
+134 -30

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。
- **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。
- **C4**:[ADR 0003](doc/adr/0003-browser-async-effects.md) 效应表(`fetch` / `after`)+ bridge 续体;[fetch.html](examples/browser-hello/fetch.html)。
- **C5**:`release-wasm` 体积配置;`marqdo wasm build` 报告 KiB 并可选 `wasm-opt`;`run_source` bytecode 单测;会话仍为 tree。
### Fixed
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
+9
View File
@@ -60,3 +60,12 @@ predicates = "=3.1.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
# Size-oriented profile for `marqdo-wasm` (C5). Use: cargo build -p marqdo-wasm --profile release-wasm --target wasm32-unknown-unknown
[profile.release-wasm]
inherits = "release"
lto = true
codegen-units = 1
opt-level = "z"
strip = true
panic = "abort"
+1 -1
View File
@@ -12,4 +12,4 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
serde_json = "1"
serde_json = "1"
+4 -2
View File
@@ -10,10 +10,12 @@ Raw `cdylib` exports — no `wasm-bindgen` CLI required.
| `mq_version` | version C string |
```bash
# from repo root
# from repo root (C5 size profile)
marqdo wasm build -o examples/browser-hello
# or:
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm
```
Prints size in KiB; runs `wasm-opt -Oz` when Binaryen is on `PATH`.
See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
+17 -3
View File
@@ -260,14 +260,28 @@ W8 资源表可增加「挂 wasm / module」行(既有 `page.head` / `头装
| 风险 | 缓解 |
|------|------|
| wasm 体积过大 | 裁剪 feature;后期 `wasm-opt`;bytecode 路径评估 |
| 异步拖垮语言 | C4 单独立项;此前不承诺同步 `fetch` |
| wasm 体积过大 | `release-wasm` profile(`opt-level=z` + LTO + strip);`marqdo wasm build` 打印 KiB,有则跑 `wasm-opt -Oz` |
| 异步拖垮语言 | ADR 0003 效应表;不阻塞 WASM |
| Feature-gate 伤 native | 默认 features = 今日行为;CI 全绿再合 |
| 作者误以浏览器替代服务器安全 | 文档强调鉴权在服务端 |
| 会话要 bytecode | **未做**:`BrowserSession` 固定 tree(缺 entry-env invoke);`run_source` 已支持 bytecode |
---
## 13. 决策摘要
## 14. C5 硬化(已落地子集)
| 项 | 状态 |
|----|------|
| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done |
| 可选 `wasm-opt` | done(Binaryen 在 PATH 时) |
| `run_source` bytecode 金样 | done(单元测) |
| 会话 bytecode / view 断点复用同一 wasm | **后续** |
预算:`release-wasm` 实测约 **0.9 MiB** 未压缩(嵌入 `lib/` 后);gzip/CDN 另计。目标维持 **≤ ~1.2 MiB**。
---
## 15. 决策摘要
| 问题 | 答案 |
|------|------|
+14 -16
View File
@@ -2,9 +2,9 @@
| | |
|---|---|
| 状态 | **进行中**(C0–C4 已落地) |
| 状态 | **C0–C5 首轮完结**(会话 bytecode / view 复用仍可加深) |
| 日期 | 2026-09-01 |
| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003 异步效应](../adr/0003-browser-async-effects.md) |
| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) |
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) |
| 阶段 | 内容 | 状态 |
@@ -12,25 +12,23 @@
| **C0** | feature 门控;`wasm32` check | **done** |
| **C1** | `run_source` + `mq_run` | **done** |
| **C2** | loader + `marqdo wasm build` | **done** |
| **C3** | `mq_boot`/`mq_call`;wire;`set_text` | **done** |
| **C4** | `fetch` / `after` 效应 + 续体(ADR 0003) | **done** |
| **C5** | bytecode / 体积 / view 调试 | pending |
## C4 — 异步效应
- Bridge:`applyEffects` 识别返回值中的 `fetch` / `after`
- 完成后 `mq_call(then, payload)`,可再链式效应
- 示例:`fetch.html` + `fetch.mq.md`
**验收:** 点「请求 UUID」后 `#status` 出现 httpbin JSON;点「延迟 pong」约 600ms 后显示 `pong`。
| **C3** | session wire + `set_text` | **done** |
| **C4** | `fetch` / `after` 效应 | **done** |
| **C5** | `release-wasm` 体积;`wasm-opt`;`run_source` bytecode 测 | **done**(会话仍 tree) |
## C5
见设计硬化项。
```bash
marqdo wasm build -o examples/browser-hello # prints KiB; wasm-opt if installed
```
- Profile:`release-wasm`(`opt-level=z`, LTO, strip)
- `BrowserSession` 明确拒绝 bytecode(待 VM entry-env)
- 一发 `run_source(..., backend=bytecode)` 单测绿
## 进度
| 日期 | 记录 |
|------|------|
| 2026-09-01 | C0–C3 |
| 2026-09-01 | C4 ADR 0003 + fetch/after demo |
| 2026-09-01 | C0–C4 |
| 2026-09-01 | C5 体积 profile + 文档 |
+20
View File
@@ -8,8 +8,12 @@ use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module_from_source;
use crate::value::Value;
use crate::Backend;
/// Persistent Marqdo program for the browser host bridge.
///
/// Session calls (`call`) use the **tree** interpreter so entry bindings persist
/// across handlers (C3). One-shot [`crate::run_source`] may still use bytecode.
pub struct BrowserSession {
module: Module,
interp: Interpreter,
@@ -18,9 +22,17 @@ pub struct BrowserSession {
impl BrowserSession {
/// Parse source, run `# main`, keep entry bindings for later [`Self::call`].
pub fn boot(source: &str) -> Result<(Self, Value)> {
Self::boot_with(source, Backend::Tree)
}
/// Like [`Self::boot`]. `Backend::Bytecode` is rejected for sessions (no shared entry env yet).
pub fn boot_with(source: &str, backend: Backend) -> Result<(Self, Value)> {
if source.trim().is_empty() {
bail!("source is empty");
}
if backend != Backend::Tree {
bail!("browser session requires tree backend (bytecode has no entry-env invoke yet)");
}
let module = load_module_from_source(source)?;
let caps = HostCaps {
fs_write: false,
@@ -129,4 +141,12 @@ import json:lib/json.mq.md
let jd = value_as_json(&done).unwrap();
assert!(jd["set_text"]["#status"].as_str().unwrap().contains("uuid"));
}
#[test]
fn session_rejects_bytecode_backend() {
let err = BrowserSession::boot_with("# main\n\n> print text=x\n", Backend::Bytecode)
.err()
.expect("err");
assert!(err.to_string().contains("tree backend"));
}
}
+8
View File
@@ -369,4 +369,12 @@ mod tests {
.expect("run_source");
assert_eq!(cap.stdout, "Hello World!\n");
}
#[test]
fn run_source_hello_bytecode() {
let mut opts = RunOptions::default();
opts.backend = Backend::Bytecode;
let cap = run_source("# main\n\n> print text=Hello World!\n", &opts).expect("bc");
assert_eq!(cap.stdout, "Hello World!\n");
}
}
+60 -8
View File
@@ -5,7 +5,7 @@ use std::process::Command;
use anyhow::{bail, Context, Result};
/// Build release wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`.
/// Build size-optimized wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`.
pub fn build_wasm(out_dir: &Path) -> Result<()> {
let status = Command::new("cargo")
.args([
@@ -14,18 +14,24 @@ pub fn build_wasm(out_dir: &Path) -> Result<()> {
"marqdo-wasm",
"--target",
"wasm32-unknown-unknown",
"--release",
"--profile",
"release-wasm",
])
.status()
.context("failed to spawn cargo (is it on PATH?)")?;
if !status.success() {
bail!("cargo build -p marqdo-wasm failed with {status}");
bail!("cargo build -p marqdo-wasm --profile release-wasm failed with {status}");
}
let artifact = find_wasm_artifact()?;
let mut artifact = find_wasm_artifact()?;
std::fs::create_dir_all(out_dir)
.with_context(|| format!("create {}", out_dir.display()))?;
let dest = out_dir.join("marqdo_wasm.wasm");
if let Some(optimized) = try_wasm_opt(&artifact)? {
artifact = optimized;
}
std::fs::copy(&artifact, &dest).with_context(|| {
format!(
"copy {} → {}",
@@ -33,22 +39,68 @@ pub fn build_wasm(out_dir: &Path) -> Result<()> {
dest.display()
)
})?;
println!("wrote {}", dest.display());
let bytes = std::fs::metadata(&dest)
.map(|m| m.len())
.unwrap_or(0);
println!(
"wrote {} ({:.1} KiB)",
dest.display(),
bytes as f64 / 1024.0
);
Ok(())
}
/// Run `wasm-opt -Oz` when Binaryen is installed; returns path to optimized file.
fn try_wasm_opt(input: &Path) -> Result<Option<PathBuf>> {
let which = Command::new("wasm-opt").arg("--version").output();
let Ok(out) = which else {
return Ok(None);
};
if !out.status.success() {
return Ok(None);
}
let tmp = input.with_extension("opt.wasm");
let status = Command::new("wasm-opt")
.args(["-Oz", "--enable-bulk-memory"])
.arg(input)
.arg("-o")
.arg(&tmp)
.status()
.context("wasm-opt spawn failed")?;
if !status.success() {
// Retry without bulk-memory flag for older binaryen.
let status2 = Command::new("wasm-opt")
.args(["-Oz"])
.arg(input)
.arg("-o")
.arg(&tmp)
.status()
.context("wasm-opt spawn failed")?;
if !status2.success() {
eprintln!("warning: wasm-opt failed; keeping cargo artifact");
return Ok(None);
}
}
println!("wasm-opt: {}", tmp.display());
Ok(Some(tmp))
}
fn find_wasm_artifact() -> Result<PathBuf> {
let mut candidates = Vec::new();
if let Ok(td) = std::env::var("CARGO_TARGET_DIR") {
candidates.push(
PathBuf::from(td)
.join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
PathBuf::from(&td).join("wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm"),
);
candidates.push(
PathBuf::from(td).join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
);
}
candidates.push(PathBuf::from(
"target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm",
));
candidates.push(PathBuf::from(
"target/wasm32-unknown-unknown/release/marqdo_wasm.wasm",
));
// Workspace may place target next to crates when invoked oddly — still try root.
for c in &candidates {
if c.is_file() {
return Ok(c.clone());