migrate: own the HTTP domain module as an explicit package

Move the pre-migration net/http.mq.md content into this repository's package
entry, replacing the bundle-relative utf8 import with the public std:text/utf8
dependency. The module leaves the default Bundle and is consumed through the
explicit @http package import; the original domain test and its baseline
terminal value are carried over unchanged.

Refs cflmy/marqdo#9, cflmy/marqdo-ext-http#1
This commit was merged in pull request #2.
This commit is contained in:
cflmy committed 2026-11-27 00:07:52 +08:00
1 parent f2dde4234c
commit 368b33d241
8 files changed
+713 -6

No files matched your search

+35 -5
View File
@@ -1,14 +1,44 @@
# marqdo-ext-http
本仓负责HTTP、URL、SSE 与报文生命周期。当前状态为 `planned`。
本仓负责HTTP 报文编解码(显式 Package)。当前处于**标准库源码归位迁移**阶段:领域模块已迁入本仓作为显式 Package,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-ext-http/issues/1))。
## 首项任务
## 现行形态:显式 Package,不进入默认 Bundle
**大改**。把现有 HTTP 迁为基于 std-net 的独立包,覆盖 URL、消息编解码、请求生命周期和 SSE。
- 入口:`index.mq.md`(`marqdo.yaml` 声明 package)。
- 消费者声明依赖并用公开 `@alias` 导入:
```yaml
# consumer/marqdo.yaml
dependencies:
http:
git: https://git.cflmy.cn/cflmy/marqdo-ext-http
rev: <精确提交>
```
```markdown
---
import:
http: "@http"
---
## @exec main
`return http.<函数>(...)`
```
- 不再以 `std:http` 提供,不保留隐藏 fallback;默认标准库 Bundle 不包含本模块。
- 测试:`scripts/test.sh` 只接受 `MARQDO_BIN` + `MARQDO_STDLIB_DIR`,用临时消费者工程经 `marqdo lock` 与 `@alias` 公开导入执行。
`index.mq.md`:原 `net/http.mq.md` 的报文/响应解析与请求构建函数,公开为 Package 入口(消费者通过 `@http` 导入)
## 边界
不进入默认 Bundle,不提供 `std:net/http`;不实现完整 HTTP Client/Server、SSE、HTTP/2(另行开发);不新增 Host 请求,底层仍使用现行通用资源/字流能力。
## 目录
- [modules/](modules/README.md) 存放对外发布的模块源码。
- [tests/](tests/README.md) 存放独立验收用的输入和断言。
- `index.mq.md`:Package 入口与唯一公开入口。
- `tests/`:迁入的领域测试源与期望。
- `scripts/`:独立验收入口。
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
+436
View File
@@ -0,0 +1,436 @@
---
import:
utf8: "std:text/utf8"
---
# @exec http
## 切片字节
`params(字节, 起, 止)`
**结果 = []**
**下标 = 起**
`while 下标 < 止 and 下标 < 长度(字节)`
**结果 = list.append(结果, 字节[下标])**
**下标 = 下标 + 1**
`end`
`return 结果`
## 找子串
`params(字节, 子, 起点)`
**结果 = 0 - 1**
**下标 = 起点**
`while 下标 + 长度(子) <= 长度(字节) and 结果 < 0`
**偏移 = 0**
**匹配 = true**
`while 偏移 < 长度(子) and 匹配`
`if 字节[下标 + 偏移] != 子[偏移]`
**匹配 = false**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**偏移 = 偏移 + 1**
`end`
`if 匹配`
**结果 = 下标**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 结果`
## 找字符
`params(字节, 值, 起点)`
**结果 = 0 - 1**
**下标 = 起点**
`while 下标 < 长度(字节) and 结果 < 0`
`if 字节[下标] == 值`
**结果 = 下标**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 结果`
## 十六进制值
`params(字节)`
**数值 = 0**
**下标 = 0**
`while 下标 < 长度(字节)`
**值 = 字节[下标]**
`if 值 >= 48 and 值 <= 57`
**数值 = 数值 * 16 + 值 - 48**
`else`
`if 值 >= 65 and 值 <= 70`
**数值 = 数值 * 16 + 值 - 55**
`else`
`if 值 >= 97 and 值 <= 102`
**数值 = 数值 * 16 + 值 - 87**
`else`
`if true`
**忽略 = 0**
`end`
`end`
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 数值`
## 文本字节
`params(文本)`
把 UTF-8 文本编码为字节列表,上限 8 MiB。
**内存 = memory.new(128, 128)**
**字节数 = utf8.编码(文本, 内存, 0)**
**结果 = []**
**下标 = 0**
`while 下标 < 字节数`
**结果 = list.append(结果, 内存[下标])**
**下标 = 下标 + 1**
`end`
`return 结果`
## 字节文本
`params(字节)`
把字节列表按 UTF-8 解码为文本,上限 8 MiB。
**长度值 = 长度(字节)**
`if 长度值 == 0`
`return {ok: true, value: ""}`
`end`
**页 = (长度值 + 65535) // 65536**
**内存 = memory.new(页, 页)**
**下标 = 0**
`while 下标 < 长度值`
**内存[下标] = 字节[下标]**
**下标 = 下标 + 1**
`end`
`return utf8.解码(内存, 0, 长度值)`
## 解码分块字节
`params(体)`
**结果 = []**
**位置 = 0**
**错误 = ""**
`while 位置 < 长度(体) and 错误 == ""`
**行尾 = 找子串(体, [13, 10], 位置)**
`if 行尾 < 0`
**错误 = "http.chunked"**
`else`
`if true`
**大小 = 十六进制值(切片字节(体, 位置, 行尾))**
`if 大小 == 0`
**位置 = 长度(体)**
`else`
`if 位置 + 大小 + 4 > 长度(体)`
**错误 = "http.chunked"**
`else`
`if true`
**结果 = list.concat(结果, 切片字节(体, 行尾 + 2, 行尾 + 2 + 大小))**
**位置 = 行尾 + 2 + 大小 + 2**
`end`
`end`
`end`
`end`
`end`
`end`
`if 错误 != ""`
`return {ok: false, code: 错误, message: "分块长度无效"}`
`end`
`return {ok: true, value: 结果}`
## 解析响应字节
`params(字节)`
解析 HTTP/1.1 响应字节。头部按 ASCII 解析,正文保持原始字节;chunked
长度以字节计。成功返回 {ok:true, value:{status, reason, headers, body}}。
**头部结束 = 找子串(字节, [13, 10, 13, 10], 0)**
`if 头部结束 < 0`
`return {ok: false, code: "http.invalid", message: "缺少头部结束"}`
`end`
**头部 = 切片字节(字节, 0, 头部结束)**
**体 = 切片字节(字节, 头部结束 + 4, 长度(字节))**
**行列表 = []**
**行起 = 0**
**下一行 = 找子串(头部, [13, 10], 0)**
`while 下一行 >= 0`
**行列表 = list.append(行列表, 切片字节(头部, 行起, 下一行))**
**行起 = 下一行 + 2**
**下一行 = 找子串(头部, [13, 10], 行起)**
`end`
**行列表 = list.append(行列表, 切片字节(头部, 行起, 长度(头部)))**
`if 长度(行列表) == 0`
`return {ok: false, code: "http.invalid", message: "缺少状态行"}`
`end`
**状态行 = 字节文本(行列表[0])**
`if not 状态行.ok`
`return {ok: false, code: "http.invalid", message: "状态行不是 ASCII"}`
`end`
**状态字节 = 行列表[0]**
**第一空格 = 找字符(状态字节, 32, 0)**
**第二空格 = 找字符(状态字节, 32, 第一空格 + 1)**
`if 第一空格 < 0 or 第二空格 < 0`
`return {ok: false, code: "http.invalid", message: "状态行格式无效"}`
`end`
**状态文本 = 字节文本(切片字节(状态字节, 第一空格 + 1, 第二空格))**
`if not 状态文本.ok`
`return {ok: false, code: "http.invalid", message: "状态码不是 ASCII"}`
`end`
**状态 = 整数(状态文本.value)**
**原因 = 字节文本(切片字节(状态字节, 第二空格 + 1, 长度(状态字节)))**
`if not 原因.ok`
`return {ok: false, code: "http.invalid", message: "原因短语不是 ASCII"}`
`end`
**头 = {}**
**行号 = 1**
`while 行号 < 长度(行列表)`
**行 = 行列表[行号]**
**冒号 = 找字符(行, 58, 0)**
`if 冒号 >= 0`
**名 = 字节文本(切片字节(行, 0, 冒号))**
**值 = 字节文本(切片字节(行, 冒号 + 2, 长度(行)))**
`if 名.ok and 值.ok`
**头 = map.set(头, 名.value, 值.value)**
`else`
`if true`
**忽略 = 0**
`end`
`end`
`else`
`if true`
**忽略 = 0**
`end`
`end`
**行号 = 行号 + 1**
`end`
**传输 = map.get(头, "Transfer-Encoding")**
**解码后 = 体**
`if 传输 == "chunked"`
**分块 = 解码分块字节(体)**
`if not 分块.ok`
`return 分块`
`end`
**解码后 = 分块.value**
`else`
`if true`
**忽略 = 0**
`end`
`end`
`return {ok: true, value: {status: 状态, reason: 原因.value, headers: 头, body: 解码后}}`
## 解析响应
`params(文本)`
兼容文本 API:按字节解析后,把正文按 UTF-8 解码。
**响应 = 解析响应字节(文本字节(文本))**
`if not 响应.ok`
`return {状态: 0, 原因: "", 头: {}, 体: ""}`
`end`
**正文 = 字节文本(响应.value.body)**
`if not 正文.ok`
`return {状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: ""}`
`end`
`return {状态: 响应.value.status, 原因: 响应.value.reason, 头: 响应.value.headers, 体: 正文.value}`
## 构建请求字节
`params(方法, 路径, 头列表, 体字节)`
构建 HTTP/1.1 请求字节。方法、路径、头名/值按 UTF-8 编码;正文使用
传入的字节列表。
**结果 = 文本字节(方法 + " " + 路径 + " HTTP/1.1" + "\r\n")**
**下标 = 0**
`while 下标 < 长度(头列表)`
**头 = 头列表[下标]**
**结果 = list.concat(结果, 文本字节(文本(头[0]) + ": " + 文本(头[1]) + "\r\n"))**
**下标 = 下标 + 1**
`end`
**结果 = list.concat(结果, [13, 10])**
`return list.concat(结果, 体字节)`
## 构建请求
`params(方法, 路径, 头列表, 体文本)`
兼容文本 API,正文按 UTF-8 编码。
**请求 = 构建请求字节(方法, 路径, 头列表, 文本字节(体文本))**
**文本结果 = 字节文本(请求)**
`if not 文本结果.ok`
`return ""`
`end`
`return 文本结果.value`
+5
View File
@@ -0,0 +1,5 @@
project:
name: marqdo-ext-http
version: 0.1.0
marqdo: ">=3.0.0-beta.1,<4.0.0"
dependencies: {}
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Run an explicit-package extension repository's tests with real CLI inputs.
Each case builds a throwaway consumer project whose `dependencies.<alias>` path
points at a copy of this repository's package (`marqdo.yaml` + `index.mq.md`),
runs `marqdo lock` once, then executes the migrated `.mq.md` test through the
public `@alias` import. Inputs are explicit: `MARQDO_BIN` (verified CLI) and
`MARQDO_STDLIB_DIR` (installed Bundle for the remaining `std:` imports, if any).
Nothing reads a sibling repository or a floating branch.
"""
from __future__ import annotations
import base64
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
CASES = REPO / "tests" / "cases"
SCHEMA = "marqdo.package-test-case"
SCHEMA_VERSION = 1
class CaseError(Exception):
pass
def substitute(value, binary: str, package_root: Path):
if isinstance(value, dict):
if set(value) == {"$bin_version"}:
return subprocess.run([binary, "--version"], capture_output=True, text=True).stdout
if set(value) == {"$package_root"}:
return str(package_root)
return {k: substitute(v, binary, package_root) for k, v in value.items()}
if isinstance(value, list):
return [substitute(v, binary, package_root) for v in value]
return value
def channel_text(events, channel):
parts = []
for event in events:
if event.get("kind") != channel:
continue
payload = event["payload"]
data = base64.b64decode(payload["data_base64"])
if len(data) != payload["byte_count"]:
raise CaseError(f"{channel} byte_count mismatch")
parts.append(data)
return b"".join(parts).decode()
def consumer_manifest(alias: str) -> str:
return (
"project:\n"
" name: package-test-consumer\n"
" version: 0.0.0\n"
' marqdo: ">=3.0.0-beta.1,<4.0.0"\n'
"dependencies:\n"
f" {alias}:\n"
f" path: ./deps/{alias}\n"
)
def run_case(case: dict, binary: str, bundle: Path) -> None:
name = case["name"]
alias = case["dep_alias"]
env = os.environ.copy()
env["MARQDO_STDLIB_DIR"] = str(bundle)
for key, value in case.get("env", {}).items():
env[key] = str(value).replace("$MARQDO_BIN", binary)
source = REPO / "tests" / case["file"]
if not source.is_file():
raise CaseError(f"{name}: missing test source {source}")
with tempfile.TemporaryDirectory(prefix="mq-package-test-") as tmp:
consumer = Path(tmp) / "consumer"
package = consumer / "deps" / alias
package.mkdir(parents=True)
shutil.copy2(REPO / "marqdo.yaml", package / "marqdo.yaml")
shutil.copy2(REPO / "index.mq.md", package / "index.mq.md")
(consumer / "marqdo.yaml").write_text(consumer_manifest(alias))
(consumer / "tests").mkdir()
shutil.copy2(source, consumer / "tests" / case["file"])
lock = subprocess.run([binary, "lock"], cwd=consumer, env=env, capture_output=True)
if lock.returncode != 0:
raise CaseError(f"{name}: marqdo lock failed: {lock.stderr.decode(errors='replace')}")
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
result = subprocess.run(
[binary, "run", str(consumer / "tests" / case["file"]), *args, "--output", "json"],
cwd=consumer, env=env, input=case.get("stdin", "").encode(), capture_output=True,
)
if result.returncode != 0:
raise CaseError(f"{name}: CLI exited {result.returncode}:\n{result.stderr.decode(errors='replace')}")
report = json.loads(result.stdout)
if report.get("run", {}).get("status") != "ok":
raise CaseError(f"{name}: run status not ok")
terminal = report["events"][-1]["payload"]
if terminal.get("status") != "ok":
raise CaseError(f"{name}: terminal status not ok")
expected = substitute(case["expected_terminal"], binary, REPO)
if terminal.get("value") != expected:
raise CaseError(
f"{name}: terminal value changed\nexpected: "
f"{json.dumps(expected, ensure_ascii=False, sort_keys=True)}\nactual: "
f"{json.dumps(terminal.get('value'), ensure_ascii=False, sort_keys=True)}"
)
stdout = channel_text(report["events"], "stdout.chunk")
if stdout != case.get("expected_stdout", ""):
raise CaseError(f"{name}: stdout changed: {stdout!r}")
def main() -> int:
binary = os.environ.get("MARQDO_BIN")
bundle = os.environ.get("MARQDO_STDLIB_DIR")
if not binary or not shutil.which(binary):
print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr)
return 2
if not bundle or not Path(bundle).is_dir():
print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr)
return 2
bundle = Path(bundle).resolve()
paths = sorted(CASES.glob("*.json"))
if not paths:
print("no test cases", file=sys.stderr)
return 2
failures = 0
ran = 0
for path in paths:
case = json.loads(path.read_text())
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
print(f"FAIL {path.name}: unsupported schema", file=sys.stderr)
failures += 1
continue
ran += 1
try:
run_case(case, binary, bundle)
print(f"PASS {case['name']}")
except (CaseError, json.JSONDecodeError) as error:
print(f"FAIL {error}", file=sys.stderr)
failures += 1
if failures:
print(f"{failures} of {ran} cases failed", file=sys.stderr)
return 1
print(f"{ran} cases passed")
return 0
if __name__ == "__main__":
sys.exit(main())
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Explicit inputs only: a verified CLI binary and the installed Bundle that
# still provides the std: dependencies (if any). Never reads sibling checkouts.
set -eu
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
: "${MARQDO_STDLIB_DIR:?set MARQDO_STDLIB_DIR to the installed Bundle}"
exec python3 "$(dirname "$0")/run_cases.py" "$@"
+5 -1
View File
@@ -1,3 +1,7 @@
# 验收测试
首个功能附带正例和失败用例,记录所用 CLI 提交或发行版本以及实际运行命令。
`tests/*.mq.md` 是从迁移前 CLI 官方标准库自测迁入的真实测试源,导入已改为公开 Package 别名(`@alias`);`tests/cases/*.json` 固定输入(stdin、CLI 参数、环境、依赖别名)与期望结果(observation 终值、stdout)。
运行入口是 `scripts/test.sh`,要求显式传入 `MARQDO_BIN` 与 `MARQDO_STDLIB_DIR`。运行器为每个 case 建立临时消费者工程(`dependencies.<alias>.path` 指向本仓 Package 副本),先 `marqdo lock` 再通过公开 `@alias` 导入执行,不读取兄弟仓路径或浮动分支。
期望值取自迁移前基线 Bundle 的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。
+48
View File
@@ -0,0 +1,48 @@
{
"schema": "marqdo.package-test-case",
"schema_version": 1,
"name": "http",
"file": "http.mq.md",
"dep_alias": "http",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"decimal": "200",
"type": "int"
},
{
"type": "text",
"value": "OK"
},
{
"type": "text",
"value": "text/plain"
},
{
"type": "text",
"value": "hello world"
},
{
"type": "text",
"value": "POST /echo HTTP/1.1\r\nHost: example.test\r\nContent-Length: 2\r\n\r\nok"
},
{
"decimal": "200",
"type": "int"
},
{
"type": "text",
"value": "你好"
},
{
"type": "text",
"value": "POST / HTTP/1.1\r\n\r\nAB"
}
],
"type": "list"
}
}
+24
View File
@@ -0,0 +1,24 @@
---
import:
http: "@http"
---
# @exec http
## main
**响应文本 = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n"**
**响应 = http.解析响应(响应文本)**
**请求 = http.构建请求("POST", "/echo", [["Host", "example.test"], ["Content-Length", "2"]], "ok")**
**响应字节 = http.解析响应字节(http.文本字节("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\n你好\r\n0\r\n\r\n"))**
**正文 = http.字节文本(响应字节.value.body)**
**请求字节 = http.构建请求字节("POST", "/", [], [65, 66])**
**请求文本 = http.字节文本(请求字节)**
`return [响应.状态, 响应.原因, 响应.头["Content-Type"], 响应.体, 请求, 响应字节.value.status, 正文.value, 请求文本.value]`