"""授权的真实 SQLite 成本;固定资源、预热与七轮交错,不链接 Dever 的 Rust 对端。""" import argparse import json import os from pathlib import Path import shutil import statistics import tomllib from scale import execute, fingerprint def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--current", type=Path, required=True, help="current release runtime test binary") parser.add_argument("--previous", type=Path, required=True, help="unchanged prior release runtime test binary") parser.add_argument("--rust-reference", type=Path, help="reuse an unchanged locked independent peer") parser.add_argument("--output", type=Path, required=True) parser.add_argument("--tenant", action="store_true", help="measure physical tenant and capability authorization") args = parser.parse_args() core = Path(__file__).resolve().parents[2] root = args.output.absolute() root.mkdir(parents=True, exist_ok=False) reference = root / "reference" reference.mkdir() fixture = Path(__file__).parent / "fixtures/auth/peer.rs.txt" shutil.copyfile(fixture, reference / "main.rs") resource = (core / "test/performance/fixtures/sqlite_resource.rs.txt").read_text() # 和 runtime 测量使用同一限额;不改变原 Model/Job 对端的默认配置。 assert resource.count("let timeout = Duration::from_secs(30);") == 1 assert resource.count("Duration::from_secs(5)") == 1 resource = resource.replace("let timeout = Duration::from_secs(30);", "let timeout = Duration::from_secs(2);") resource = resource.replace("Duration::from_secs(5)", "Duration::from_millis(100)") (reference / "sqlite_resource.rs").write_text(resource) shutil.copyfile(core / "rust/Cargo.lock", reference / "Cargo.lock") (reference / "Cargo.toml").write_text('''[package] name = "auth-reference" version = "0.0.1" edition = "2024" [[bin]] name = "auth-reference" path = "main.rs" [dependencies] deadpool-sqlite = { version = "=0.14.0", features = ["bundled", "hooks", "functions"] } tokio = { version = "=1.53.1", features = ["rt", "time", "macros", "sync"] } tokio-util = { version = "=0.7.19", features = ["rt"] } percent-encoding = "=2.3.2" [profile.release] lto = "fat" codegen-units = 1 overflow-checks = true strip = true ''') report = dict(rounds=7, warmups=1, cpu_affinity=[0], builds=[], samples=[], contract="Global authorization, same or separate catalog, allowed owner and denied visitor. Real SQLite/WAL, one connection per physical pool, per-operation 2s deadline, 100ms pool wait, bounded 8 blocking workers, cancellation and fault drain. Four cases, each process retains one warmup and seven 256-call samples. Setup is outside internal timing. Native Rust uses EXISTS and scalar results; no forced string/set allocation.", limitations="Runtime boundary probe; not a Dever application or full four-way auth/tenant matrix. Authentication/signature, physical tenant selection, capabilities and PostgreSQL are covered separately by functional tests, not this timer. Independent resource module lacks nominal FaultInfo; success timing does not establish that complete error contract.") cases = ("tenant_true", "tenant_false", "capability_true", "capability_false") if args.tenant else ( "same_true", "same_false", "separate_true", "separate_false") if args.tenant: report["contract"] = "Physical tenant authorization with a separate control catalog: ordinary permission and registered capability, allowed owner and denied visitor. Component enablement and live roles are queried on every call. Real SQLite/WAL, one connection per physical pool, 2s operation deadline, 100ms pool wait, eight blocking workers and cancellation/fault drain. Four cases, each process retains one warmup and seven 256-call samples; setup and physical tenant selection are outside internal timing." report["limitations"] = "Runtime boundary probe; not a Dever application or full four-way auth/tenant matrix. Signatures, physical selection and PostgreSQL are not timed. Independent Rust does not link Dever; its shared resource module lacks nominal FaultInfo, so success timing does not establish complete error equivalence." def save(): (root / "results.json").write_text(json.dumps(report, indent=2) + "\n") common = ["--offline", "--manifest-path", str(reference / "Cargo.toml"), "--target-dir", str(reference / "target")] commands = [ ("reference-clippy", ["cargo", "+1.95.0", "clippy", *common, "--", "-D", "warnings"]), ("reference-build", ["cargo", "+1.95.0", "build", *common, "--release"]), ] if args.rust_reference: peer = args.rust_reference.resolve(strict=True).parents[2] for name in ("main.rs", "sqlite_resource.rs", "Cargo.toml"): assert fingerprint(reference / name) == fingerprint(peer / name), name shutil.copyfile(peer / "Cargo.lock", reference / "Cargo.lock") commands = [] for label, command in commands: row = execute(command, root, label, 900) report["builds"].append(row) save() assert row["exit_code"] == 0, row 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) programs = dict(current=args.current.resolve(strict=True), previous=args.previous.resolve(strict=True), rust=args.rust_reference.resolve(strict=True) if args.rust_reference else reference / "target/release/auth-reference") report["binaries"] = {n: dict(path=str(p), sha256=fingerprint(p)) for n, p in programs.items()} sources = [Path(__file__), fixture, core / "test/rust/runtime/auth/access.rs", core / "test/rust/runtime/auth/capability.rs", core / "rust/Cargo.lock", *core.joinpath("rust/src/runtime").rglob("*.rs"), *reference.glob("*.rs"), reference / "Cargo.toml", reference / "Cargo.lock"] report["sources"] = {str(p): fingerprint(p) for p in sources} os.sched_setaffinity(0, {0}) names = list(programs) for repeat in range(-1, 7): assert all(fingerprint(Path(p)) == digest for p, digest in report["sources"].items()) order = names[repeat % len(names):] + names[:repeat % len(names)] if repeat % 2: order.reverse() for name in order: assert fingerprint(programs[name]) == report["binaries"][name]["sha256"] arguments = [str(root / f"fixture-{repeat}-{name}"), *(["--tenant"] if args.tenant else [])] if name == "rust" else [ "auth::capability::tenant_authorization_cost" if args.tenant else "auth::access::authorization_cost", "--exact", "--ignored", "--nocapture"] row = dict(name=name, repeat=repeat, **execute( [str(programs[name]), *arguments], root, f"{repeat}-{name}", 120)) report["samples"].append(row) save() assert row["exit_code"] == 0 and not row["timeout"], row values = [] for line in Path(row["stdout"]).read_text().splitlines(): if not line.startswith(tuple(case + "," for case in cases)): continue case, sample, count, nanos, allowed = line.split(",") value = dict(case=case, sample=int(sample), iterations=int(count), nanoseconds=int(nanos), allowed=int(allowed)) assert value["allowed"] == (256 if case.endswith("true") else 0), value assert value["iterations"] == 256 and value["nanoseconds"] > 0, value values.append(value) assert {(v["case"], v["sample"]) for v in values} == { (case, sample) for case in cases for sample in range(-1, 7)} and len(values) == 32, values row["values"] = values row["checked"] = True save() print("round", repeat, "complete", flush=True) report["medians_ns"] = {case: {name: statistics.median( v["nanoseconds"] for r in report["samples"] if r["repeat"] >= 0 and r["name"] == name for v in r["values"] if v["case"] == case and v["sample"] >= 0) for name in names} for case in cases} save() print(json.dumps(report["medians_ns"], indent=2)) if __name__ == "__main__": main()