"""HTTP 客户端资源责任对照;保留裸库参考,固定一次预热和七轮轮换。""" import argparse import json import os from pathlib import Path import statistics import tomllib from http_reference import server from scale import execute, fingerprint def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--plain", type=Path, required=True) parser.add_argument("--previous", type=Path, required=True) parser.add_argument("--previous-direct", type=Path, required=True) args = parser.parse_args() core = Path(__file__).resolve().parents[2] os.chdir(core) root = args.output.resolve() root.mkdir(parents=True, exist_ok=False) plain = args.plain.resolve(strict=True) previous = args.previous.resolve(strict=True) compiler = core / "target/next-cargo/release/dever" os.environ["CARGO_BUILD_JOBS"] = "1" os.environ["GOMAXPROCS"] = "1" report = dict(rounds=7, warmups=1, size=10000, cpu_affinity=[0], builds=[], samples=[], source_hashes={}) report["contract"] = { "shared": ["one fixed origin, one DNS resolution", "32 physical sockets including idle sockets", "32 in-flight requests held through body consumption", "10s idle expiry, no retry", "5s queue/connect/headers/complete-body deadline", "60s per streaming read, 65536-byte chunks", "8192-byte sent/received headers and 1MiB sent/collected body", "cancel and await protocol tasks on close", "retain protocol panics; release permits on EOF/error/drop"], "representation": "Rust keeps native Hyper Parts/Bytes and a shared single cursor with synchronous close; Dever returns public records/shared AsyncStream. No forced header copies in Rust.", "single": "One fresh TCP connection per call, no detached driver, 5s whole-operation deadline, same sent/received header/body budgets and status constraints. Native typed request/socket address; no forced text/header copies.", "scope": "Sequential successful HTTP/1. Pool/stream rules in shared; single-call rules in single. Reference tests separately verify cancellation, physical permits and panic/drain. Not full TLS/H2 or all language ownership equivalence.", } def save(): (root / "results.json").write_text(json.dumps(report, indent=2) + "\n") reference_sources = sorted(Path(__file__).parent.glob("http_resource_*.rs")) sources = [*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"), core / "rust/Cargo.lock", core / "rust/Cargo.toml", core / "rust/src/runtime/Cargo.toml", Path(__file__), *reference_sources] for path in sources: relative = path.relative_to(core) report["source_hashes"][str(relative)] = fingerprint(path) target = root / "inputs" / relative target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(path.read_bytes()) reference = root / "resource" reference.mkdir() for source in reference_sources: (reference / source.name).write_bytes(source.read_bytes()) manifest = (plain / "http_pool-rust/Cargo.toml").read_text() manifest = manifest.replace("collection-reference", "http-resource-reference").replace( 'path = "main.rs"', 'path = "http_resource_reference.rs"') manifest = manifest.replace('[dependencies]\n', '[dependencies]\ntokio-util = { version = "=0.7.19", features = ["rt"] }\nfutures-util = { version = "=0.3.34", default-features = false, features = ["std"] }\ntower-service = "=0.3.3"\n') (reference / "Cargo.toml").write_text(manifest) (reference / "Cargo.lock").write_bytes((core / "rust/Cargo.lock").read_bytes()) cargo = ["cargo", "+1.95.0"] common = ["--manifest-path", str(reference / "Cargo.toml"), "--offline", "--target-dir", str(reference / "target")] for label, command in [("reference-tests", [*cargo, "test", *common]), ("reference-clippy", [*cargo, "clippy", *common, "--all-targets", "--", "-D", "warnings"]), ("reference-build", [*cargo, "build", *common, "--release"])]: result = execute(command, root, label, 900) report["builds"].append(result) save() if result["exit_code"]: raise RuntimeError(result) locked = {(p["name"], p["version"], p.get("source")) for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]} actual = tomllib.loads((reference / "Cargo.lock").read_text())["package"] assert all(not p.get("source") or (p["name"], p["version"], p["source"]) in locked for p in actual) resource = reference / "target/release/http-resource-reference" programs = {} for shape in ["http", "http_pool", "http_stream"]: source = plain / (shape + "-dever/main.dever") binary = root / shape result = execute([str(compiler), "build", str(source), "--output", str(binary)], root, shape + "-build", 900) report["builds"].append(result) save() if result["exit_code"]: raise RuntimeError(result) prior = args.previous_direct.resolve(strict=True) if shape == "http" else previous / shape programs[shape] = dict(dever=binary, previous=prior, resource=resource, rust=plain / (shape + "-rust/target/release/collection-reference"), go=plain / (shape + "-go/program")) report["binaries"] = {s: {name: dict(path=str(path), sha256=fingerprint(path)) for name, path in cases.items()} for s, cases in programs.items()} report["compiler_sha256"] = fingerprint(compiler) os.sched_setaffinity(0, {0}) config = root / "setting.json" config.write_text(json.dumps({"module": {"main": {"main": {"port": server(root)}}}})) report["fixture_sha256"] = fingerprint(root / "http-server.cjs") names = ["dever", "previous", "resource", "rust", "go"] for repeat in range(-1, 7): assert all(fingerprint(core / path) == digest for path, digest in report["source_hashes"].items()) for shape, cases in programs.items(): for offset in range(len(names)): name = names[(repeat + 1 + offset) % len(names)] dever = name in ("dever", "previous") arguments = ["--config", str(config), "main.main.bench", json.dumps({"n": report["size"]})] if dever else [str(report["size"]), str(config)] if name == "resource": arguments.insert(0, shape) row = dict(shape=shape, name=name, repeat=repeat, **execute([str(cases[name]), *arguments], root, f"{shape}-{name}-{repeat}", 60)) output = Path(row["stdout"]).read_text() row["correct"] = row["exit_code"] == 0 and (json.loads(output)["data"] if dever else int(output)) == report["size"] report["samples"].append(row) save() assert row["correct"], row print("round", repeat, "complete", flush=True) report["medians"] = {shape: {name: { "seconds": statistics.median(r["seconds"] for r in report["samples"] if r["shape"] == shape and r["name"] == name and r["repeat"] >= 0), "cpu": statistics.median(r["user_cpu_seconds"] + r["system_cpu_seconds"] for r in report["samples"] if r["shape"] == shape and r["name"] == name and r["repeat"] >= 0), } for name in names} for shape in programs} save() print(json.dumps(report["medians"], indent=2)) if __name__ == "__main__": main()