外部适配器契约(客户 / 伙伴用 · 提案 · 2026-11-16)
目标:把你的系统接进 modu,不改 modu 内核。 两条路,都不需要在 modu 里写代码:
- 数据:写一个只读 REST 服务,把它声明成
rest数据源。- 界面:写一个网页,用
Embed物料嵌进来(iframe + postMessage)。这两条是已上线能力(
packages/core/src/rest/dataProvider.ts、packages/core/src/spec/materials/embed.tsx), 本文只是把它写成一份可对接的契约。内部分层与取舍见 project-extension-contract.md。
0. 一分钟版
你的系统 ──(只读 HTTP GET)──▶ modu 页面 / 规则 / 报表
你的页面 ──(iframe + postMessage)──▶ modu 的 Embed 物料
modu 对你只有两个要求:数据接口只读、嵌入页面的 origin 明确。
1. 数据契约:REST 适配器
1.1 modu 会调哪些接口(只有 GET)
| 用途 | 请求 |
|---|---|
| 列表 | GET {baseUrl}{pathPrefix?}/{resource}?<分页><排序><筛选> |
| 单条 | GET {baseUrl}{pathPrefix?}/{resource}/{id} |
| 批量取 | GET {baseUrl}{pathPrefix?}/{resource}?id=1&id=2 |
没有任何写方法。create / update / deleteOne 在 modu 侧发请求之前就抛
ReadOnlyViolationError(rest/dataProvider.ts 头注释:铁律 2 只允许 GET/HEAD)。
需要写回你的系统时,走 modu 的 integrations.json(集成调用),不要指望数据源。
1.2 分页(三选一,在数据源配置里选)
| 配置值 | 请求参数 |
|---|---|
page-pageSize(默认,simple-rest 风格) | current=1&pageSize=20 |
page-size(DRF 风格) | page=1&page_size=20 |
skip-limit(FastAPI / 常见) | skip=0&limit=20 |
1.3 排序与筛选(固定命名)
- 排序:
_sort=<字段>&_order=asc|desc - 筛选(
eq默认):<字段>=<值> - 其他操作符:
<字段>_<operator>=<值>(如age_gte=18) - 包含:
<字段>_like=<值> - 前缀:
<字段>_like=<值>% - 多值:重复同名参数
<字段>=a&<字段>=b
你的服务不必实现全部操作符:不认识的就忽略或返回 400 并在错误体里说明。 modu 会按页面实际用到的筛选发请求。
1.4 响应形态(四选一,在数据源配置里选)
| 配置值 | 列表响应 |
|---|---|
simple-rest(默认) | { "data": [...], "total": 123 };也接受裸数组(此时 total 从 x-total-count 头取) |
drf | { "count": 123, "next": "...", "previous": "...", "results": [...] } |
fastapi | { "items": [...], "total": 123 } |
array | [ ... ],total 取 x-total-count |
单条响应:{ "data": { ... } } 或裸对象。字段名就是页面上显示的列名。
1.5 认证(三选一)
| 配置值 | 做法 | 纪律 |
|---|---|---|
none | 不带凭据 | 仅限内网 / 只读公开数据 |
env + apiKeyRef | modu 运行时从环境变量取值,加到 authHeaderName(默认 Authorization,前缀 authScheme 默认 "Bearer ") | 只存变量名,禁明文;值由部署方注入 |
tokenEndpoint | 先 POST/GET 你的授权端点拿 token,再带在请求头 | 必须同源(推荐经反向代理);这是唯一允许的非 GET 请求,且只用于认证 |
1.6 错误约定
- 非 2xx → modu 把该资源标记为加载失败并在界面显示错误;不会重试写操作(因为没有写)。
- 建议错误体:
{ "message": "人话原因" }。 - 4xx 表示「请求不合法」(筛选不认识、参数缺),5xx 表示「你那边挂了」——别把两者混用,排障会变慢。
1.7 最小可用适配器(Node,约 30 行)
import { createServer } from "node:http";
const rows = [ // 你的真实数据源在这里
{ id: 1, name: "一号机", status: "running" },
{ id: 2, name: "二号机", status: "stopped" },
];
createServer((req, res) => {
const url = new URL(req.url, "http://x");
if (req.method !== "GET") return res.writeHead(405).end('{"message":"read-only"}');
const [, resource, id] = url.pathname.split("/"); // /items → resource=items, id=undefined
if (resource !== "items") return res.writeHead(404).end('{"message":"unknown resource"}');
const send = (body) => { res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(body)); };
if (id) return send({ data: rows.find((r) => String(r.id) === id) ?? null });
let out = rows.filter((r) => // 只做 eq 筛选,够用就行
Object.entries(Object.fromEntries(url.searchParams)).every(([k, v]) => k.startsWith("_") || k === "current" || k === "pageSize" || String(r[k]) === v));
const sort = url.searchParams.get("_sort"); const order = url.searchParams.get("_order") ?? "asc";
if (sort) out = out.sort((a, b) => (a[sort] > b[sort] ? 1 : -1) * (order === "desc" ? -1 : 1));
const size = Number(url.searchParams.get("pageSize") ?? 20);
const cur = Number(url.searchParams.get("current") ?? 1);
send({ data: out.slice((cur - 1) * size, cur * size), total: out.length });
}).listen(7100, "127.0.0.1");
Pro 连接器清单放 .modu/connectors/<id>.json(version/id/kind/title/plugin);base modu check 校验形状、plugin=datasource.<kind>,并交叉校验 datasources.json 的 connector 引用。
声明(.modu/datasources.json):
{ "id": "plant", "kind": "rest", "label": "设备系统", "baseUrl": "http://127.0.0.1:7100",
"resources": ["items"], "probeResource": "items", "responseShape": "simple-rest" }
跑 modu check,再刷新页面就能在资源里看到 plant:items。
2. 界面契约:Embed 物料
用于「modu 内置物料表达不了」的界面:专业图表、地图、三维、第三方编辑器。 做法是你写一个普通网页,modu 用 iframe 嵌它,双方只通过 postMessage 说话。
2.1 页面里怎么用
{ "id": "chart", "type": "Embed",
"props": { "src": "https://bi.example.com/panel/42",
"allowDomains": ["https://bi.example.com"],
"auth": "modu-session", "height": 560, "title": "产能看板" } }
| prop | 说明 |
|---|---|
src | 你的页面地址(https,或同源) |
allowDomains | 必填:允许的 origin 列表(逐字匹配,含协议与端口) |
auth | "none"(默认)或 "modu-session"(宿主把当前 JWT 投给你) |
height | 初始高度(之后按你上报的高度调整) |
title | iframe 的标题(可访问性) |
2.2 消息契约(只有三条)
| 方向 | type | 负载 | 时机 |
|---|---|---|---|
| 宿主 → 子 | oct-modu-host:token | { token } | 你发 ready 后、且 auth: "modu-session" 时 |
| 子 → 宿主 | oct-modu-embed:ready | {} | 页面初始化完成,可以收 token 了 |
| 子 → 宿主 | oct-modu-embed:height | { height: 120..4000 } | 内容高度变化时(越界值被忽略) |
2.3 安全纪律(两侧都必须守)
- 宿主侧:只消费
allowDomains里的 origin;targetOrigin用事件来源的具体 origin,永不用*。 - 你这边:发消息时也指定
targetOrigin(modu 的 origin),不要*;收到的 token 只放内存,别写 localStorage。 - 不要试图访问父窗口 DOM;不要依赖
window.parent上的任何东西。
2.4 最小嵌入页(20 行)
<!doctype html><meta charset="utf-8"><title>panel</title>
<body style="margin:0"><div id="app">loading…</div>
<script>
const MODU = "https://modu.example.com"; // 宿主 origin(部署时定)
const say = (type, extra = {}) => parent.postMessage({ type, ...extra }, MODU);
window.addEventListener("message", (e) => {
if (e.origin !== MODU) return; // 逐字校验,别只看 e.data
if (e.data?.type === "oct-modu-host:token") {
window.__token = e.data.token; // 只放内存
document.getElementById("app").textContent = "已拿到会话,开始加载…";
}
});
new ResizeObserver(() => say("oct-modu-embed:height", { height: document.body.scrollHeight })).observe(document.body);
say("oct-modu-embed:ready");
</script>
3. 版本与兼容
| 契约 | 版本 | 兼容策略 |
|---|---|---|
| REST 适配器 | v1 | 只增不改:新增响应形态/分页风格是可选项,老配置不受影响 |
| Embed 消息 | v1 | 只增不改:新增消息类型时,不认识的 type 必须忽略(两侧都是) |
两边的契约都是「请求形状 + JSON 形状」,不涉及 modu 内部类型,因此 modu 升级不需要你改代码。
4. 接入清单
- 数据接口只实现了 GET(写接口另开,不要塞进适配器)
- 分页/响应形态/认证三处配置与实现对得上(
modu check会校验取值) - 筛选参数:不认识的忽略或 400 + 人话错误
-
total正确(分页器靠它) - 凭据只以环境变量名出现在配置里(
apiKeyRef),值不进 git - 嵌入页:
allowDomains写全(协议+端口),postMessage指定targetOrigin - 嵌入页上报
ready与height
5. 不做什么
- 不经适配器写数据:写回你的系统请用 modu 的集成调用(
integrations.json),或你的页面自己调你的接口。 - 不在适配器里做业务计算:适配器只负责「把数据取出来」。计算写 modu 的
rules.json(阈值进参数)或你的系统。 - 不把机密放进前端:
apiKeyRef只是引用名;跨域授信走tokenEndpoint同源代理。 - 不依赖 iframe 之外的能力:DOM、store、路由参数都拿不到,只有 postMessage 这三条消息。
源文件 · mesa/docs/requirements/external-adapter-contract.md