feat(wasm): C4 async fetch/after effects with bridge continuations

Accept ADR 0003: handlers return fetch/after maps; the official bridge
runs Promise/timer work and resumes via mq_call. Add fetch.mq.md demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-01 10:53:11 +08:00
1 parent aac896b044
commit ab52db2037
12 files changed
+374 -52

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); official `loader.js` is host glue only — do not invent a second JS app language for product code.
10. **Browser (route C):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is host glue only.
## Markup → meaning (v0.2)
+1
View File
@@ -6,6 +6,7 @@
- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。
- **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)。
### Fixed
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
+48
View File
@@ -0,0 +1,48 @@
# ADR 0003:浏览器异步 I/O(fetch / 定时)— 效应表 + 续体回调
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-09-01 |
| 决策者 | chaungming + 协作 |
| 相关 | [0002-browser-marqdo-wasm.md](0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
---
## 背景
Marqdo 调用面今日以**同步**为主。浏览器 `fetch` / `setTimeout` 是异步的;若在 WASM 里阻塞等待,会卡死 UI,且 `wasm32-unknown-unknown` 无真实阻塞 HTTP。
C3 已有:`mq_call` 返回 Map(如 `set_text`)由官方 bridge 执行。C4 在同一通道上扩展异步效应。
---
## 决策
1. **不**在语言内核引入 async/await 关键字或假同步 `fetch`。
2. 处理器返回值可含**效应字段**(与 `set_text` 并列),由 **JS bridge** 执行:
- `fetch`: `{ url, method?, then, headers?, body? }`
- `after`: `{ ms, then }`(定时续体)
3. 异步完成后 bridge 调用 `mq_call(then, payload)`:
- fetch 成功/失败:`{ ok, status, body, error? }`
- after:`{ ok: true }`
4. 能力默认关网络语义仍由**返回效应**显式开启(站点作者主动返回 `fetch`);CORS / 鉴权仍是浏览器与服务端责任。
5. 服务端 `lib/net` / `plugins/web` **不变**;本 ADR 仅浏览器 WASM 宿主。
---
## 后果
- 作者用表格/Map 声明「请求谁、完成后调谁」,无手写业务 JS。
- Bridge 必须串行处理效应(先 `set_text`,再调度 `fetch`/`after`)。
- 深层 Promise 链靠多次 `then` 回调;不在 C4 做通用 async 运行时。
---
## 否决
| 方案 | 原因 |
|------|------|
| WASM 内同步阻塞 `fetch` | 卡死主线程;平台不支持 |
| 编译期把 Marqdo 译成 async JS | 回到路线 B |
| 在核心加 `await` 关键字 | 违反 Markup-as-Syntax / 关键字纪律 |
+10 -6
View File
@@ -196,16 +196,20 @@ L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表
---
## 7. 异步模型(C4 才深化)
## 7. 异步模型(C4)
Marqdo 今日调用多为**同步**。浏览器 `fetch` / 定时器是异步的。
锁定:[ADR 0003](../adr/0003-browser-async-effects.md)。
C1–C3 约定:
处理器返回 Map 可含(与 `set_text` 并列):
- 同步子集先完整。
- `fetch`:C4 引入 **宿主 Promise → 续体** 或 **显式 `> 浏览器.请求` 返回 future 句柄 + 轮询/回调表**;需短 ADR 补丁,不在 C1 假装同步阻塞整个页面。
| 字段 | 含义 | 完成后 `mq_call` 实参 |
|------|------|----------------------|
| `fetch` | `{ url, method?, then, headers?, body? }` | `{ ok, status, body, error? }` |
| `after` | `{ ms, then }` | `{ ok: true }` |
在续体方案落地前:网络仍以**服务端** `ext/web` / `lib/net`(native)为主。
Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。
示例见 `examples/browser-hello/fetch.mq.md`。
---
+16 -39
View File
@@ -2,58 +2,35 @@
| | |
|---|---|
| 状态 | **进行中**(C0–C3 已落地) |
| 状态 | **进行中**(C0–C4 已落地) |
| 日期 | 2026-09-01 |
| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.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) |
| 相关 | [interpreter.md](interpreter.md) · [ext-web.md](../design/ext-web.md) · [next-phase.md](next-phase.md) |
实现阶段编号 **C0–C5**(Client / WASM)。每阶段结束须:文档状态更新 + CHANGELOG + 可演示验收。
---
## 总览
| 阶段 | 内容 | 状态 |
|------|------|------|
| **C0** | Cargo feature 骨架;`wasm32` check | **done** |
| **C0** | feature 门控;`wasm32` check | **done** |
| **C1** | `run_source` + `mq_run` | **done** |
| **C2** | loader + `examples/browser-hello` + `marqdo wasm build` | **done** |
| **C3** | 会话 `mq_boot`/`mq_call`;wire 表;`set_text` DOM 回写 | **done** |
| **C4** | `fetch`/定时器异步模型 | pending |
| **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 — 异步效应
## C2 — 示例页与挂载
- Bridge:`applyEffects` 识别返回值中的 `fetch` / `after`
- 完成后 `mq_call(then, payload)`,可再链式效应
- 示例:`fetch.html` + `fetch.mq.md`
```bash
marqdo wasm build -o examples/browser-hello
cd examples/browser-hello && python3 -m http.server 8765
```
**验收:** 点「请求 UUID」后 `#status` 出现 httpbin JSON;点「延迟 pong」约 600ms 后显示 `pong`。
---
## C5
## C3 — 交互装配
见设计硬化项。
- `BrowserSession` + `Interpreter::invoke_in_entry`
- ABI:`mq_boot` / `mq_call`
- 示例:`interact.html` + `counter.mq.md`
- Bridge:`wireEvents` / `applyDomPatch`
**验收:** 打开 interact 页,点「加一」计数递增;源码仅为 `.mq.md` + 官方 bridge。
---
## C4 / C5
见设计文 §7 / §12。
---
## 进度记录
## 进度
| 日期 | 记录 |
|------|------|
| 2026-09-01 | ADR 0002;C0–C1 |
| 2026-09-01 | C2 `wasm build`;C3 session + interact 示例 |
| 2026-09-01 | C0–C3 |
| 2026-09-01 | C4 ADR 0003 + fetch/after demo |
+3 -3
View File
@@ -15,7 +15,7 @@ python3 -m http.server 8765
|----|------|
| [/](http://127.0.0.1:8765/) | C1:编辑源码 → `mq_run` 打印 |
| [/interact.html](http://127.0.0.1:8765/interact.html) | C3:`counter.mq.md` 交互表 → 点击改 DOM |
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | C4:`fetch` / `after` 效应续体 |
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyDomPatch`)
- `counter.mq.md`:作者面只有 `.mq.md`(业务逻辑)
- 设计:[browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyEffects`)
- 业务源码只有 `.mq.md`;异步见 [ADR 0003](../../doc/adr/0003-browser-async-effects.md)
+79
View File
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · fetch / after (C4)</title>
<style>
:root {
--ink: #1a1f1c;
--paper: #e8efe6;
--accent: #2f6f4e;
--muted: #5a6b60;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
color: var(--ink);
background:
radial-gradient(800px 420px at 0% 100%, #d5e4d8 0%, transparent 55%),
linear-gradient(165deg, #f3f7f2, var(--paper));
padding: 2rem clamp(1rem, 4vw, 3rem);
}
h1 {
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
font-weight: 600;
font-size: clamp(1.6rem, 3vw, 2.2rem);
margin: 0 0 0.35rem;
}
.lead { color: var(--muted); margin: 0 0 1.25rem; max-width: 38rem; }
#status {
font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.95rem;
line-height: 1.45;
white-space: pre-wrap;
word-break: break-all;
min-height: 4rem;
margin: 1rem 0 1.25rem;
padding: 0.85rem 1rem;
background: rgba(255,255,255,0.55);
border: 1px solid #b7c7bb;
}
button {
margin-right: 0.5rem;
margin-bottom: 0.4rem;
padding: 0.55rem 1.1rem;
border: 0;
background: var(--accent);
color: #f5faf6;
font: inherit;
cursor: pointer;
}
button.secondary { background: #3a4740; }
button:disabled { opacity: 0.5; cursor: wait; }
pre {
margin-top: 1.5rem;
width: min(42rem, 100%);
padding: 0.9rem 1rem;
background: #122018;
color: #d7eadc;
overflow: auto;
font-size: 0.8rem;
line-height: 1.4;
}
.err { color: #ffb4a8; }
a { color: var(--accent); }
</style>
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">C4:返回 <code>fetch</code> / <code>after</code> 效应,由官方 bridge 续体回调(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
<div id="status">idle</div>
<button id="load" type="button" disabled>请求 UUID</button>
<button id="ping" class="secondary" type="button" disabled>延迟 pong</button>
<pre id="log">loading…</pre>
<script type="module" src="./fetch.js"></script>
</body>
</html>
+52
View File
@@ -0,0 +1,52 @@
import {
applyDomPatch,
boot,
loadWasm,
readCString,
wireEvents,
} from "./marqdo-bridge.js";
async function main() {
const log = document.getElementById("log");
const loadBtn = document.getElementById("load");
const pingBtn = document.getElementById("ping");
let exports;
try {
exports = await loadWasm("./marqdo_wasm.wasm");
} catch (e) {
log.classList.add("err");
log.textContent = String(e);
return;
}
const srcRes = await fetch("./fetch.mq.md");
if (!srcRes.ok) {
log.classList.add("err");
log.textContent = `failed to load fetch.mq.md (${srcRes.status})`;
return;
}
const source = await srcRes.text();
const result = boot(exports, source);
if (!result.ok) {
log.classList.add("err");
log.textContent = result.error || "boot failed";
return;
}
const n = wireEvents(exports, result.value, {
onError: (err) => {
log.classList.add("err");
log.textContent = err;
},
});
applyDomPatch({ set_text: { "#status": "idle" } });
const ver = readCString(exports.memory, exports.mq_version());
log.classList.remove("err");
log.textContent = `marqdo-wasm ${ver} · wired ${n} · ADR 0003 effects\nsource: fetch.mq.md`;
loadBtn.disabled = false;
pingBtn.disabled = false;
}
main();
+50
View File
@@ -0,0 +1,50 @@
---
title: browser fetch (C4)
description: return fetch/after effects; bridge continues via mq_call
import json:lib/json.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#load" | click | load |
| 2 | "#ping" | click | ping |
**`wire`**
## load
*`patch` = > json.set map=None key="#status" value="loading…"*
*`ret` = > json.set map=None key="set_text" value=patch*
*`req` = > json.set map=None key="url" value="https://httpbin.org/uuid"*
*`req` = > json.set map=req key="then" value="on_uuid"*
**> json.set map=ret key="fetch" value=req**
## on_uuid
+ `ok`
+ `status`
+ `body`=""
+ `error`=""
1. ok
*`p` = > json.set map=None key="#status" value=body*
**> json.set map=None key="set_text" value=p**
2. *
*`msg` = "fetch failed"*
*`p` = > json.set map=None key="#status" value=msg*
**> json.set map=None key="set_text" value=p**
## ping
*`patch` = > json.set map=None key="#status" value="wait 600ms…"*
*`ret` = > json.set map=None key="set_text" value=patch*
*`t` = > json.set map=None key="ms" value=600*
*`t` = > json.set map=t key="then" value="on_ping"*
**> json.set map=ret key="after" value=t**
## on_ping
+ `ok`=True
*`p` = > json.set map=None key="#status" value="pong"*
**> json.set map=None key="set_text" value=p**
+1 -1
View File
@@ -62,7 +62,7 @@
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./">打印示例</a></p>
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./fetch.html">fetch (C4)</a> · <a href="./">打印示例</a></p>
<div id="count">0</div>
<button id="bump" type="button" disabled>加一</button>
<button id="reset" class="secondary" type="button" disabled>清零</button>
+92 -2
View File
@@ -64,7 +64,7 @@ export async function loadWasm(url = "./marqdo_wasm.wasm") {
return instance.exports;
}
/** Apply C3 return patches: { set_text: { "#id": "…" } } */
/** Apply C3/C4 return effects: set_text, fetch, after */
export function applyDomPatch(value) {
if (!value || typeof value !== "object") return;
const setText = value.set_text || value.setText;
@@ -76,6 +76,96 @@ export function applyDomPatch(value) {
}
}
/**
* Run sync DOM patches then schedule async effects (ADR 0003).
* Returns a Promise that settles when immediate scheduling is done
* (not when fetch/after callbacks finish).
*/
export function applyEffects(exports, value, { onError } = {}) {
applyDomPatch(value);
if (!value || typeof value !== "object") return Promise.resolve();
const tasks = [];
const fetchSpec = value.fetch;
if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) {
tasks.push(runFetchEffect(exports, fetchSpec, onError));
}
const afterSpec = value.after;
if (afterSpec && typeof afterSpec === "object" && afterSpec.then) {
tasks.push(runAfterEffect(exports, afterSpec, onError));
}
return Promise.all(tasks);
}
async function runFetchEffect(exports, spec, onError) {
const thenFn = spec.then;
const method = (spec.method || "GET").toUpperCase();
const init = { method };
if (spec.headers && typeof spec.headers === "object") {
init.headers = spec.headers;
}
if (spec.body != null && method !== "GET" && method !== "HEAD") {
init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body);
}
try {
const res = await fetch(String(spec.url), init);
const body = await res.text();
const result = call(exports, thenFn, {
ok: res.ok,
status: res.status,
body,
});
if (!result.ok) {
if (onError) onError(result.error);
else console.error(result.error);
return;
}
await applyEffects(exports, result.value, { onError });
if (result.stdout) console.log(result.stdout);
} catch (e) {
try {
const result = call(exports, thenFn, {
ok: false,
status: 0,
body: "",
error: String(e),
});
if (result.ok) await applyEffects(exports, result.value, { onError });
else if (onError) onError(result.error);
} catch (e2) {
if (onError) onError(String(e2));
else console.error(e2);
}
}
}
function runAfterEffect(exports, spec, onError) {
const ms = Math.max(0, Number(spec.ms) || 0);
const thenFn = spec.then;
return new Promise((resolve) => {
setTimeout(() => {
try {
const result = call(exports, thenFn, { ok: true });
if (!result.ok) {
if (onError) onError(result.error);
else console.error(result.error);
resolve();
return;
}
Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve);
if (result.stdout) console.log(result.stdout);
} catch (e) {
if (onError) onError(String(e));
else console.error(e);
resolve();
}
}, ms);
});
}
/**
* Wire events from `# main` return value.
* Accepts a list of row maps, or `{ wire: [...] }`.
@@ -101,7 +191,7 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
else console.error(result.error);
return;
}
applyDomPatch(result.value);
applyEffects(exports, result.value, { onError });
if (result.stdout) console.log(result.stdout);
} catch (e) {
if (onError) onError(String(e));
+21
View File
@@ -108,4 +108,25 @@ import json:lib/json.mq.md
let j2 = value_as_json(&v2).unwrap();
assert_eq!(j2["set_text"]["#out"], "2");
}
#[test]
fn fetch_mq_load_returns_fetch_effect() {
let src = std::fs::read_to_string("examples/browser-hello/fetch.mq.md")
.expect("fetch.mq.md");
let (mut sess, wire) = BrowserSession::boot(&src).expect("boot");
assert!(matches!(wire, Value::List(_)));
let v = sess.call("load", "{}").expect("load");
let j = value_as_json(&v).unwrap();
assert_eq!(j["set_text"]["#status"], "loading…");
assert_eq!(j["fetch"]["then"], "on_uuid");
assert!(j["fetch"]["url"].as_str().unwrap().contains("httpbin"));
let done = sess
.call(
"on_uuid",
r#"{"ok":true,"status":200,"body":"{\"uuid\":\"x\"}"}"#,
)
.expect("on_uuid");
let jd = value_as_json(&done).unwrap();
assert!(jd["set_text"]["#status"].as_str().unwrap().contains("uuid"));
}
}