Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,55 @@
|
||||
"""三方接收同一 argv,重复读取独立参数列表并累计全部字符。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''loop characters(values: List<Text>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum length(value) |
|
||||
flow read() (out: Int)
|
||||
| step | kind | do |
|
||||
| values | flow | dever.process.arguments() |
|
||||
| out | loop | characters(values) |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum read() |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language in ('rust', 'runtime'):
|
||||
arguments = ('dever_runtime::io::arguments().unwrap()' if language == 'runtime' else
|
||||
'std::env::args_os().skip(1).map(|value| value.into_string()).collect::<Result<Vec<_>, _>>().unwrap()')
|
||||
return '''fn read() -> i64 {
|
||||
let values = ARGUMENTS;
|
||||
let mut count = 0i64;
|
||||
for value in &values { count = count.checked_add(i64::try_from(value.chars().count()).unwrap()).unwrap(); }
|
||||
count
|
||||
}
|
||||
fn main() {
|
||||
let input: serde_json::Value = serde_json::from_str(&std::env::args().nth(2).unwrap()).unwrap();
|
||||
let n = input["n"].as_i64().unwrap();
|
||||
let mut count = 0i64;
|
||||
for _ in 0..n {
|
||||
count = count.checked_add(read()).unwrap();
|
||||
}
|
||||
println!("{count}");
|
||||
}
|
||||
'''.replace('ARGUMENTS', arguments)
|
||||
return '''package main
|
||||
import ("encoding/json"; "fmt"; "os"; "unicode/utf8")
|
||||
func main() {
|
||||
var input struct { N int64 }
|
||||
if err := json.Unmarshal([]byte(os.Args[2]), &input); err != nil { panic(err) }
|
||||
count := int64(0)
|
||||
for i := int64(0); i < input.N; i++ {
|
||||
values := append([]string(nil), os.Args[1:]...)
|
||||
subtotal := int64(0)
|
||||
for _, value := range values {
|
||||
if !utf8.ValidString(value) { panic("process argument is not UTF-8") }
|
||||
size := int64(utf8.RuneCountInString(value))
|
||||
next := subtotal + size; if next < subtotal { panic("count overflow") }; subtotal = next
|
||||
}
|
||||
next := count + subtotal; if next < count { panic("count overflow") }; count = next
|
||||
}
|
||||
fmt.Println(count)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,54 @@
|
||||
"""顺序调用直接 future,百万次调用中实际挂起一次;对端不共享 Dever 运行库。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''noop() () {}
|
||||
rule pause(value: Int) ()
|
||||
| value | do |
|
||||
| 0 | dever.time.sleep(1) |
|
||||
| other | noop() |
|
||||
flow item(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | rule | pause(value % 1000000) |
|
||||
| out | calc | value |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum item(value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''async fn pause(value: i64) -> Result<(), &'static str> {
|
||||
if value == 0 {
|
||||
let millis = u64::try_from(1i64).map_err(|_| "sleep duration must be nonnegative")?;
|
||||
let deadline = tokio::time::Instant::now().checked_add(std::time::Duration::from_millis(millis)).ok_or("sleep deadline is out of range")?;
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn item(value: i64) -> Result<i64, &'static str> { pause(value % 1000000).await?; Ok(value) }
|
||||
async fn measure(n: i64) -> Result<i64, &'static str> {
|
||||
let mut total = 0i64;
|
||||
for value in 0..n { total = total.checked_add(item(value).await?).expect("sum overflow"); }
|
||||
Ok(total)
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
|
||||
println!("{}", runtime.block_on(measure(n)).unwrap());
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv"; "time")
|
||||
func pause(value int64) { if value == 0 { time.Sleep(time.Millisecond) } }
|
||||
func item(value int64) int64 { pause(value % 1000000); return value }
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
next := total + item(value)
|
||||
if next < total { panic("sum overflow") }; total = next
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,138 @@
|
||||
"""授权的真实 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()
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Bytes 的真实转换、共享切片与完整内容校验;Rust 对端不依赖 Dever runtime。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''loop values(n: Int) (out: List<Int>)
|
||||
| each value in range(0, n) | result |
|
||||
| out | list value % 256 |
|
||||
loop total(data: Bytes) (out: Int)
|
||||
| each byte in data | result |
|
||||
| out | sum byte |
|
||||
measure(n: Int) (out: Int) {
|
||||
data = dever.bytes.fromInts(values(n))
|
||||
out = total(dever.bytes.slice(data, 1, n))
|
||||
}
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::Bytes;
|
||||
fn from_ints(values: &[i64]) -> Result<Bytes, &'static str> {
|
||||
let mut bytes = Vec::with_capacity(values.len());
|
||||
for value in values { bytes.push(u8::try_from(*value).map_err(|_| "invalid byte")?); }
|
||||
Ok(bytes.into())
|
||||
}
|
||||
fn slice(bytes: &Bytes, start: i64, end: i64) -> Result<Bytes, &'static str> {
|
||||
let start = usize::try_from(start).map_err(|_| "invalid range")?;
|
||||
let end = usize::try_from(end).map_err(|_| "invalid range")?;
|
||||
bytes.get(start..end).map(|range| bytes.slice_ref(range)).ok_or("invalid range")
|
||||
}
|
||||
fn values(n: i64) -> Vec<i64> {
|
||||
let mut values = Vec::with_capacity(n as usize);
|
||||
for value in 0..n { values.push(value.checked_rem(256).expect("remainder")); }
|
||||
values
|
||||
}
|
||||
fn total(bytes: &[u8]) -> i64 {
|
||||
let mut total = 0i64;
|
||||
for byte in bytes { total = total.checked_add(i64::from(*byte)).expect("sum overflow"); }
|
||||
total
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let data = from_ints(&values(n)).unwrap();
|
||||
println!("{}", total(&slice(&data, 1, n).unwrap()));
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func values(n int64) []int64 {
|
||||
values := make([]int64, 0, n)
|
||||
for value := int64(0); value < n; value++ { values = append(values, value % 256) }
|
||||
return values
|
||||
}
|
||||
func fromInts(values []int64) []byte {
|
||||
bytes := make([]byte, 0, len(values))
|
||||
for _, value := range values {
|
||||
if value < 0 || value > 255 { panic("invalid byte") }
|
||||
bytes = append(bytes, byte(value))
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
func slice(bytes []byte, start, end int64) []byte {
|
||||
if start < 0 || end < start || end > int64(len(bytes)) { panic("invalid range") }
|
||||
return bytes[start:end]
|
||||
}
|
||||
func total(bytes []byte) int64 {
|
||||
total := int64(0)
|
||||
for _, value := range bytes {
|
||||
sum := total + int64(value)
|
||||
if sum < total { panic("sum overflow") }
|
||||
total = sum
|
||||
}
|
||||
return total
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
data := fromInts(values(n))
|
||||
fmt.Println(total(slice(data, 1, n)))
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,110 @@
|
||||
"""UTC 毫秒日期时间往返;独立 Chrono/Go time 实现,不共享 Dever runtime。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''roundtrip(start: DateTime, offset: Int) (out: Int) {
|
||||
span = dever.time.duration(offset)
|
||||
changed = dever.time.add(start, span)
|
||||
text = dever.time.formatDatetime(changed)
|
||||
restored = dever.time.parseDatetime(text)
|
||||
check dever.time.difference(restored, start) == span else Invalid
|
||||
out = 1
|
||||
}
|
||||
loop count(start: DateTime, n: Int) (out: Int)
|
||||
| each offset in range(0, n) | result |
|
||||
| out | sum roundtrip(start, offset) |
|
||||
measure(n: Int) (out: Int) {
|
||||
out = count(dever.time.parseDatetime("2024-02-29T12:34:56.12+08:00"), n)
|
||||
}
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use chrono::{DateTime, Utc, Datelike, Timelike};
|
||||
use std::fmt::Write;
|
||||
fn calendar(value: i64) -> DateTime<Utc> {
|
||||
DateTime::from_timestamp_millis(value).filter(|date| (0..=9999).contains(&date.year())).expect("calendar range")
|
||||
}
|
||||
fn parse(text: &str) -> i64 {
|
||||
if let Some(fraction) = text.get(19..).and_then(|tail| tail.strip_prefix('.')) {
|
||||
assert!(fraction.bytes().take_while(u8::is_ascii_digit).count() <= 3);
|
||||
}
|
||||
let value = DateTime::parse_from_rfc3339(text).unwrap();
|
||||
assert!(value.nanosecond() < 1_000_000_000 && value.nanosecond() % 1_000_000 == 0);
|
||||
let millis = value.timestamp_millis();
|
||||
calendar(millis);
|
||||
millis
|
||||
}
|
||||
fn format(millis: i64) -> String {
|
||||
let value = calendar(millis);
|
||||
let spec = if value.timestamp_subsec_millis() == 0 { "%Y-%m-%dT%H:%M:%SZ" } else { "%Y-%m-%dT%H:%M:%S%.3fZ" };
|
||||
let mut text = String::with_capacity(24);
|
||||
write!(text, "{}", value.naive_utc().format(spec)).unwrap();
|
||||
text
|
||||
}
|
||||
fn roundtrip(start: i64, offset: i64) -> i64 {
|
||||
let changed = start.checked_add(offset).unwrap();
|
||||
let restored = parse(&format(changed));
|
||||
assert_eq!(restored.checked_sub(start).unwrap(), offset);
|
||||
1
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let start = parse("2024-02-29T12:34:56.12+08:00");
|
||||
let mut total = 0i64;
|
||||
for offset in 0..n { total = total.checked_add(roundtrip(start, offset)).unwrap(); }
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv"; "strings"; "time")
|
||||
func calendar(value int64) time.Time {
|
||||
date := time.UnixMilli(value).UTC()
|
||||
if date.Year() < 0 || date.Year() > 9999 { panic("calendar range") }
|
||||
return date
|
||||
}
|
||||
func parse(text string) int64 {
|
||||
if len(text) > 19 && strings.HasPrefix(text[19:], ".") {
|
||||
count := 0
|
||||
for _, digit := range text[20:] {
|
||||
if digit < '0' || digit > '9' { break }; count++
|
||||
}
|
||||
if count > 3 { panic("millisecond precision") }
|
||||
}
|
||||
value, err := time.Parse(time.RFC3339Nano, text)
|
||||
if err != nil { panic(err) }
|
||||
if value.Nanosecond() % 1000000 != 0 { panic("millisecond precision") }
|
||||
millis := value.UnixMilli()
|
||||
calendar(millis)
|
||||
return millis
|
||||
}
|
||||
func format(millis int64) string {
|
||||
value := calendar(millis)
|
||||
if value.Nanosecond() == 0 { return value.Format("2006-01-02T15:04:05Z") }
|
||||
return value.Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
func add(left, right int64) int64 {
|
||||
sum := left + right
|
||||
if (right > 0 && sum < left) || (right < 0 && sum > left) { panic("overflow") }
|
||||
return sum
|
||||
}
|
||||
func subtract(left, right int64) int64 {
|
||||
difference := left - right
|
||||
if (right > 0 && difference > left) || (right < 0 && difference < left) { panic("overflow") }
|
||||
return difference
|
||||
}
|
||||
func roundtrip(start, offset int64) int64 {
|
||||
changed := add(start, offset)
|
||||
restored := parse(format(changed))
|
||||
if subtract(restored, start) != offset { panic("wrong result") }
|
||||
return 1
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
start := parse("2024-02-29T12:34:56.12+08:00")
|
||||
total := int64(0)
|
||||
for offset := int64(0); offset < n; offset++ { total = add(total, roundtrip(start, offset)) }
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,82 @@
|
||||
"""有界通道真实生产/消费;独立 Rust 直接用 async-channel,不引用 Dever 运行库。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''flow sendOne(channel: Channel<Int>, value: Int) ()
|
||||
| step | kind | do |
|
||||
| - | calc | send(channel, value) |
|
||||
loop produce(channel: Channel<Int>, n: Int) ()
|
||||
| each value in range(0, n) | result |
|
||||
| - | do sendOne(channel, value) |
|
||||
flow producer(channel: Channel<Int>, n: Int) ()
|
||||
| step | kind | do |
|
||||
| - | loop | produce(channel, n) |
|
||||
| - | calc | close(channel) |
|
||||
flow readOne(channel: Channel<Int>) (out: Int)
|
||||
| step | kind | do |
|
||||
| value | calc | receive(channel) |
|
||||
| - | check | value != null else Invalid |
|
||||
| out | calc | value |
|
||||
loop consume(channel: Channel<Int>, n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum readOne(channel) |
|
||||
flow total(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Int>(64) |
|
||||
| task | calc | run(producer(channel, n)) |
|
||||
| out | loop | consume(channel, n) |
|
||||
| - | calc | wait(task) |
|
||||
cmd total = total
|
||||
'''
|
||||
if language == 'runtime':
|
||||
return '''fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let sum = dever_runtime::task::run(true, 4096, async |scope| {
|
||||
let channel = dever_runtime::channel::Channel::new(64).unwrap();
|
||||
let output = channel.clone();
|
||||
let producer = scope.spawn_leaf(async move {
|
||||
for value in 0..n { output.send(value).await.unwrap(); }
|
||||
output.close();
|
||||
}).unwrap();
|
||||
let mut sum = 0i64;
|
||||
for _ in 0..n {
|
||||
let value = channel.receive().await.map_err(|_| "unexpected close")?;
|
||||
sum = sum.checked_add(value).unwrap();
|
||||
}
|
||||
producer.wait().await.unwrap();
|
||||
Ok::<_, &str>(sum)
|
||||
}).unwrap().unwrap();
|
||||
println!("{sum}");
|
||||
}
|
||||
'''
|
||||
return '''use std::sync::Arc;
|
||||
use tokio_util::task::{TaskTracker, AbortOnDropHandle};
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
|
||||
let sum = runtime.block_on(async {
|
||||
let (sender, receiver) = async_channel::bounded(64);
|
||||
let capacity = Arc::new(tokio::sync::Semaphore::new(4096));
|
||||
let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let tracker = TaskTracker::new();
|
||||
let tracking = tracker.token();
|
||||
let producer = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
for value in 0..n { sender.send(value).await.unwrap(); }
|
||||
sender.close();
|
||||
drop(permit);
|
||||
tracking
|
||||
}));
|
||||
let mut sum = 0i64;
|
||||
for _ in 0..n {
|
||||
let value = receiver.recv().await.map_err(|_| "unexpected close")?;
|
||||
sum = sum.checked_add(value).unwrap();
|
||||
}
|
||||
drop(producer.await.unwrap());
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
Ok::<_, &str>(sum)
|
||||
}).unwrap();
|
||||
println!("{sum}");
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,93 @@
|
||||
"""有界并发结果按输入顺序交付;独立参考不依赖 Dever 运行库。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''noop() () {}
|
||||
rule pause(value: Int) ()
|
||||
| value | do |
|
||||
| 0 | dever.time.sleep(1) |
|
||||
| other | noop() |
|
||||
flow item(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | rule | pause(value % 4096) |
|
||||
| out | calc | value |
|
||||
loop jobs(n: Int) (out: List<Int>)
|
||||
| each value in range(0, n) parallel 64 | result |
|
||||
| out | list item(value) |
|
||||
checked(value: Int, index: Int) (out: Int) {
|
||||
check value == index else Invalid
|
||||
out = index + 1
|
||||
}
|
||||
loop verify(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | fold(index = 0, checked(value, index)) |
|
||||
flow measure(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| values | loop | jobs(n) |
|
||||
| out | loop | verify(values) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'runtime':
|
||||
text = source('rust')
|
||||
return text.replace('let values: Vec<i64> = stream::iter(0..n).map(item).buffered(64).try_collect().await?;', """let mut values = Vec::with_capacity(n as usize);
|
||||
let mut input = 0..n;
|
||||
dever_runtime::ordered_loop!(&'static str, 64,
|
||||
async || Ok::<_, &'static str>(input.next()),
|
||||
async |value: i64| item(value).await,
|
||||
|value| values.push(value)).await?;""")
|
||||
if language == 'rust':
|
||||
return '''use futures_util::{stream, StreamExt, TryStreamExt};
|
||||
async fn item(value: i64) -> Result<i64, &'static str> {
|
||||
if value % 4096 == 0 {
|
||||
let deadline = tokio::time::Instant::now().checked_add(std::time::Duration::from_millis(1)).ok_or("deadline overflow")?;
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
async fn measure(n: i64) -> Result<i64, &'static str> {
|
||||
let values: Vec<i64> = stream::iter(0..n).map(item).buffered(64).try_collect().await?;
|
||||
let mut index = 0i64;
|
||||
for value in values {
|
||||
if value != index { return Err("out of order"); }
|
||||
index = index.checked_add(1).expect("count overflow");
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
|
||||
println!("{}", runtime.block_on(measure(n)).unwrap());
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv"; "time"; "sync")
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
jobs, results := make(chan int64), make(chan int64, 64)
|
||||
var workers sync.WaitGroup
|
||||
for i := 0; i < 64; i++ {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); for value := range jobs {
|
||||
if value % 4096 == 0 { time.Sleep(time.Millisecond) }; results <- value
|
||||
} }()
|
||||
}
|
||||
values := make([]int64, 0, n)
|
||||
var ready [64]bool
|
||||
var slots [64]int64
|
||||
sent, head := int64(0), int64(0)
|
||||
for head < n {
|
||||
var submit chan int64
|
||||
if sent < n && sent-head < 64 { submit = jobs }
|
||||
select {
|
||||
case submit <- sent: sent++
|
||||
case value := <-results:
|
||||
ready[value % 64] = true; slots[value % 64] = value
|
||||
for ready[head % 64] { ready[head % 64] = false; values = append(values, slots[head % 64]); head++ }
|
||||
}
|
||||
}
|
||||
close(jobs); workers.Wait()
|
||||
for index, value := range values { if value != int64(index) { panic("out of order") } }
|
||||
fmt.Println(len(values))
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,99 @@
|
||||
"""同一配置密钥和动态消息的 HMAC-SHA256 → SHA256 → 全摘要校验和;独立成熟库对端。"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
|
||||
def config():
|
||||
return {'module': {'main': {'main': {'key': 'public-benchmark-key'}}}}
|
||||
|
||||
|
||||
def expected(n):
|
||||
key = config()['module']['main']['main']['key'].encode()
|
||||
values = [sum(hashlib.sha256(hmac.digest(key, str(index).encode(), 'sha256')).digest()) for index in range(1000)]
|
||||
return sum(values) * (n // 1000) + sum(values[:n % 1000])
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting key: Secret
|
||||
loop checksum(value: Bytes) (out: Int)
|
||||
| each byte in value | result |
|
||||
| out | sum byte |
|
||||
roundtrip(value: Int) (out: Int) {
|
||||
message = dever.bytes.fromText(int.toText(value % 1000))
|
||||
signed = dever.crypto.hmacSha256(key, message)
|
||||
out = checksum(dever.crypto.sha256(signed))
|
||||
}
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum roundtrip(value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use hmac::{Hmac, Mac};
|
||||
use bytes::Bytes;
|
||||
use zeroize::Zeroizing;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Root { module: Module }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Module { main: Domain }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Domain { main: Settings }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings { key: String }
|
||||
fn sign(key: &[u8], message: &[u8]) -> Bytes {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(key).unwrap();
|
||||
mac.update(message);
|
||||
Bytes::copy_from_slice(&mac.finalize().into_bytes())
|
||||
}
|
||||
fn hash(message: &[u8]) -> Bytes { Bytes::copy_from_slice(&Sha256::digest(message)) }
|
||||
fn main() {
|
||||
let path = std::env::args().nth(2).unwrap();
|
||||
let input = Zeroizing::new(std::fs::read_to_string(path).unwrap());
|
||||
let root: Root = serde_json::from_str(&input).unwrap();
|
||||
let key = Zeroizing::new(root.module.main.main.key.into_bytes());
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut total = 0i64;
|
||||
for value in 0..n {
|
||||
let message = Bytes::from((value % 1000).to_string());
|
||||
let signed = sign(&key, &message);
|
||||
let digest = hash(&signed);
|
||||
let mut checksum = 0i64;
|
||||
for byte in digest { checksum = checksum.checked_add(i64::from(byte)).unwrap(); }
|
||||
total = total.checked_add(checksum).unwrap();
|
||||
}
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("crypto/hmac"; "crypto/sha256"; "encoding/json"; "fmt"; "os"; "strconv"; "strings")
|
||||
type Settings struct { Key string }
|
||||
type Domain struct { Main Settings }
|
||||
type Module struct { Main Domain }
|
||||
type Root struct { Module Module }
|
||||
func main() {
|
||||
input, err := os.ReadFile(os.Args[2]); if err != nil { panic(err) }
|
||||
var root Root
|
||||
decoder := json.NewDecoder(strings.NewReader(string(input))); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&root); err != nil { panic(err) }
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
key := []byte(root.Module.Main.Main.Key)
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
message := []byte(strconv.FormatInt(value % 1000, 10))
|
||||
mac := hmac.New(sha256.New, key); mac.Write(message)
|
||||
digest := sha256.Sum256(mac.Sum(nil))
|
||||
checksum := int64(0)
|
||||
for _, value := range digest { checksum += int64(value) }
|
||||
next := total + checksum; if next < total { panic("integer overflow") }; total = next
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,124 @@
|
||||
// 真实插件缓存、编译器查询和图索引计时;仅替换不可在 CLI 中加载的 VS Code 宿主。
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const Module = require('node:module');
|
||||
const { createHash } = require('node:crypto');
|
||||
const { performance } = require('node:perf_hooks');
|
||||
|
||||
class EventEmitter {
|
||||
callbacks = new Set();
|
||||
event = callback => { this.callbacks.add(callback); return { dispose: () => this.callbacks.delete(callback) }; };
|
||||
fire(value) { for (const callback of this.callbacks) callback(value); }
|
||||
dispose() { this.callbacks.clear(); }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const [compiler, project, source, changed, destination, symbol] = process.argv.slice(2).map((value, index) => index === 5 ? value : path.resolve(value));
|
||||
assert.ok(symbol, 'compiler project source changed-source output-directory symbol');
|
||||
await fs.mkdir(destination);
|
||||
const original = await fs.readFile(source);
|
||||
const replacement = await fs.readFile(changed);
|
||||
assert.notDeepEqual(original, replacement);
|
||||
const saved = new EventEmitter();
|
||||
const disposable = () => ({ dispose() {} });
|
||||
const quiet = () => ({ appendLine() {}, show() {}, hide() {}, dispose() {} });
|
||||
const vscode = {
|
||||
EventEmitter, Uri: { file: fsPath => ({ fsPath }) },
|
||||
Range: class { constructor(start, end) { Object.assign(this, { start, end }); } },
|
||||
DiagnosticSeverity: { Error: 0 },
|
||||
Diagnostic: class { constructor(range, message) { Object.assign(this, { range, message }); } },
|
||||
Location: class { constructor(uri, range) { Object.assign(this, { uri, range }); } },
|
||||
DiagnosticRelatedInformation: class { constructor(location, message) { Object.assign(this, { location, message }); } },
|
||||
workspace: {
|
||||
isTrusted: true, textDocuments: [],
|
||||
getConfiguration: () => ({ get: () => [compiler] }),
|
||||
onDidChangeTextDocument: () => disposable(), onDidCloseTextDocument: () => disposable(),
|
||||
onDidChangeConfiguration: () => disposable(), onDidSaveTextDocument: saved.event,
|
||||
createFileSystemWatcher: () => ({ dispose() {}, onDidChange: disposable, onDidCreate: disposable, onDidDelete: disposable }),
|
||||
},
|
||||
window: { createOutputChannel: quiet, createStatusBarItem: quiet },
|
||||
languages: { createDiagnosticCollection: () => ({ set() {}, clear() {}, dispose() {} }) },
|
||||
};
|
||||
const requireOriginal = Module._load;
|
||||
Module._load = function(name, ...args) { return name === 'vscode' ? vscode : requireOriginal.call(this, name, ...args); };
|
||||
const { createInspection } = require('../../editor/vscode/inspection.cjs');
|
||||
Module._load = requireOriginal;
|
||||
const { graph } = require('../../editor/vscode/graph.cjs');
|
||||
const { workflow } = require('../../editor/vscode/workflow.cjs');
|
||||
const context = { subscriptions: [] };
|
||||
const inspection = createInspection(context);
|
||||
const sha = data => createHash('sha256').update(data).digest('hex');
|
||||
const report = { rounds: 7, warmups: 1, compiler, compiler_sha256: sha(await fs.readFile(compiler)),
|
||||
project, source, symbol, node: process.version, source_sha256: sha(original), changed_sha256: sha(replacement),
|
||||
scope: 'Actual inspection.cjs cache and saved-source invalidation; real compiler subprocess. Cold/changed include compiler, transport and JSON parse. Serialization, adjacency and Mermaid text generation are measured separately; no browser layout or VS Code host timing claim.',
|
||||
samples: [] };
|
||||
report.plugin_sources = {};
|
||||
for (const name of ['inspection.cjs', 'graph.cjs', 'workflow.cjs']) {
|
||||
const data = await fs.readFile(path.resolve(__dirname, '../../editor/vscode', name));
|
||||
report.plugin_sources[name] = sha(data);
|
||||
await fs.writeFile(path.join(destination, name), data);
|
||||
}
|
||||
await fs.copyFile(__filename, path.join(destination, 'editor.cjs'));
|
||||
await fs.writeFile(path.join(destination, 'original-source.txt'), original);
|
||||
await fs.writeFile(path.join(destination, 'changed-source.txt'), replacement);
|
||||
const save = () => fs.writeFile(path.join(destination, 'results.json'), JSON.stringify(report, null, 2) + '\n');
|
||||
async function measure(phase, repeat, call) {
|
||||
const started = performance.now();
|
||||
const value = await call();
|
||||
report.samples.push({ phase, repeat, milliseconds: performance.now() - started, memory: process.memoryUsage() });
|
||||
return value;
|
||||
}
|
||||
function check(index, expected) {
|
||||
assert.deepEqual(index.diagnostics, []);
|
||||
assert.ok(index.symbols.some(item => item.name === symbol), symbol);
|
||||
assert.equal(index.files.find(file => file.path === source).sha256, sha(expected));
|
||||
}
|
||||
try {
|
||||
for (let repeat = -1; repeat < 7; repeat++) {
|
||||
await fs.writeFile(source, original);
|
||||
saved.fire({ languageId: 'dever', uri: { fsPath: source } });
|
||||
const index = await measure('cold-query', repeat, () => inspection.load(project));
|
||||
check(index, original);
|
||||
const cached = await measure('cached-query', repeat, () => inspection.load(project));
|
||||
assert.equal(cached, index);
|
||||
const adjacency = await measure('adjacency', repeat, () => graph(index));
|
||||
assert.equal(adjacency.symbols.size, index.symbols.length);
|
||||
assert.equal(await measure('cached-adjacency', repeat, () => graph(index)), adjacency);
|
||||
const encoded = await measure('serialize-index', repeat, () => JSON.stringify(index));
|
||||
const decoded = await measure('parse-index', repeat, () => JSON.parse(encoded));
|
||||
assert.deepEqual(decoded, index);
|
||||
const flow = await measure('selected-flow', repeat, () => inspection.load(project, symbol));
|
||||
check(flow, original);
|
||||
assert.ok(flow.flows.length > 0);
|
||||
const markdown = await measure('workflow-text', repeat, () => workflow(flow, project));
|
||||
assert.ok(markdown.includes('flowchart TD'));
|
||||
await fs.writeFile(source, replacement);
|
||||
saved.fire({ languageId: 'dever', uri: { fsPath: source } });
|
||||
const updated = await measure('changed-query', repeat, () => inspection.load(project));
|
||||
check(updated, replacement);
|
||||
assert.notEqual(updated, index);
|
||||
assert.notEqual(graph(updated), adjacency);
|
||||
report.samples.at(-1).index_bytes = Buffer.byteLength(encoded);
|
||||
report.samples.at(-1).symbols = index.symbols.length;
|
||||
await save();
|
||||
}
|
||||
report.correct = true;
|
||||
report.medians_ms = {};
|
||||
for (const phase of new Set(report.samples.map(row => row.phase))) {
|
||||
const values = report.samples.filter(row => row.phase === phase && row.repeat >= 0).map(row => row.milliseconds).sort((a, b) => a - b);
|
||||
report.medians_ms[phase] = values[3];
|
||||
}
|
||||
await save();
|
||||
console.log(JSON.stringify(report.medians_ms));
|
||||
} catch (error) {
|
||||
report.error = error.stack;
|
||||
await save();
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.writeFile(source, original);
|
||||
for (const item of context.subscriptions) item.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,123 @@
|
||||
"""共享文件逐块读取、完整字节校验、EOF 与关闭;输入文件由驱动创建。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting input: Text
|
||||
loop checksum(bytes: Bytes) (out: Int)
|
||||
| each byte in bytes | result |
|
||||
| out | sum byte |
|
||||
rule sumChunk(state: dever.io.ReadState) (out: Int)
|
||||
| state | out |
|
||||
| Read(bytes) | checksum(bytes) |
|
||||
| End | fail(Invalid) |
|
||||
flow readChunk(file: dever.system.File) (out: Int)
|
||||
| step | kind | do |
|
||||
| state | flow | dever.io.read(file, 64) |
|
||||
| out | rule | sumChunk(state) |
|
||||
loop readChunks(file: dever.system.File, n: Int) (out: Int)
|
||||
| each index in range(0, n) | result |
|
||||
| out | sum readChunk(file) |
|
||||
rule ended(state: dever.io.ReadState) (out: Bool)
|
||||
| state | out |
|
||||
| Read(bytes) | false |
|
||||
| End | true |
|
||||
flow measure(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| file | flow | dever.io.open(input) |
|
||||
| out | loop | readChunks(file, n) |
|
||||
| state | flow | dever.io.read(file, 64) |
|
||||
| end | rule | ended(state) |
|
||||
| - | check | end else Invalid |
|
||||
| - | flow | dever.io.close(file) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::Bytes;
|
||||
use serde::Deserialize;
|
||||
use std::{fs, io::{self, Read}, sync::{Arc, Mutex}};
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Root { module: Module }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Module { main: Domain }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Domain { main: Settings }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings { input: String }
|
||||
struct File(Arc<Mutex<Option<fs::File>>>);
|
||||
fn closed() -> io::Error { io::Error::new(io::ErrorKind::BrokenPipe, "file is closed") }
|
||||
impl File {
|
||||
fn read(&self, limit: i64) -> io::Result<Option<Bytes>> {
|
||||
let limit = usize::try_from(limit).ok().filter(|n| *n > 0)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "read limit must be positive"))?;
|
||||
let mut guard = self.0.lock().map_err(|_| io::Error::other("file lock poisoned"))?;
|
||||
let file = guard.as_mut().ok_or_else(closed)?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(limit).map_err(io::Error::other)?;
|
||||
bytes.resize(limit, 0);
|
||||
let count = file.read(&mut bytes)?;
|
||||
bytes.truncate(count);
|
||||
Ok((count != 0).then(|| Bytes::from(bytes)))
|
||||
}
|
||||
fn close(&self) -> io::Result<()> {
|
||||
let file = self.0.lock().map_err(|_| io::Error::other("file lock poisoned"))?.take().ok_or_else(closed)?;
|
||||
drop(file);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let config = fs::read_to_string(std::env::args().nth(2).unwrap()).unwrap();
|
||||
let root: Root = serde_json::from_str(&config).unwrap();
|
||||
let file = File(Arc::new(Mutex::new(Some(fs::File::open(root.module.main.main.input).unwrap()))));
|
||||
let mut out = 0i64;
|
||||
for _ in 0..n {
|
||||
let bytes = file.read(64).unwrap().expect("premature EOF");
|
||||
let mut sum = 0i64;
|
||||
for byte in bytes { sum = sum.checked_add(i64::from(byte)).unwrap(); }
|
||||
out = out.checked_add(sum).unwrap();
|
||||
}
|
||||
assert!(file.read(64).unwrap().is_none());
|
||||
file.close().unwrap();
|
||||
println!("{out}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("encoding/json"; "fmt"; "io"; "os"; "strconv"; "sync")
|
||||
type File struct { mu sync.Mutex; file *os.File }
|
||||
func (file *File) read(limit int) []byte {
|
||||
if limit <= 0 { panic("read limit must be positive") }
|
||||
file.mu.Lock(); defer file.mu.Unlock()
|
||||
if file.file == nil { panic("file is closed") }
|
||||
buffer := make([]byte, limit)
|
||||
n, err := file.file.Read(buffer)
|
||||
if err != nil && err != io.EOF { panic(err) }
|
||||
return buffer[:n]
|
||||
}
|
||||
func (file *File) close() {
|
||||
file.mu.Lock(); defer file.mu.Unlock()
|
||||
if file.file == nil { panic("file is closed") }
|
||||
if err := file.file.Close(); err != nil { panic(err) }; file.file = nil
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
input, err := os.Open(os.Args[2]); if err != nil { panic(err) }
|
||||
var config struct { Module struct { Main struct { Main struct { Input string } } } }
|
||||
decoder := json.NewDecoder(input); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&config); err != nil { panic(err) }; input.Close()
|
||||
opened, err := os.Open(config.Module.Main.Main.Input); if err != nil { panic(err) }
|
||||
file := File{file: opened}; out := int64(0)
|
||||
for index := int64(0); index < n; index++ {
|
||||
bytes := file.read(64); if len(bytes) == 0 { panic("premature EOF") }
|
||||
sum := int64(0)
|
||||
for _, value := range bytes { next := sum + int64(value); if next < sum { panic("overflow") }; sum = next }
|
||||
next := out + sum; if next < out { panic("overflow") }; out = next
|
||||
}
|
||||
if len(file.read(64)) != 0 { panic("expected EOF") }; file.close()
|
||||
fmt.Println(out)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,118 @@
|
||||
"""同步共享文件流:一次读取、校验全部字节、关闭后验证别名结束。"""
|
||||
import file_reference
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting input: Text
|
||||
loop checksum(bytes: Bytes) (out: Int)
|
||||
| each byte in bytes | result |
|
||||
| out | sum byte |
|
||||
rule sumChunk(event: dever.io.ReadEvent) (out: Int)
|
||||
| event | out |
|
||||
| Chunk(bytes) | checksum(bytes) |
|
||||
| Failed(message) | fail(dever.io.ReadEvent.Failed(message)) |
|
||||
loop total(events: Stream<dever.io.ReadEvent>) (sum: Int, count: Int)
|
||||
| each event in events | result |
|
||||
| sum | sum sumChunk(event) |
|
||||
| count | count |
|
||||
flow measure(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| file | flow | dever.io.open(input) |
|
||||
| events | flow | dever.io.chunks(file, 64) |
|
||||
| result | loop | total(events) |
|
||||
| - | check | result.count == n else Invalid |
|
||||
| remaining | loop | total(events) |
|
||||
| - | check | remaining.count == 0 else Invalid |
|
||||
| - | flow | dever.io.close(file) |
|
||||
| out | calc | result.sum |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
prefix = file_reference.source('rust').split('fn main()')[0].replace('struct File(', '#[derive(Clone)]\nstruct File(')
|
||||
prefix = prefix.replace('limit: i64', 'limit: usize').replace(""" let limit = usize::try_from(limit).ok().filter(|n| *n > 0)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "read limit must be positive"))?;
|
||||
""", '')
|
||||
return prefix + '''struct Stream { source: Arc<Mutex<Option<File>>>, limit: usize }
|
||||
impl Stream {
|
||||
fn new(file: &File, limit: i64) -> io::Result<Self> {
|
||||
let limit = usize::try_from(limit).ok().filter(|n| *n > 0).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "read limit must be positive"))?;
|
||||
if file.0.lock().unwrap().is_none() { return Err(closed()); }
|
||||
Ok(Self { source: Arc::new(Mutex::new(Some(file.clone()))), limit })
|
||||
}
|
||||
fn next(&self) -> Option<io::Result<Bytes>> {
|
||||
let mut source = self.source.lock().unwrap();
|
||||
match source.as_ref()?.read(self.limit) {
|
||||
Ok(Some(bytes)) => Some(Ok(bytes)),
|
||||
Ok(None) => { source.take(); None },
|
||||
Err(error) => { source.take(); Some(Err(error)) },
|
||||
}
|
||||
}
|
||||
fn close(&self) { self.source.lock().unwrap().take(); }
|
||||
}
|
||||
struct Consume<'a>(&'a Stream);
|
||||
impl Drop for Consume<'_> { fn drop(&mut self) { self.0.close(); } }
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let config = fs::read_to_string(std::env::args().nth(2).unwrap()).unwrap();
|
||||
let root: Root = serde_json::from_str(&config).unwrap();
|
||||
let file = File(Arc::new(Mutex::new(Some(fs::File::open(root.module.main.main.input).unwrap()))));
|
||||
let stream = Stream::new(&file, 64).unwrap();
|
||||
let out = {
|
||||
let _close = Consume(&stream);
|
||||
let mut out = 0i64;
|
||||
let mut count = 0i64;
|
||||
while let Some(bytes) = stream.next() {
|
||||
let bytes = bytes.unwrap();
|
||||
let mut sum = 0i64;
|
||||
for byte in bytes { sum = sum.checked_add(i64::from(byte)).unwrap(); }
|
||||
out = out.checked_add(sum).unwrap();
|
||||
count = count.checked_add(1).unwrap();
|
||||
}
|
||||
assert_eq!(count, n);
|
||||
out
|
||||
};
|
||||
assert!(stream.next().is_none());
|
||||
file.close().unwrap();
|
||||
println!("{out}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("encoding/json"; "fmt"; "io"; "os"; "strconv"; "sync")
|
||||
type File struct { mu sync.Mutex; file *os.File }
|
||||
func (file *File) read(limit int) []byte {
|
||||
file.mu.Lock(); defer file.mu.Unlock()
|
||||
if file.file == nil { panic("file is closed") }
|
||||
bytes := make([]byte, limit); n, err := file.file.Read(bytes)
|
||||
if err != nil && err != io.EOF { panic(err) }; return bytes[:n]
|
||||
}
|
||||
type Stream struct { mu sync.Mutex; file *File; limit int }
|
||||
func (stream *Stream) next() []byte {
|
||||
stream.mu.Lock(); defer stream.mu.Unlock()
|
||||
if stream.file == nil { return nil }
|
||||
bytes := stream.file.read(stream.limit)
|
||||
if len(bytes) == 0 { stream.file = nil }; return bytes
|
||||
}
|
||||
func (stream *Stream) close() { stream.mu.Lock(); stream.file = nil; stream.mu.Unlock() }
|
||||
func total(stream *Stream, n int64) int64 {
|
||||
defer stream.close(); out, count := int64(0), int64(0)
|
||||
for bytes := stream.next(); len(bytes) > 0; bytes = stream.next() {
|
||||
sum := int64(0)
|
||||
for _, value := range bytes { next := sum + int64(value); if next < sum { panic("overflow") }; sum = next }
|
||||
next := out + sum; if next < out { panic("overflow") }; out = next; count++
|
||||
}
|
||||
if count != n { panic("chunk count") }; return out
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
input, err := os.Open(os.Args[2]); if err != nil { panic(err) }
|
||||
var config struct { Module struct { Main struct { Main struct { Input string } } } }
|
||||
decoder := json.NewDecoder(input); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&config); err != nil { panic(err) }; input.Close()
|
||||
opened, err := os.Open(config.Module.Main.Main.Input); if err != nil { panic(err) }
|
||||
file := File{file: opened}; stream := Stream{file: &file, limit: 64}
|
||||
out := total(&stream, n); if len(stream.next()) != 0 { panic("closed alias") }
|
||||
if err := opened.Close(); err != nil { panic(err) }; file.file = nil
|
||||
fmt.Println(out)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,148 @@
|
||||
//! 独立权限查询对端;复用官方 SQLite 资源模块,不链接 Dever 运行库。
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::{Pool, rusqlite::Connection};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::{
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const ROLE: &str = "SELECT EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND u.user_id=$2 AND r.enabled=TRUE AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$3)))";
|
||||
const LOCAL: &str = "SELECT EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND u.user_id=$2 AND r.enabled=TRUE AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$3)) AND EXISTS(SELECT 1 FROM _dever_permission p WHERE p.site=u.site AND p.key=$3 AND p.active=TRUE))";
|
||||
const CAPABILITY: &str = "capability:content.article.admin.00000000-0000-0000-0000-00000000002a";
|
||||
|
||||
fn prepare(path: &Path) -> Result<()> {
|
||||
drop(
|
||||
std::fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(path)?,
|
||||
);
|
||||
let connection = Connection::open(path)?;
|
||||
connection.execute_batch(
|
||||
"CREATE TABLE _dever_permission(key TEXT PRIMARY KEY,site TEXT NOT NULL,component TEXT NOT NULL,domain TEXT NOT NULL,action TEXT NOT NULL,active BOOLEAN NOT NULL CHECK(active IN (0,1)),method TEXT NOT NULL,kind TEXT NOT NULL);
|
||||
CREATE TABLE _dever_role(site TEXT NOT NULL,id TEXT NOT NULL,name TEXT NOT NULL,all_permissions BOOLEAN NOT NULL CHECK(all_permissions IN (0,1)),enabled BOOLEAN NOT NULL CHECK(enabled IN (0,1)),protected BOOLEAN NOT NULL CHECK(protected IN (0,1)),PRIMARY KEY(site,id));
|
||||
CREATE TABLE _dever_user_role(site TEXT NOT NULL,user_id INTEGER NOT NULL CHECK(user_id>0),role_id TEXT NOT NULL,PRIMARY KEY(site,user_id,role_id),FOREIGN KEY(site,role_id) REFERENCES _dever_role(site,id) ON DELETE CASCADE);
|
||||
CREATE TABLE _dever_role_permission(site TEXT NOT NULL,role_id TEXT NOT NULL,permission_key TEXT NOT NULL,PRIMARY KEY(site,role_id,permission_key),FOREIGN KEY(site,role_id) REFERENCES _dever_role(site,id) ON DELETE CASCADE);
|
||||
CREATE TABLE _dever_tenant_component(tenant INTEGER NOT NULL,component TEXT NOT NULL,enabled BOOLEAN NOT NULL,PRIMARY KEY(tenant,component));
|
||||
CREATE TABLE _dever_auth_capability(key TEXT PRIMARY KEY,component TEXT NOT NULL,domain TEXT NOT NULL,site TEXT NOT NULL,action TEXT NOT NULL,active BOOLEAN NOT NULL);
|
||||
INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http');
|
||||
INSERT INTO _dever_tenant_component VALUES (1,'content',TRUE);
|
||||
INSERT INTO _dever_auth_capability VALUES ('capability:content.article.admin.00000000-0000-0000-0000-00000000002a','content','article','admin','00000000-0000-0000-0000-00000000002a',TRUE);
|
||||
INSERT INTO _dever_role VALUES ('admin','owner','Owner',TRUE,TRUE,TRUE);
|
||||
INSERT INTO _dever_user_role VALUES ('admin',7,'owner');",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn authorize(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
catalog: Option<&Pool>,
|
||||
user: i64,
|
||||
) -> Result<bool> {
|
||||
let sql = if let Some(catalog) = catalog {
|
||||
let mut catalog_lease = Some(Lease {
|
||||
object: Some(catalog.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let exists = work.call(&mut catalog_lease, Duration::from_secs(2), |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_permission WHERE site=$1 AND key=$2 AND active=TRUE)")?
|
||||
.query_row(["admin", "content.article.admin.read"], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
if !exists {
|
||||
return Ok(false);
|
||||
}
|
||||
ROLE
|
||||
} else {
|
||||
LOCAL
|
||||
};
|
||||
work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached(sql)?.query_row(
|
||||
deadpool_sqlite::rusqlite::params!["admin", user, "content.article.admin.read"],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn authorize_tenant(
|
||||
work: &Work, lease: &mut Option<Lease>, catalog: &Pool, user: i64, key: &'static str,
|
||||
) -> Result<bool> {
|
||||
let mut control = Some(Lease { object: Some(catalog.get().await?), reusable: true });
|
||||
if key.starts_with("capability:") {
|
||||
use deadpool_sqlite::rusqlite::OptionalExtension;
|
||||
let permission = work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT c.component,EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$2)) AND u.user_id=$3 AND r.enabled=TRUE) FROM _dever_auth_capability c WHERE c.site=$1 AND c.key=$2 AND c.active=TRUE")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params!["admin",key,user], |row| Ok((row.get::<_,String>(0)?, row.get::<_,bool>(1)?))).optional()?)
|
||||
}).await?;
|
||||
let Some((component, allowed)) = permission else { return Ok(false) };
|
||||
let enabled = work.call(&mut control, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_tenant_component WHERE tenant=$1 AND component=$2 AND enabled=TRUE)")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params![1,component], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
return Ok(enabled && allowed);
|
||||
} else {
|
||||
let enabled = work.call(&mut control, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_permission p WHERE site=$1 AND key=$2 AND active=TRUE AND EXISTS(SELECT 1 FROM _dever_tenant_component c WHERE c.tenant=$3 AND c.component=p.component AND c.enabled=TRUE))")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params!["admin", key, 1], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
if !enabled { return Ok(false) }
|
||||
}
|
||||
work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached(ROLE)?.query_row(
|
||||
deadpool_sqlite::rusqlite::params!["admin",user,key], |row| row.get(0))?)
|
||||
}).await
|
||||
}
|
||||
|
||||
async fn measure(first: &str, second: &str, tenant: bool) -> Result<()> {
|
||||
let database = pool(first, 1).await?;
|
||||
let separate = pool(second, 1).await?;
|
||||
let work = Work::new();
|
||||
println!("case,sample,iterations,elapsed_ns,allowed");
|
||||
let cases = if tenant { [("tenant",Some(&separate)), ("capability",Some(&separate))] }
|
||||
else { [("same",None), ("separate",Some(&separate))] };
|
||||
for (name, catalog) in cases {
|
||||
for (user, expected) in [(7, true), (8, false)] {
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
for sample in -1..7 {
|
||||
let started = Instant::now();
|
||||
let mut allowed = 0;
|
||||
for _ in 0..256 {
|
||||
let result = if tenant {
|
||||
let key = if name == "tenant" { "content.article.admin.read" } else { CAPABILITY };
|
||||
authorize_tenant(&work, &mut lease, &separate, user, key).await?
|
||||
} else { authorize(&work, &mut lease, catalog, user).await? };
|
||||
assert_eq!(result, expected);
|
||||
allowed += usize::from(result);
|
||||
}
|
||||
println!(
|
||||
"{name}_{expected},{sample},256,{},{}",
|
||||
started.elapsed().as_nanos(),
|
||||
allowed
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
work.finish().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let directory = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or("provide a new fixture directory")?;
|
||||
let directory = Path::new(&directory);
|
||||
std::fs::create_dir(directory)?;
|
||||
let first = directory.join("roles.sqlite");
|
||||
let second = directory.join("catalog.sqlite");
|
||||
prepare(&first)?;
|
||||
prepare(&second)?;
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()?
|
||||
.block_on(measure(first.to_str().unwrap(), second.to_str().unwrap(), std::env::args().nth(2).as_deref()==Some("--tenant")))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
cmd submit = app.submit
|
||||
cmd submitAll = app.submitAll
|
||||
job publish(input: app.Payload) retry(2) timeout(1000) = app.apply
|
||||
@@ -0,0 +1,21 @@
|
||||
type Payload { name: Text, amount: Int }
|
||||
|
||||
flow submit(input: Payload, key: Text) (id: Id)
|
||||
| step | kind | do |
|
||||
| id | calc | enqueue(job.publish, input, key) |
|
||||
|
||||
type Submission { key: Text, payload: Payload }
|
||||
|
||||
loop submissions(inputs: List<Payload>) (result: List<Submission>)
|
||||
| each input in inputs | result |
|
||||
| result | list Submission { key = input.name, payload = input } |
|
||||
|
||||
flow submitAll(inputs: List<Payload>) (ids: List<Id>)
|
||||
| step | kind | do |
|
||||
| ids | calc | enqueueMany(job.publish, submissions(inputs)) |
|
||||
|
||||
flow apply(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| amount | calc | input.amount * 3 + 7 |
|
||||
| saved | data | data.create({ name = input.name, amount = amount }) |
|
||||
| - | check | saved.amount >= 0 else Conflict |
|
||||
@@ -0,0 +1,103 @@
|
||||
//! System Job 的完整持久合同参考;共用基础队列操作,不链接 Dever 运行库。
|
||||
use crate::base_queue;
|
||||
pub(crate) use base_queue::{Batch, Payload, Submit, enqueue, insert, transition};
|
||||
use base_queue::{Result, SCHEMA, TARGET, identifier, now};
|
||||
use deadpool_sqlite::rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub(crate) struct Claim {
|
||||
value: base_queue::Claim,
|
||||
target: String,
|
||||
schema: String,
|
||||
execution: String,
|
||||
tenant: i64,
|
||||
retries: i64,
|
||||
timeout_ms: i64,
|
||||
}
|
||||
impl std::ops::Deref for Claim {
|
||||
type Target = base_queue::Claim;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Rejected(String);
|
||||
impl std::fmt::Display for Rejected {
|
||||
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
out.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Rejected {}
|
||||
fn rejected(cause: impl std::fmt::Display) -> Box<dyn std::error::Error + Send + Sync> {
|
||||
Box::new(Rejected(cause.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "kind", deny_unknown_fields)]
|
||||
enum Execution {
|
||||
System { tenant: Option<i64> },
|
||||
}
|
||||
|
||||
pub(crate) fn decode(claim: &Claim) -> Result<Payload> {
|
||||
if claim.target != TARGET
|
||||
|| claim.schema != SCHEMA
|
||||
|| claim.tenant != 0
|
||||
|| claim.retries != 2
|
||||
|| claim.timeout_ms != 1000
|
||||
{
|
||||
return Err(rejected(
|
||||
"queued Job differs from its declaration or physical queue",
|
||||
));
|
||||
}
|
||||
if claim.execution.len() > 16 * 1024 * 1024 || claim.payload.len() > 16 * 1024 * 1024 {
|
||||
return Err(rejected("Job JSON exceeds 16 MiB"));
|
||||
}
|
||||
let Execution::System { tenant } = serde_json::from_str(&claim.execution).map_err(rejected)?;
|
||||
if tenant.is_some() {
|
||||
return Err(rejected(
|
||||
"Job execution tenant differs from its physical queue",
|
||||
));
|
||||
}
|
||||
// Serde 的结构体默认也接受位置数组;Dever 的具名载荷合同只接受对象。
|
||||
struct Object;
|
||||
impl<'de> serde::de::Visitor<'de> for Object {
|
||||
type Value = Payload;
|
||||
fn expecting(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
out.write_str("Job payload object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, fields: A) -> std::result::Result<Payload, A::Error> {
|
||||
Payload::deserialize(serde::de::value::MapAccessDeserializer::new(fields))
|
||||
}
|
||||
}
|
||||
let mut decoder = serde_json::Deserializer::from_str(&claim.payload);
|
||||
let value = serde::Deserializer::deserialize_map(&mut decoder, Object).map_err(rejected)?;
|
||||
decoder.end().map_err(rejected)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn claim(connection: &mut Connection) -> Result<Option<Claim>> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let clock = now();
|
||||
tx.prepare_cached("UPDATE _dever_job SET state=CASE WHEN attempt >= retries THEN 'dead' ELSE 'pending' END,token=NULL,lease_until=NULL,error='lease expired' WHERE id IN (SELECT id FROM _dever_job WHERE state='running' AND lease_until<=?1 ORDER BY lease_until,id LIMIT 256)")?.execute([clock])?;
|
||||
let token = identifier()?;
|
||||
let value = tx.prepare_cached(
|
||||
"SELECT id,target,substr(payload,1,16777217),schema,substr(execution,1,16777217),retries,timeout_ms,attempt,execution_tenant FROM _dever_job
|
||||
WHERE id=(SELECT id FROM (
|
||||
SELECT id,available_at FROM _dever_job WHERE state='pending' AND attempt < retries AND available_at <= ?1
|
||||
UNION ALL
|
||||
SELECT id,available_at FROM _dever_job WHERE state='running' AND attempt < retries AND lease_until <= ?1 AND available_at <= ?1
|
||||
ORDER BY available_at,id LIMIT 1
|
||||
))"
|
||||
)?.query_row([clock], |row| Ok(Claim {
|
||||
value: base_queue::Claim { id: row.get(0)?, payload: row.get(2)?, attempt: row.get::<_,i64>(7)?+1, token },
|
||||
target: row.get(1)?, schema: row.get(3)?, execution: row.get(4)?,
|
||||
retries: row.get(5)?, timeout_ms: row.get(6)?, tenant: row.get(8)?,
|
||||
})).optional()?;
|
||||
if let Some(value) = &value {
|
||||
tx.prepare_cached("UPDATE _dever_job SET state='running',attempt=?1,token=?2,lease_until=?3,error=CASE WHEN state='running' THEN 'lease expired' ELSE error END WHERE id=?4")?
|
||||
.execute(params![value.attempt,value.token,clock+10000,value.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
type Queue { name: Text, amount: Int }
|
||||
@@ -0,0 +1,22 @@
|
||||
type Payload { name: Text, amount: Int }
|
||||
|
||||
submit(input: Payload, key: Text) (id: Id) {
|
||||
id = dever.job.enqueue(job.publish, input, key)
|
||||
}
|
||||
|
||||
submitOne(input: Payload) (id: Id) {
|
||||
id = submit(input, input.name)
|
||||
}
|
||||
|
||||
submitAll(inputs: List<Payload>) (ids: List<Id>) {
|
||||
ids = each(submitOne, inputs)
|
||||
}
|
||||
|
||||
apply(input: Payload) () {
|
||||
amount = input.amount * 3 + 7
|
||||
saved = model.create({ name = input.name, amount = amount })
|
||||
reject(saved.amount < 0)
|
||||
}
|
||||
|
||||
reject(failed: true) () { fail(dever.api.Error.Conflict) }
|
||||
reject(failed: false) () {}
|
||||
@@ -0,0 +1,284 @@
|
||||
// 独立 database/sql 队列参考;事务和取消交给驱动,信号后等待在途事务完成。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const target = "benchmark.queue.publish"
|
||||
const schema = "Payload{name:Text,amount:Int}"
|
||||
|
||||
type Payload struct {
|
||||
Name string "json:\"name\""
|
||||
Amount int64 "json:\"amount\""
|
||||
}
|
||||
type Submit struct {
|
||||
Input Payload "json:\"input\""
|
||||
Key string "json:\"key\""
|
||||
}
|
||||
type Batch struct {
|
||||
Inputs []Payload "json:\"inputs\""
|
||||
}
|
||||
type Claim struct {
|
||||
ID, Payload, Token string
|
||||
Attempt int64
|
||||
}
|
||||
|
||||
func identifier() (string, error) {
|
||||
var value [16]byte
|
||||
_, err := rand.Read(value[:])
|
||||
return hex.EncodeToString(value[:]), err
|
||||
}
|
||||
|
||||
func decode(raw string, out any) error {
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(out); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("trailing JSON: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func submit(db *sql.DB, inputs []Submit) ([]string, error) {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
insert, err := tx.Prepare("INSERT INTO _dever_job(id,target,payload,schema,execution,execution_tenant,task_key,state,retries,timeout_ms,available_at,created_at) VALUES (?,?,?,?,'{\"kind\":\"System\",\"tenant\":null}',0,?,'pending',2,1000,?,?) ON CONFLICT(execution_tenant,target,task_key) WHERE state IN ('pending','running') DO NOTHING")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer insert.Close()
|
||||
find, err := tx.Prepare("SELECT id FROM _dever_job WHERE execution_tenant=0 AND target=? AND task_key=? AND state IN ('pending','running')")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer find.Close()
|
||||
ids := make([]string, 0, len(inputs))
|
||||
for _, value := range inputs {
|
||||
if len(value.Key) == 0 || len(value.Key) > 1024 {
|
||||
return nil, errors.New("invalid key")
|
||||
}
|
||||
id, err := identifier()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload, err := json.Marshal(value.Input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clock := time.Now().UnixMilli()
|
||||
result, err := insert.Exec(id, target, string(payload), schema, value.Key, clock, clock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
changed, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if changed == 0 {
|
||||
if err = find.QueryRow(target, value.Key).Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, tx.Commit()
|
||||
}
|
||||
|
||||
func claim(db *sql.DB) (*Claim, error) {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
clock := time.Now().UnixMilli()
|
||||
_, err = tx.Exec("UPDATE _dever_job SET state=CASE WHEN attempt>=retries THEN 'dead' ELSE 'pending' END,token=NULL,lease_until=NULL,error='lease expired' WHERE id IN (SELECT id FROM _dever_job WHERE state='running' AND lease_until<=? ORDER BY lease_until,id LIMIT 256)", clock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var value Claim
|
||||
value.Token, err = identifier()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tx.QueryRow("SELECT id,payload,attempt FROM _dever_job WHERE state='pending' AND available_at<=? AND attempt<retries ORDER BY available_at,id LIMIT 1", clock).Scan(&value.ID, &value.Payload, &value.Attempt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, tx.Commit()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value.Attempt++
|
||||
_, err = tx.Exec("UPDATE _dever_job SET state='running',attempt=?,token=?,lease_until=? WHERE id=?", value.Attempt, value.Token, clock+10000, value.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &value, tx.Commit()
|
||||
}
|
||||
|
||||
func transition(ctx context.Context, tx *sql.Tx, value *Claim, state string, failure any) error {
|
||||
clock := time.Now().UnixMilli()
|
||||
result, err := tx.ExecContext(ctx, "UPDATE _dever_job SET state=?,available_at=?,error=?,token=NULL,lease_until=NULL WHERE id=? AND state='running' AND token=? AND lease_until>?", state, clock+1, failure, value.ID, value.Token, clock)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
changed, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if changed != 1 {
|
||||
return errors.New("lease ownership lost")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func apply(db *sql.DB, value *Claim) (bool, error) {
|
||||
var input Payload
|
||||
if err := decode(value.Payload, &input); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if input.Amount > math.MaxInt64/3 || input.Amount < math.MinInt64/3 {
|
||||
return false, errors.New("amount overflow")
|
||||
}
|
||||
amount := input.Amount * 3
|
||||
if amount > math.MaxInt64-7 {
|
||||
return false, errors.New("amount overflow")
|
||||
}
|
||||
amount += 7
|
||||
var id, created, stored int64
|
||||
var name string
|
||||
err = tx.QueryRowContext(ctx, "INSERT INTO benchmark_queue(created_at,name,amount) VALUES (?,?,?) RETURNING id,created_at,name,amount", time.Now().UnixMilli(), strings.TrimSpace(input.Name), amount).Scan(&id, &created, &name, &stored)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if stored < 0 {
|
||||
return false, nil
|
||||
}
|
||||
if err = transition(ctx, tx, value, "completed", nil); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit()
|
||||
}
|
||||
|
||||
func work(db *sql.DB, value *Claim) error {
|
||||
accepted, err := apply(db, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if accepted {
|
||||
return nil
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
state := "pending"
|
||||
if value.Attempt >= 2 {
|
||||
state = "dead"
|
||||
}
|
||||
if err = transition(context.Background(), tx, value, state, "handler failed"); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func run() error {
|
||||
db, err := sql.Open("sqlite3", "file:"+os.Args[1]+"?mode=rw&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMAL&_busy_timeout=30000&_txlock=immediate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(2)
|
||||
if os.Args[2] == "worker" {
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
value, err := claim(db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value != nil {
|
||||
if err = work(db, value); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var inputs []Submit
|
||||
switch os.Args[2] {
|
||||
case "submitAll":
|
||||
var batch Batch
|
||||
if err = decode(os.Args[3], &batch); err != nil {
|
||||
return err
|
||||
}
|
||||
if batch.Inputs == nil {
|
||||
return errors.New("inputs required")
|
||||
}
|
||||
for _, input := range batch.Inputs {
|
||||
inputs = append(inputs, Submit{Input: input, Key: input.Name})
|
||||
}
|
||||
case "submit":
|
||||
var input Submit
|
||||
if err = decode(os.Args[3], &input); err != nil {
|
||||
return err
|
||||
}
|
||||
inputs = []Submit{input}
|
||||
default:
|
||||
return errors.New("unknown command")
|
||||
}
|
||||
ids, err := submit(db, inputs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Args[2] == "submit" {
|
||||
return json.NewEncoder(os.Stdout).Encode(ids[0])
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(ids)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! 独立队列参考:官方 SQLite 事务、deadpool 阻塞交接及 Tokio 信号,不链接 Dever。
|
||||
mod queue;
|
||||
use deadpool_sqlite::{Object, Runtime, rusqlite::Connection};
|
||||
use queue::*;
|
||||
use std::time::Duration;
|
||||
|
||||
async fn call<T: Send + 'static>(
|
||||
object: &Object,
|
||||
action: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
// 每次阻塞操作都等待真实结束,终止信号不丢弃正在提交或回滚的任务。
|
||||
object
|
||||
.interact(action)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
async fn run() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let pool = deadpool_sqlite::Config::new(&args[1])
|
||||
.builder(Runtime::Tokio1)?
|
||||
.max_size(2)
|
||||
.build()?;
|
||||
let object = pool.get().await?;
|
||||
call(&object, |connection| {
|
||||
connection.execute_batch(
|
||||
"PRAGMA journal_mode=WAL;PRAGMA synchronous=NORMAL;PRAGMA foreign_keys=ON;",
|
||||
)?;
|
||||
connection.busy_timeout(Duration::from_secs(30))?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
if args[2] == "worker" {
|
||||
let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
loop {
|
||||
// 仅在领取间隙停止;已经领取的工作在上方期限内完成事务收尾。
|
||||
let stopping = tokio::select! { biased;
|
||||
_ = stop.recv() => true,
|
||||
_ = std::future::ready(()) => false,
|
||||
};
|
||||
if stopping {
|
||||
break;
|
||||
}
|
||||
match call(&object, claim).await? {
|
||||
Some(value) => call(&object, move |connection| apply(connection, value)).await?,
|
||||
None => tokio::select! {
|
||||
_ = stop.recv() => break,
|
||||
_ = tokio::time::sleep(Duration::from_millis(1)) => {},
|
||||
},
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let inputs = match args[2].as_str() {
|
||||
"submitAll" => serde_json::from_str::<Batch>(&args[3])?
|
||||
.inputs
|
||||
.into_iter()
|
||||
.map(|input| Submit {
|
||||
key: input.name.clone(),
|
||||
input,
|
||||
})
|
||||
.collect(),
|
||||
"submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
|
||||
_ => return Err("unknown command".into()),
|
||||
};
|
||||
let ids = call(&object, move |connection| submit(connection, inputs)).await?;
|
||||
let out = if args[2] == "submit" {
|
||||
serde_json::to_value(&ids[0])?
|
||||
} else {
|
||||
serde_json::to_value(ids)?
|
||||
};
|
||||
println!("{out}");
|
||||
}
|
||||
drop(object);
|
||||
pool.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
if let Err(error) = runtime.block_on(run()) {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! 独立 Job 对端的 SQL 业务;两种资源调度共用同一队列合同。
|
||||
use deadpool_sqlite::rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
error::Error,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
#[cfg(not(feature = "contract"))]
|
||||
pub(crate) const TARGET: &str = "benchmark.queue.publish";
|
||||
#[cfg(not(feature = "contract"))]
|
||||
pub(crate) const SCHEMA: &str = "Payload{name:Text,amount:Int}";
|
||||
// 完整合同对照保留与实际 Dever fixture 相同的持久声明,避免行宽差异改变 B-tree 成本。
|
||||
#[cfg(feature = "contract")]
|
||||
pub(crate) const TARGET: &str = "benchmark.queue.job.publish";
|
||||
#[cfg(feature = "contract")]
|
||||
pub(crate) const SCHEMA: &str = "550a5abbd4954e48b26bf2d51a821e0ce6b143622a82373344ded0ee8aef124a";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Payload {
|
||||
pub(crate) name: String,
|
||||
pub(crate) amount: i64,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Batch {
|
||||
pub(crate) inputs: Vec<Payload>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Submit {
|
||||
pub(crate) input: Payload,
|
||||
pub(crate) key: String,
|
||||
}
|
||||
pub(crate) struct Claim {
|
||||
pub(crate) id: String,
|
||||
pub(crate) token: String,
|
||||
pub(crate) payload: String,
|
||||
pub(crate) attempt: i64,
|
||||
}
|
||||
|
||||
pub(crate) fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
.try_into()
|
||||
.unwrap()
|
||||
}
|
||||
pub(crate) fn identifier() -> Result<String> {
|
||||
let mut bytes = [0; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{:032x}", u128::from_be_bytes(bytes)))
|
||||
}
|
||||
|
||||
pub(crate) fn submit(connection: &mut Connection, inputs: Vec<Submit>) -> Result<Vec<String>> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let mut ids = Vec::with_capacity(inputs.len());
|
||||
for value in inputs {
|
||||
ids.push(enqueue(&tx, value)?);
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(crate) fn enqueue(connection: &Connection, value: Submit) -> Result<String> {
|
||||
if value.key.is_empty() || value.key.len() > 1024 {
|
||||
return Err("invalid key".into());
|
||||
}
|
||||
let id = identifier()?;
|
||||
let payload = serde_json::to_string(&value.input)?;
|
||||
let inserted = connection.prepare_cached("INSERT INTO _dever_job(id,target,payload,schema,execution,execution_tenant,task_key,state,retries,timeout_ms,available_at,created_at) VALUES (?1,?2,?3,?4,'{\"kind\":\"System\",\"tenant\":null}',0,?5,'pending',2,1000,?6,?6) ON CONFLICT(execution_tenant,target,task_key) WHERE state IN ('pending','running') DO NOTHING")?
|
||||
.execute(params![id, TARGET, payload, SCHEMA, value.key, now()])?;
|
||||
Ok(if inserted == 1 {
|
||||
id
|
||||
} else {
|
||||
connection.prepare_cached("SELECT id FROM _dever_job WHERE execution_tenant=0 AND target=?1 AND task_key=?2 AND state IN ('pending','running')")?
|
||||
.query_row(params![TARGET, value.key], |row| row.get(0))?
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn claim(connection: &mut Connection) -> Result<Option<Claim>> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let clock = now();
|
||||
tx.prepare_cached("UPDATE _dever_job SET state=CASE WHEN attempt >= retries THEN 'dead' ELSE 'pending' END,token=NULL,lease_until=NULL,error='lease expired' WHERE id IN (SELECT id FROM _dever_job WHERE state='running' AND lease_until<=?1 ORDER BY lease_until,id LIMIT 256)")?.execute([clock])?;
|
||||
let token = identifier()?;
|
||||
let value = tx.prepare_cached("SELECT id,payload,attempt FROM _dever_job WHERE state='pending' AND available_at<=?1 AND attempt<retries ORDER BY available_at,id LIMIT 1")?
|
||||
.query_row([clock], |row| Ok(Claim { id:row.get(0)?, payload:row.get(1)?, attempt:row.get::<_,i64>(2)?+1, token })).optional()?;
|
||||
if let Some(value) = &value {
|
||||
tx.prepare_cached(
|
||||
"UPDATE _dever_job SET state='running',attempt=?1,token=?2,lease_until=?3 WHERE id=?4",
|
||||
)?
|
||||
.execute(params![value.attempt, value.token, clock + 10000, value.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn transition(
|
||||
connection: &Connection,
|
||||
claim: &Claim,
|
||||
state: &str,
|
||||
error: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let clock = now();
|
||||
let changed = connection.prepare_cached("UPDATE _dever_job SET state=?1,available_at=?2,error=?3,token=NULL,lease_until=NULL WHERE id=?4 AND state='running' AND token=?5 AND lease_until>?6")?
|
||||
.execute(params![state, clock+1, error, claim.id, claim.token, clock])?;
|
||||
if changed != 1 {
|
||||
return Err("lease ownership lost".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn apply(connection: &mut Connection, claim: Claim) -> Result<()> {
|
||||
let input: Payload = serde_json::from_str(&claim.payload)?;
|
||||
let deadline = Instant::now() + Duration::from_millis(1000);
|
||||
connection.progress_handler(1000, Some(move || Instant::now() >= deadline))?;
|
||||
let outcome = (|| -> Result<bool> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let saved = insert(&tx, input)?;
|
||||
if saved.3 < 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
transition(&tx, &claim, "completed", None)?;
|
||||
if Instant::now() >= deadline {
|
||||
return Err("handler deadline expired".into());
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
})();
|
||||
connection.progress_handler(0, None::<fn() -> bool>)?;
|
||||
if !outcome? {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
transition(
|
||||
&tx,
|
||||
&claim,
|
||||
if claim.attempt >= 2 {
|
||||
"dead"
|
||||
} else {
|
||||
"pending"
|
||||
},
|
||||
Some("handler failed"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn insert(connection: &Connection, input: Payload) -> Result<(i64, i64, String, i64)> {
|
||||
let amount = input
|
||||
.amount
|
||||
.checked_mul(3)
|
||||
.and_then(|n| n.checked_add(7))
|
||||
.ok_or("amount overflow")?;
|
||||
let mut statement = connection.prepare_cached("INSERT INTO benchmark_queue(created_at,name,amount) VALUES (?1,?2,?3) RETURNING id,created_at,name,amount")?;
|
||||
let mut rows = statement.query(params![now(), input.name.trim(), amount])?;
|
||||
let row = rows.next()?.ok_or("missing inserted row")?;
|
||||
let saved = (row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?);
|
||||
rows.next()?;
|
||||
Ok(saved)
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
//! 逐操作交接的独立 Job 对端;保留轻量队列参考,不用较慢参考覆盖它。
|
||||
#[allow(dead_code)]
|
||||
#[cfg(not(feature = "contract"))]
|
||||
mod queue;
|
||||
#[cfg(feature = "contract")]
|
||||
#[allow(dead_code)]
|
||||
#[path = "queue.rs"]
|
||||
mod base_queue;
|
||||
#[cfg(feature = "contract")]
|
||||
#[path = "contract.rs"]
|
||||
mod queue;
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::rusqlite::TransactionBehavior;
|
||||
use futures_util::FutureExt;
|
||||
use queue::{Batch, Claim, Payload, Submit};
|
||||
use sqlite_resource::{Lease, Result, Work, panic_message, pool};
|
||||
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc, time::Duration};
|
||||
use tokio::time::Instant;
|
||||
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
async fn submit(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
inputs: Vec<Submit>,
|
||||
) -> Result<Vec<String>> {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let mut ids = Vec::with_capacity(inputs.len());
|
||||
for value in inputs {
|
||||
ids.push(
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::enqueue(connection, value)
|
||||
})
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
async fn handle(work: &Work, lease: &mut Option<Lease>, input: Payload) -> Result<()> {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let saved = work
|
||||
.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::insert(connection, input)
|
||||
})
|
||||
.await?;
|
||||
if saved.3 < 0 {
|
||||
return Err("negative amount".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait<T>(
|
||||
work: &Work,
|
||||
deadline: Instant,
|
||||
handler: impl Future<Output = Result<T>>,
|
||||
) -> Result<T> {
|
||||
let outcome = AssertUnwindSafe(tokio::time::timeout_at(deadline, handler))
|
||||
.catch_unwind()
|
||||
.await
|
||||
.map_err(|panic| panic_message(panic).into())
|
||||
.and_then(|value| value.map_err(Into::into))
|
||||
.and_then(|value| value);
|
||||
// 单 worker 没有并行的其他 Job;复用其 tracker,每次确认前等待真实后代退出。
|
||||
let cleanup = work.finish().await;
|
||||
match (outcome, cleanup) {
|
||||
(Ok(value), Ok(())) if Instant::now() < deadline => Ok(value),
|
||||
(Ok(_), Ok(())) => Err("handler deadline expired during cleanup".into()),
|
||||
(Err(cause), Ok(())) | (Ok(_), Err(cause)) => Err(cause),
|
||||
(Err(cause), Err(cleanup)) => Err(format!("{cause}; cleanup: {cleanup}").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn process(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
database: &deadpool_sqlite::Pool,
|
||||
claim: Claim,
|
||||
) -> Result<()> {
|
||||
let claim = Arc::new(claim);
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let outcome = wait(work, deadline, async {
|
||||
#[cfg(not(feature = "contract"))]
|
||||
let input = serde_json::from_str(&claim.payload)?;
|
||||
#[cfg(feature = "contract")]
|
||||
let input = queue::decode(&claim)?;
|
||||
handle(work, lease, input).await
|
||||
})
|
||||
.await;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
let value = claim.clone();
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::transition(connection, &value, "completed", None)
|
||||
})
|
||||
.await?;
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("Job handler: {error}");
|
||||
#[cfg(feature = "contract")]
|
||||
let rejected = error.is::<queue::Rejected>();
|
||||
#[cfg(not(feature = "contract"))]
|
||||
let rejected = false;
|
||||
if lease.is_none() {
|
||||
// wait 已等待取消的阻塞操作释放连接;此处重新借用,不能复用未提交租约。
|
||||
*lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
} else {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
if !connection.is_autocommit() {
|
||||
connection.execute_batch("ROLLBACK")?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
queue::transition(
|
||||
&tx,
|
||||
&claim,
|
||||
if rejected {
|
||||
"blocked"
|
||||
} else if claim.attempt >= 2 {
|
||||
"dead"
|
||||
} else {
|
||||
"pending"
|
||||
},
|
||||
Some("handler failed"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn worker(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
database: &deadpool_sqlite::Pool,
|
||||
) -> Result<()> {
|
||||
let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
loop {
|
||||
let stopping = tokio::select! { biased;
|
||||
_ = stop.recv() => true,
|
||||
_ = std::future::ready(()) => false,
|
||||
};
|
||||
if stopping {
|
||||
break;
|
||||
}
|
||||
match work.call(lease, IO_TIMEOUT, queue::claim).await? {
|
||||
Some(claim) => process(work, lease, database, claim).await?,
|
||||
None => tokio::select! {
|
||||
_ = stop.recv() => break,
|
||||
_ = tokio::time::sleep(Duration::from_millis(1)) => {},
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run(args: &[String]) -> Result<()> {
|
||||
let database = pool(&args[1], 2).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = async {
|
||||
if args[2] == "worker" {
|
||||
worker(&work, &mut lease, &database).await?;
|
||||
} else {
|
||||
let inputs = match args[2].as_str() {
|
||||
"submitAll" => serde_json::from_str::<Batch>(&args[3])?
|
||||
.inputs
|
||||
.into_iter()
|
||||
.map(|input| Submit {
|
||||
key: input.name.clone(),
|
||||
input,
|
||||
})
|
||||
.collect(),
|
||||
"submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
|
||||
_ => return Err("unknown command".into()),
|
||||
};
|
||||
let ids = submit(&work, &mut lease, inputs).await?;
|
||||
let out = if args[2] == "submit" {
|
||||
serde_json::to_value(&ids[0])?
|
||||
} else {
|
||||
serde_json::to_value(ids)?
|
||||
};
|
||||
println!("{out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
// 未提交的连接直接丢弃,SQLite 回滚;等待后台析构,保留清理中的原始错误。
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(database);
|
||||
if let Err(cause) = cleanup {
|
||||
if result.is_ok() {
|
||||
return Err(cause);
|
||||
}
|
||||
eprintln!("cleanup: {cause}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?
|
||||
.block_on(run(&args))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use deadpool_sqlite::rusqlite::Connection;
|
||||
|
||||
struct File(std::path::PathBuf);
|
||||
impl File {
|
||||
fn new() -> Self {
|
||||
let mut id = [0; 16];
|
||||
getrandom::getrandom(&mut id).unwrap();
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("job-boundary-{:032x}", u128::from_ne_bytes(id)));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
Connection::open(directory.join("queue.db"))
|
||||
.unwrap()
|
||||
.execute_batch("CREATE TABLE effects(value INTEGER)")
|
||||
.unwrap();
|
||||
Self(directory)
|
||||
}
|
||||
}
|
||||
impl Drop for File {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn scenario(
|
||||
handler_pending: bool,
|
||||
expired: bool,
|
||||
late_panic: bool,
|
||||
handler_panic: bool,
|
||||
) -> Result<()> {
|
||||
let file = File::new();
|
||||
let path = file.0.join("queue.db");
|
||||
let database = pool(path.to_str().unwrap(), 2).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (release, released) = std::sync::mpsc::channel();
|
||||
let (entered, ready) = tokio::sync::oneshot::channel();
|
||||
let deadline = Instant::now()
|
||||
+ if expired {
|
||||
Duration::from_millis(50)
|
||||
} else {
|
||||
IO_TIMEOUT
|
||||
};
|
||||
let handler = async {
|
||||
let (started, blocking) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let operation = work.call(&mut lease, IO_TIMEOUT, move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO effects VALUES(1)")?;
|
||||
started.send(()).unwrap();
|
||||
released.recv()?;
|
||||
assert!(!late_panic, "late SQLite panic");
|
||||
Ok(())
|
||||
});
|
||||
tokio::pin!(operation);
|
||||
tokio::select! {
|
||||
result = &mut operation => panic!("operation finished before release: {result:?}"),
|
||||
result = blocking => result.unwrap(),
|
||||
}
|
||||
}
|
||||
// 丢弃 SQL future 后真实阻塞工作仍在运行,持有未提交的连接。
|
||||
entered.send(()).unwrap();
|
||||
assert!(!handler_panic, "handler panic");
|
||||
if handler_pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
{
|
||||
let result = wait(&work, deadline, handler);
|
||||
tokio::pin!(result);
|
||||
tokio::select! {
|
||||
result = &mut result => panic!("boundary returned before descendant exit: {result:?}"),
|
||||
result = ready => result.unwrap(),
|
||||
}
|
||||
if expired {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
}
|
||||
assert!(futures_util::poll!(&mut result).is_pending());
|
||||
release.send(()).unwrap();
|
||||
let result = result.await;
|
||||
if expired || late_panic || handler_panic {
|
||||
let message = result.unwrap_err().to_string();
|
||||
if late_panic {
|
||||
assert!(message.contains("late SQLite panic"), "{message}");
|
||||
}
|
||||
if handler_panic {
|
||||
assert!(message.contains("handler panic"), "{message}");
|
||||
}
|
||||
if expired && handler_pending {
|
||||
assert!(message.contains("deadline"), "{message}");
|
||||
}
|
||||
} else {
|
||||
result?;
|
||||
}
|
||||
}
|
||||
assert!(lease.is_none());
|
||||
assert_eq!(
|
||||
Connection::open(&path)?.query_row("SELECT count(*) FROM effects", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
// tracker 在首个边界后仍可跟踪下一项工作;事务回滚完成后才允许重试。
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
wait(
|
||||
&work,
|
||||
Instant::now() + IO_TIMEOUT,
|
||||
work.call(&mut lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute("INSERT INTO effects VALUES(2)", [])?;
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
Connection::open(&path)?
|
||||
.query_row("SELECT sum(value) FROM effects", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
2
|
||||
);
|
||||
drop(lease);
|
||||
work.finish().await?;
|
||||
drop(database);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_cancelled_sql_and_rolls_back_before_next_job() -> Result<()> {
|
||||
scenario(false, false, false, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_success_when_descendant_cleanup_exceeds_deadline() -> Result<()> {
|
||||
scenario(false, true, false, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timeout_drains_and_preserves_late_panic() -> Result<()> {
|
||||
scenario(true, true, true, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handler_panic_still_drains_and_preserves_late_panic() -> Result<()> {
|
||||
scenario(false, false, true, true).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
long cmd integer = app.integer
|
||||
|
||||
long cmd continuous_integer = app.continuousInteger
|
||||
|
||||
long cmd float = app.float
|
||||
|
||||
long cmd continuous_float = app.continuousFloat
|
||||
|
||||
long cmd list = app.list
|
||||
|
||||
long cmd continuous_list = app.continuousList
|
||||
|
||||
long cmd map = app.map
|
||||
|
||||
long cmd continuous_map = app.continuousMap
|
||||
|
||||
long cmd list_read = app.listRead
|
||||
|
||||
long cmd continuous_list_read = app.continuousListRead
|
||||
|
||||
long cmd map_read = app.mapRead
|
||||
|
||||
long cmd continuous_map_read = app.continuousMapRead
|
||||
|
||||
long cmd list_record = app.listRecord
|
||||
|
||||
long cmd continuous_list_record = app.continuousListRecord
|
||||
|
||||
long cmd list_record_read = app.listRecordRead
|
||||
|
||||
long cmd continuous_list_record_read = app.continuousListRecordRead
|
||||
|
||||
long cmd call_read = app.callRead
|
||||
|
||||
long cmd continuous_call_read = app.continuousCallRead
|
||||
|
||||
long cmd record_update = app.recordUpdate
|
||||
|
||||
long cmd continuous_record_update = app.continuousRecordUpdate
|
||||
|
||||
long cmd record_inspect = app.recordInspect
|
||||
|
||||
long cmd continuous_record_inspect = app.continuousRecordInspect
|
||||
|
||||
long cmd map_lookup = app.mapLookup
|
||||
|
||||
long cmd continuous_map_lookup = app.continuousMapLookup
|
||||
|
||||
long cmd map_text_lookup = app.mapTextLookup
|
||||
|
||||
long cmd continuous_map_text_lookup = app.continuousMapTextLookup
|
||||
|
||||
long cmd text_equal = app.textEqual
|
||||
|
||||
long cmd continuous_text_equal = app.continuousTextEqual
|
||||
|
||||
long cmd text_contains = app.textContains
|
||||
|
||||
long cmd continuous_text_contains = app.continuousTextContains
|
||||
|
||||
long cmd bytes_concat = app.bytesConcat
|
||||
|
||||
long cmd continuous_bytes_concat = app.continuousBytesConcat
|
||||
|
||||
long cmd text_concat = app.textConcat
|
||||
|
||||
long cmd continuous_text_concat = app.continuousTextConcat
|
||||
@@ -0,0 +1,410 @@
|
||||
type Sample {
|
||||
elapsed_ns: Int
|
||||
checksum: Int
|
||||
}
|
||||
|
||||
type FloatSample {
|
||||
elapsed_ns: Int
|
||||
checksum: Float
|
||||
}
|
||||
|
||||
type Record {
|
||||
first: Int
|
||||
second: Int
|
||||
third: Int
|
||||
}
|
||||
|
||||
type OwnedRecord {
|
||||
name: Text
|
||||
tags: List<Text>
|
||||
count: Int
|
||||
}
|
||||
|
||||
type Accumulator {
|
||||
values: List<Int>
|
||||
count: Int
|
||||
}
|
||||
|
||||
type Lookup {
|
||||
values: Map<Int, Int>
|
||||
index: Int
|
||||
total: Int
|
||||
}
|
||||
|
||||
type TextLookup {
|
||||
values: Map<Text, Int>
|
||||
total: Int
|
||||
}
|
||||
|
||||
type TextPair {
|
||||
left: Text
|
||||
right: Text
|
||||
}
|
||||
|
||||
rule selected(value: Int?) (out: Int)
|
||||
| value | out |
|
||||
| null | 0 |
|
||||
| other | value |
|
||||
|
||||
loop total(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop byteTotal(values: Bytes) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop floatTotal(values: Bytes) (out: Float)
|
||||
| each value in values | result |
|
||||
| out | sum float.fromInt(value) |
|
||||
|
||||
loop buildList(values: Bytes) (out: List<Int>)
|
||||
| each value in values | result |
|
||||
| out | list value |
|
||||
|
||||
loop buildMap(values: Bytes) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = {}, putValue(value, acc)) |
|
||||
|
||||
loop mapTotal(values: Map<Int, Int>) (out: Int)
|
||||
| each entry in entries(values) | result |
|
||||
| out | sum entry.value |
|
||||
|
||||
loop buildRecords(values: Bytes) (out: List<Record>)
|
||||
| each value in values | result |
|
||||
| out | list Record { first = value, second = 0, third = 0 } |
|
||||
|
||||
loop recordTotal(values: List<Record>) (out: Int)
|
||||
| each row in values | result |
|
||||
| out | sum row.first + row.second + row.third |
|
||||
|
||||
ownedRecord(value: Int) (row: OwnedRecord) {
|
||||
name = "row-value-" + int.toText(value)
|
||||
row = OwnedRecord { name = name, tags = [name], count = value - length(name) - 1 }
|
||||
}
|
||||
|
||||
inspectOwned(row: OwnedRecord) (value: Int) {
|
||||
value = row.count + length(row.name) + length(row.tags)
|
||||
}
|
||||
|
||||
forwardOwned(row: OwnedRecord) (value: Int) {
|
||||
value = inspectOwned(row)
|
||||
}
|
||||
|
||||
loop ownedRecords(values: Bytes) (out: List<OwnedRecord>)
|
||||
| each value in values | result |
|
||||
| out | list ownedRecord(value) |
|
||||
|
||||
loop inspectRecords(values: List<OwnedRecord>) (out: Int)
|
||||
| each row in values | result |
|
||||
| out | sum forwardOwned(row) |
|
||||
|
||||
appendField(value: Int, state: Accumulator) (next: Accumulator) {
|
||||
next = Accumulator { values = append(state.values, value), count = state.count + 1 }
|
||||
}
|
||||
|
||||
appendInspected(value: Int, state: Accumulator) (next: Accumulator) {
|
||||
count = length(state.values) + 1
|
||||
next = Accumulator { values = append(state.values, value), count = count }
|
||||
}
|
||||
|
||||
loop updateRecords(values: Bytes) (out: Accumulator)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = Accumulator { values = [], count = 0 }, appendField(value, acc)) |
|
||||
|
||||
loop inspectUpdates(values: Bytes) (out: Accumulator)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = Accumulator { values = [], count = 0 }, appendInspected(value, acc)) |
|
||||
|
||||
lookup(value: Int, state: Lookup) (next: Lookup) {
|
||||
found = selected(get(state.values, state.index))
|
||||
next = Lookup { values = state.values, index = state.index + 1, total = state.total + found }
|
||||
}
|
||||
|
||||
loop lookupValues(input: Bytes, initial: Lookup) (out: Lookup)
|
||||
| each value in input | result |
|
||||
| out | fold(acc = initial, lookup(value, acc)) |
|
||||
|
||||
loop textEntries(values: List<MapEntry<Int, Int>>) (out: Map<Text, Int>)
|
||||
| each entry in values | result |
|
||||
| out | fold(acc = {}, textEntry(entry, acc)) |
|
||||
|
||||
loop textKeys(values: List<MapEntry<Text, Int>>) (out: List<Text>)
|
||||
| each entry in values | result |
|
||||
| out | list entry.key |
|
||||
|
||||
textLookup(key: Text, state: TextLookup) (next: TextLookup) {
|
||||
found = selected(get(state.values, key))
|
||||
next = TextLookup { values = state.values, total = state.total + found }
|
||||
}
|
||||
|
||||
loop lookupText(keys: List<Text>, initial: TextLookup) (out: TextLookup)
|
||||
| each key in keys | result |
|
||||
| out | fold(acc = initial, textLookup(key, acc)) |
|
||||
|
||||
textPair(value: Int) (pair: TextPair) {
|
||||
left = "compare-value-" + int.toText(value)
|
||||
pair = TextPair { left = left, right = text.lower(text.upper(left)) }
|
||||
}
|
||||
|
||||
rule matchedValue(matched: Bool) (value: Int)
|
||||
| matched | value |
|
||||
| true | 120 |
|
||||
| false | 0 |
|
||||
|
||||
loop textPairs(values: Bytes) (out: List<TextPair>)
|
||||
| each value in values | result |
|
||||
| out | list textPair(value) |
|
||||
|
||||
loop equalPairs(rows: List<TextPair>) (out: Int)
|
||||
| each row in rows | result |
|
||||
| out | sum matchedValue(row.left == row.right) |
|
||||
|
||||
loop containsPairs(rows: List<TextPair>) (out: Int)
|
||||
| each row in rows | result |
|
||||
| out | sum matchedValue(text.contains(row.left, row.right)) |
|
||||
|
||||
loop joinText(chunks: List<Text>) (out: Text)
|
||||
| each value in chunks | result |
|
||||
| out | fold(acc = "", appendText(value, acc)) |
|
||||
|
||||
loop byteChunks(chunks: List<Text>) (out: List<Bytes>)
|
||||
| each value in chunks | result |
|
||||
| out | list dever.bytes.fromText(value) |
|
||||
|
||||
loop joinBytes(chunks: List<Bytes>) (out: Bytes)
|
||||
| each value in chunks | result |
|
||||
| out | fold(acc = dever.bytes.fromText(""), appendBytes(value, acc)) |
|
||||
|
||||
flow integer(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | byteTotal(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousInteger(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list integer(ticks) |
|
||||
|
||||
flow float(ticks: Text) (sample: FloatSample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | floatTotal(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | FloatSample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousFloat(ticks: Text) (samples: List<FloatSample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list float(ticks) |
|
||||
|
||||
flow list(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildList(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = total(values) } |
|
||||
|
||||
loop continuousList(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list list(ticks) |
|
||||
|
||||
flow map(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildMap(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = mapTotal(values) } |
|
||||
|
||||
loop continuousMap(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list map(ticks) |
|
||||
|
||||
flow listRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildList(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | total(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousListRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRead(ticks) |
|
||||
|
||||
flow mapRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildMap(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | mapTotal(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousMapRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapRead(ticks) |
|
||||
|
||||
flow listRecord(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildRecords(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = recordTotal(values) } |
|
||||
|
||||
loop continuousListRecord(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRecord(ticks) |
|
||||
|
||||
flow listRecordRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildRecords(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | recordTotal(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousListRecordRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRecordRead(ticks) |
|
||||
|
||||
flow callRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| rows | loop | ownedRecords(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | inspectRecords(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(rows) } |
|
||||
|
||||
loop continuousCallRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list callRead(ticks) |
|
||||
|
||||
flow recordUpdate(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | updateRecords(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample {
|
||||
elapsed_ns = end - begin
|
||||
checksum = total(state.values) + state.count - length(state.values)
|
||||
} |
|
||||
|
||||
loop continuousRecordUpdate(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list recordUpdate(ticks) |
|
||||
|
||||
flow recordInspect(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | inspectUpdates(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample {
|
||||
elapsed_ns = end - begin
|
||||
checksum = total(state.values) + state.count - length(state.values)
|
||||
} |
|
||||
|
||||
loop continuousRecordInspect(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list recordInspect(ticks) |
|
||||
|
||||
flow mapLookup(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| values | loop | buildMap(input) |
|
||||
| initial | calc | Lookup { values = values, index = 0, total = 0 } |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | lookupValues(input, initial) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = state.total } |
|
||||
|
||||
loop continuousMapLookup(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapLookup(ticks) |
|
||||
|
||||
flow mapTextLookup(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| values | loop | textEntries(entries(buildMap(input))) |
|
||||
| keys | loop | textKeys(entries(values)) |
|
||||
| initial | calc | TextLookup { values = values, total = 0 } |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | lookupText(keys, initial) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = state.total + length(keys) - length(input) } |
|
||||
|
||||
loop continuousMapTextLookup(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapTextLookup(ticks) |
|
||||
|
||||
flow textEqual(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| rows | loop | textPairs(input) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | equalPairs(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(input) } |
|
||||
|
||||
loop continuousTextEqual(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textEqual(ticks) |
|
||||
|
||||
flow textContains(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| rows | loop | textPairs(input) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | containsPairs(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(input) } |
|
||||
|
||||
loop continuousTextContains(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textContains(ticks) |
|
||||
|
||||
flow bytesConcat(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| chunks | loop | byteChunks(text.split(ticks, "")) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | joinBytes(chunks) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = byteTotal(value) } |
|
||||
|
||||
loop continuousBytesConcat(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list bytesConcat(ticks) |
|
||||
|
||||
flow textConcat(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| chunks | calc | text.split(ticks, ",") |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | joinText(chunks) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = byteTotal(dever.bytes.fromText(value)) } |
|
||||
|
||||
loop continuousTextConcat(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textConcat(ticks) |
|
||||
|
||||
putValue(value: Int, state: Map<Int, Int>) (out: Map<Int, Int>) {
|
||||
out = put(state, length(state), value)
|
||||
}
|
||||
|
||||
textEntry(entry: MapEntry<Int, Int>, state: Map<Text, Int>) (out: Map<Text, Int>) {
|
||||
out = put(state, "lookup-key-" + int.toText(entry.key), entry.value)
|
||||
}
|
||||
|
||||
appendText(value: Text, state: Text) (out: Text) {
|
||||
out = state + value
|
||||
}
|
||||
|
||||
appendBytes(value: Bytes, state: Bytes) (out: Bytes) {
|
||||
out = dever.bytes.concat(state, value)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
cmd batch = app.batch
|
||||
|
||||
cmd count = app.count
|
||||
@@ -0,0 +1,20 @@
|
||||
flow change(number: Int, title: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| created | data | data.create({ number = number, title = title, amount = number }) |
|
||||
| found | data | data.get(created.id) |
|
||||
| updated | data | data.update(found.id, { amount = found.amount + 1 }) |
|
||||
| out | calc | updated.amount |
|
||||
|
||||
loop changes(numbers: List<Int>, title: Text) (out: Int)
|
||||
| each number in numbers | result |
|
||||
| out | sum change(number, title) |
|
||||
|
||||
flow batch(numbers: List<Int>, title: Text) (checksum: Int, count: Int)
|
||||
| step | kind | do |
|
||||
| removed | data | data.delete({ where = number >= 0 }) |
|
||||
| checksum | loop | changes(numbers, title) |
|
||||
| count | data | data.count() |
|
||||
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
@@ -0,0 +1,5 @@
|
||||
module model-peer
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/mattn/go-sqlite3 v1.14.47
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
|
||||
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
@@ -0,0 +1,6 @@
|
||||
type Article {
|
||||
number: Int unique
|
||||
title: Text(1, 120)
|
||||
amount: Int default 0
|
||||
note: Text? raw
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
change(number: Int, title: Text) (out: Int) {
|
||||
created = model.create({ number = number, title = title, amount = number })
|
||||
found = model.get(created.id)
|
||||
updated = model.update(found.id, { amount = found.amount + 1 })
|
||||
out = updated.amount
|
||||
}
|
||||
|
||||
batch(numbers: List<Int>, title: Text) (checksum: Int, count: Int) {
|
||||
removed = model.delete({ where = number >= 0 })
|
||||
checksum = sum(each(change, numbers, title))
|
||||
count = model.count()
|
||||
}
|
||||
|
||||
count() (out: Int) {
|
||||
out = model.count()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// 独立 database/sql CMD 对端;事务出错回滚,成功编码后提交。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
sqlite3 "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Input struct {
|
||||
Numbers []int64 "json:\"numbers\""
|
||||
Title string "json:\"title\""
|
||||
}
|
||||
type Output struct {
|
||||
Checksum int64 "json:\"checksum\""
|
||||
Count int64 "json:\"count\""
|
||||
}
|
||||
type Article struct {
|
||||
ID, CreatedAt, Number int64
|
||||
Title string
|
||||
Amount int64
|
||||
Note sql.NullString
|
||||
}
|
||||
|
||||
func article(row *sql.Row) (value Article, err error) {
|
||||
err = row.Scan(&value.ID, &value.CreatedAt, &value.Number, &value.Title, &value.Amount, &value.Note)
|
||||
return
|
||||
}
|
||||
|
||||
func run() error {
|
||||
if os.Args[1] == "--sqlite-version" {
|
||||
version, _, _ := sqlite3.Version()
|
||||
fmt.Println(version)
|
||||
return nil
|
||||
}
|
||||
var input Input
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(os.Args[2]))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("unexpected trailing JSON: %v", err)
|
||||
}
|
||||
if input.Numbers == nil {
|
||||
return fmt.Errorf("numbers is required")
|
||||
}
|
||||
input.Title = strings.TrimSpace(input.Title)
|
||||
if n := utf8.RuneCountInString(input.Title); n < 1 || n > 120 {
|
||||
return fmt.Errorf("title range")
|
||||
}
|
||||
sql.Register("model-sqlite", &sqlite3.SQLiteDriver{ConnectHook: func(conn *sqlite3.SQLiteConn) error {
|
||||
return conn.RegisterFunc("_dever_length", utf8.RuneCountInString, true)
|
||||
}})
|
||||
db, err := sql.Open("model-sqlite", "file:"+os.Args[1]+"?mode=rw&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMAL&_busy_timeout=30000&_txlock=immediate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec("DELETE FROM benchmark_article WHERE number >= ?", 0); err != nil {
|
||||
return err
|
||||
}
|
||||
create, err := tx.Prepare("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?,?,?,?,NULL) RETURNING id,created_at,number,title,amount,note")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer create.Close()
|
||||
read, err := tx.Prepare("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer read.Close()
|
||||
update, err := tx.Prepare("UPDATE benchmark_article SET amount = ? WHERE id = ? RETURNING id,created_at,number,title,amount,note")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer update.Close()
|
||||
var out Output
|
||||
for _, number := range input.Numbers {
|
||||
created, err := article(create.QueryRow(time.Now().UnixMilli(), number, input.Title, number))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found, err := article(read.QueryRow(created.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found.Amount == math.MaxInt64 {
|
||||
return fmt.Errorf("amount overflow")
|
||||
}
|
||||
updated, err := article(update.QueryRow(found.Amount+1, found.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if (updated.Amount > 0 && out.Checksum > math.MaxInt64-updated.Amount) || (updated.Amount < 0 && out.Checksum < math.MinInt64-updated.Amount) {
|
||||
return fmt.Errorf("checksum overflow")
|
||||
}
|
||||
out.Checksum += updated.Amount
|
||||
}
|
||||
if err = tx.QueryRow("SELECT COUNT(*) FROM benchmark_article").Scan(&out.Count); err != nil {
|
||||
return err
|
||||
}
|
||||
encoded, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Println(string(encoded))
|
||||
return err
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 独立同步 SQLite CMD 对端;不链接 Dever,不模拟其异步任务调度。
|
||||
use rusqlite::{Connection, OpenFlags, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
error::Error,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input {
|
||||
numbers: Vec<i64>,
|
||||
title: String,
|
||||
}
|
||||
|
||||
struct Article {
|
||||
id: i64,
|
||||
_created_at: i64,
|
||||
_number: i64,
|
||||
_title: String,
|
||||
amount: i64,
|
||||
_note: Option<String>,
|
||||
}
|
||||
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
_created_at: row.get(1)?,
|
||||
_number: row.get(2)?,
|
||||
_title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
_note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Output {
|
||||
checksum: i64,
|
||||
count: i64,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
let mut input: Input = serde_json::from_str(&args[2])?;
|
||||
input.title = input.title.trim().into();
|
||||
if !(1..=120).contains(&input.title.chars().count()) {
|
||||
return Err("title range".into());
|
||||
}
|
||||
let mut connection = Connection::open_with_flags(&args[1], OpenFlags::SQLITE_OPEN_READ_WRITE)?;
|
||||
connection.create_scalar_function(
|
||||
"_dever_length",
|
||||
1,
|
||||
rusqlite::functions::FunctionFlags::SQLITE_UTF8
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_INNOCUOUS,
|
||||
|ctx| {
|
||||
Ok(ctx
|
||||
.get_raw(0)
|
||||
.as_str()
|
||||
.map_err(|error| rusqlite::Error::UserFunctionError(Box::new(error)))?
|
||||
.chars()
|
||||
.count() as i64)
|
||||
},
|
||||
)?;
|
||||
connection.busy_timeout(Duration::from_secs(30))?;
|
||||
connection.execute_batch(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;",
|
||||
)?;
|
||||
let transaction =
|
||||
connection.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
transaction
|
||||
.prepare_cached("DELETE FROM benchmark_article WHERE number >= ?1")?
|
||||
.execute([0])?;
|
||||
let mut checksum = 0i64;
|
||||
for number in input.numbers {
|
||||
let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?;
|
||||
let created = transaction.prepare_cached("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?1,?2,?3,?4,NULL) RETURNING id,created_at,number,title,amount,note")?
|
||||
.query_row(params![now,number,input.title,number], article)?;
|
||||
let found = transaction.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?1")?
|
||||
.query_row([created.id], article)?;
|
||||
let updated = transaction.prepare_cached("UPDATE benchmark_article SET amount = ?2 WHERE id = ?1 RETURNING id,created_at,number,title,amount,note")?
|
||||
.query_row(params![found.id,found.amount.checked_add(1).ok_or("amount overflow")?], article)?;
|
||||
checksum = checksum
|
||||
.checked_add(updated.amount)
|
||||
.ok_or("checksum overflow")?;
|
||||
}
|
||||
let count = transaction
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?;
|
||||
let encoded = serde_json::to_string(&Output { checksum, count })?;
|
||||
transaction.commit()?;
|
||||
println!("{encoded}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
flow page(page: Int, size: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(order = [number.asc, id.asc], page = page, size = size) |
|
||||
|
||||
flow cursor(after: data.Article?, size: Int) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(order = [number.asc, id.asc], after = after, size = size) |
|
||||
@@ -0,0 +1,338 @@
|
||||
//! 独立分页、游标和批量关系参考;不链接 Dever,复用同一 SQLite 资源责任。
|
||||
#[cfg(feature = "read-boundary")]
|
||||
mod boundary;
|
||||
mod sqlite_resource;
|
||||
#[cfg(feature = "read-boundary")]
|
||||
use boundary::{decode, encode};
|
||||
use deadpool_sqlite::rusqlite::{self, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(not(feature = "read-boundary"))]
|
||||
use serde_json::{from_str as decode, to_string as encode};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
const TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const MAX_PAGE: i64 = 1024;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Moment(i64);
|
||||
impl Serialize for Moment {
|
||||
fn serialize<S: serde::Serializer>(&self, output: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
let value = chrono::DateTime::from_timestamp_millis(self.0)
|
||||
.ok_or_else(|| serde::ser::Error::custom("timestamp out of range"))?;
|
||||
let pattern = if self.0 % 1000 == 0 {
|
||||
"%Y-%m-%dT%H:%M:%SZ"
|
||||
} else {
|
||||
"%Y-%m-%dT%H:%M:%S%.3fZ"
|
||||
};
|
||||
output.collect_str(&value.format(pattern))
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for Moment {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(input: D) -> std::result::Result<Self, D::Error> {
|
||||
let value = String::deserialize(input)?;
|
||||
let parsed =
|
||||
chrono::DateTime::parse_from_rfc3339(&value).map_err(serde::de::Error::custom)?;
|
||||
#[cfg(feature = "read-boundary")]
|
||||
boundary::moment(&value, parsed).map_err(serde::de::Error::custom)?;
|
||||
Ok(Moment(parsed.timestamp_millis()))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Article {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
number: i64,
|
||||
title: String,
|
||||
#[cfg_attr(feature = "read-boundary", serde(default))]
|
||||
amount: i64,
|
||||
note: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PageInput {
|
||||
page: i64,
|
||||
size: i64,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CursorInput {
|
||||
#[cfg_attr(
|
||||
feature = "read-boundary",
|
||||
serde(default, deserialize_with = "boundary::after")
|
||||
)]
|
||||
after: Option<Article>,
|
||||
size: i64,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Page<T> {
|
||||
items: Vec<T>,
|
||||
page: i64,
|
||||
size: i64,
|
||||
total: i64,
|
||||
pages: i64,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Cursor {
|
||||
items: Vec<Article>,
|
||||
next: Option<Article>,
|
||||
has_more: bool,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Post {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
title: String,
|
||||
author_id: i64,
|
||||
note: Option<String>,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Author {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
name: String,
|
||||
note: Option<String>,
|
||||
posts: Vec<Post>,
|
||||
}
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
created_at: Moment(row.get(1)?),
|
||||
number: row.get(2)?,
|
||||
title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
fn page_offset(input: &PageInput) -> Result<i64> {
|
||||
if input.page < 1 || !(1..=MAX_PAGE).contains(&input.size) {
|
||||
return Err("invalid page or size".into());
|
||||
}
|
||||
input
|
||||
.page
|
||||
.checked_sub(1)
|
||||
.and_then(|page| page.checked_mul(input.size))
|
||||
.ok_or_else(|| "page offset overflow".into())
|
||||
}
|
||||
async fn page(work: &Work, lease: &mut Option<Lease>, input: PageInput) -> Result<Page<Article>> {
|
||||
let offset = page_offset(&input)?;
|
||||
let total: i64 = work
|
||||
.call(lease, TIMEOUT, |db| {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let size = input.size;
|
||||
let items = work.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article ORDER BY number ASC,id ASC LIMIT ?1 OFFSET ?2")?
|
||||
.query_map(params![size, offset], article)?.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}).await?;
|
||||
Ok(Page {
|
||||
items,
|
||||
page: input.page,
|
||||
size,
|
||||
total,
|
||||
pages: total / size + i64::from(total % size != 0),
|
||||
})
|
||||
}
|
||||
async fn cursor(work: &Work, lease: &mut Option<Lease>, input: CursorInput) -> Result<Cursor> {
|
||||
if !(1..=MAX_PAGE).contains(&input.size) {
|
||||
return Err("invalid cursor size".into());
|
||||
}
|
||||
if input.after.as_ref().is_some_and(|row| row.id <= 0) {
|
||||
return Err("invalid cursor record".into());
|
||||
}
|
||||
let size = input.size;
|
||||
let mut items = work.call(lease, TIMEOUT, move |db| {
|
||||
let rows = match input.after {
|
||||
Some(after) => db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE (number > ?1 OR (number = ?1 AND id > ?2)) ORDER BY number ASC,id ASC LIMIT ?3")?
|
||||
.query_map(params![after.number, after.id, size + 1], article)?.collect::<rusqlite::Result<Vec<_>>>()?,
|
||||
None => db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article ORDER BY number ASC,id ASC LIMIT ?1")?
|
||||
.query_map([size + 1], article)?.collect::<rusqlite::Result<Vec<_>>>()?,
|
||||
};
|
||||
Ok(rows)
|
||||
}).await?;
|
||||
let has_more = items.len() > size as usize;
|
||||
if has_more {
|
||||
items.pop();
|
||||
}
|
||||
let next = if has_more {
|
||||
items.last().cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Cursor {
|
||||
items,
|
||||
next,
|
||||
has_more,
|
||||
})
|
||||
}
|
||||
async fn relations(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
input: PageInput,
|
||||
) -> Result<Page<Author>> {
|
||||
let offset = page_offset(&input)?;
|
||||
let total: i64 = work
|
||||
.call(lease, TIMEOUT, |db| {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_read_author")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let size = input.size;
|
||||
let mut items = work.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db.prepare_cached("SELECT id,created_at,name,note FROM benchmark_read_author ORDER BY id ASC LIMIT ?1 OFFSET ?2")?
|
||||
.query_map(params![size, offset], |row| Ok(Author { id: row.get(0)?, created_at: Moment(row.get(1)?),
|
||||
name: row.get(2)?, note: row.get(3)?, posts: Vec::new() }))?.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}).await?;
|
||||
let mut ids: Vec<_> = items.iter().map(|row| row.id).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut related: HashMap<i64, Vec<Post>> = HashMap::with_capacity(ids.len());
|
||||
if !ids.is_empty() {
|
||||
let placeholders = (1..=ids.len())
|
||||
.map(|i| format!("?{i}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let sql = format!(
|
||||
"SELECT id,created_at,title,author_id,note FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY author_id ORDER BY id DESC) AS __dever_rank FROM benchmark_read_post WHERE author_id IN ({placeholders})) AS related WHERE __dever_rank <= {} ORDER BY id DESC",
|
||||
MAX_PAGE + 1
|
||||
);
|
||||
let values = work
|
||||
.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db
|
||||
.prepare_cached(&sql)?
|
||||
.query_map(rusqlite::params_from_iter(ids), |row| {
|
||||
Ok(Post {
|
||||
id: row.get(0)?,
|
||||
created_at: Moment(row.get(1)?),
|
||||
title: row.get(2)?,
|
||||
author_id: row.get(3)?,
|
||||
note: row.get(4)?,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
})
|
||||
.await?;
|
||||
for value in values {
|
||||
let group = related.entry(value.author_id).or_default();
|
||||
group.push(value);
|
||||
if group.len() > MAX_PAGE as usize {
|
||||
return Err("relation exceeds max_page_size".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
for row in &mut items {
|
||||
row.posts = related.remove(&row.id).unwrap_or_default();
|
||||
}
|
||||
Ok(Page {
|
||||
items,
|
||||
page: input.page,
|
||||
size,
|
||||
total,
|
||||
pages: total / size + i64::from(total % size != 0),
|
||||
})
|
||||
}
|
||||
async fn execute(path: &str, operation: &str, input: &str) -> Result<String> {
|
||||
enum Input {
|
||||
Page(PageInput),
|
||||
Cursor(CursorInput),
|
||||
Relations(PageInput),
|
||||
}
|
||||
let input = match operation {
|
||||
"page" => Input::Page(decode(input)?),
|
||||
"cursor" => Input::Cursor(decode(input)?),
|
||||
"relations" => Input::Relations(decode(input)?),
|
||||
_ => return Err("unknown read operation".into()),
|
||||
};
|
||||
let pool = pool(path, 1).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = async {
|
||||
#[cfg(feature = "read-boundary")]
|
||||
boundary::verify(&work, &mut lease).await?;
|
||||
Ok(match input {
|
||||
Input::Page(input) => encode(&page(&work, &mut lease, input).await?)?,
|
||||
Input::Cursor(input) => encode(&cursor(&work, &mut lease, input).await?)?,
|
||||
Input::Relations(input) => encode(&relations(&work, &mut lease, input).await?)?,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(pool);
|
||||
match (result, cleanup) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
|
||||
(Err(primary), Err(cleanup)) => {
|
||||
eprintln!("cleanup: {cleanup}");
|
||||
Err(primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn plans(path: &str) -> Result<()> {
|
||||
let db =
|
||||
rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
|
||||
let prefix = "SELECT id,created_at,number,title,amount,note FROM benchmark_article";
|
||||
let cases = [
|
||||
(
|
||||
"flag_or",
|
||||
format!(
|
||||
"{prefix} WHERE (?1 = 0 OR (number > ?2 OR (number = ?2 AND id > ?3))) ORDER BY number ASC,id ASC LIMIT ?4"
|
||||
),
|
||||
vec![1i64, 196605, 65535, 2],
|
||||
),
|
||||
(
|
||||
"lexicographic",
|
||||
format!(
|
||||
"{prefix} WHERE (number > ?1 OR (number = ?1 AND id > ?2)) ORDER BY number ASC,id ASC LIMIT ?3"
|
||||
),
|
||||
vec![196605, 65535, 2],
|
||||
),
|
||||
(
|
||||
"tuple",
|
||||
format!("{prefix} WHERE (number,id) > (?1,?2) ORDER BY number ASC,id ASC LIMIT ?3"),
|
||||
vec![196605, 65535, 2],
|
||||
),
|
||||
];
|
||||
let mut report = Vec::new();
|
||||
for (case, sql, parameters) in cases {
|
||||
let steps = db
|
||||
.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))?
|
||||
.query_map(rusqlite::params_from_iter(parameters), |row| {
|
||||
row.get::<_, String>(3)
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
report.push(serde_json::json!({"case":case,"sql":sql,"plan":steps}));
|
||||
}
|
||||
println!("{}", serde_json::to_string(&report)?);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
if args[1] == "--plans" {
|
||||
return plans(&args[2]);
|
||||
}
|
||||
#[cfg(feature = "read-boundary")]
|
||||
if args[1] == "--self-test" {
|
||||
return boundary::self_test();
|
||||
}
|
||||
#[cfg(feature = "read-boundary")]
|
||||
let (path, operation, input) = boundary::command(&args)?;
|
||||
#[cfg(not(feature = "read-boundary"))]
|
||||
let (path, operation, input) = (&args[1], args[2].as_str(), args[3].as_str());
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
println!("{}", runtime.block_on(execute(&path, operation, input))?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! 独立参考的真实入口责任:配置、Model 结构与具名 JSON 的单次编解码预算。
|
||||
use super::*;
|
||||
use rusqlite::OptionalExtension;
|
||||
use serde::de::{MapAccess, Visitor, value::MapAccessDeserializer};
|
||||
use serde_json::ser::{CompactFormatter, Formatter};
|
||||
use std::{
|
||||
fmt,
|
||||
io::{self, Write},
|
||||
marker::PhantomData,
|
||||
path::{Component, Path},
|
||||
};
|
||||
include!("schemas.rs");
|
||||
const MAX_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_VALUES: usize = 65536;
|
||||
const MAX_DEPTH: usize = 64;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Setting {
|
||||
database: Databases,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Databases {
|
||||
default: Sqlite,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Sqlite {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
path: String,
|
||||
max_connections: usize,
|
||||
max_page_size: usize,
|
||||
}
|
||||
pub(super) fn command(args: &[String]) -> Result<(String, &str, &str)> {
|
||||
if args.len() != 5 || args[1] != "--config" {
|
||||
return Err("expected --config FILE CMD JSON".into());
|
||||
}
|
||||
let path = Path::new(&args[2]).canonicalize()?;
|
||||
let setting: Setting = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
|
||||
let setting = setting.database.default;
|
||||
if setting.kind != "sqlite"
|
||||
|| setting.max_connections != 1
|
||||
|| setting.max_page_size != MAX_PAGE as usize
|
||||
{
|
||||
return Err("this reference requires SQLite, one connection and max_page_size=1024".into());
|
||||
}
|
||||
let relative = Path::new(&setting.path);
|
||||
if relative.as_os_str().is_empty()
|
||||
|| relative
|
||||
.components()
|
||||
.any(|c| !matches!(c, Component::Normal(_)))
|
||||
{
|
||||
return Err("database path must be relative to the application directory".into());
|
||||
}
|
||||
let database = path
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.ok_or("missing project root")?
|
||||
.join(relative);
|
||||
let operation = match args[3].as_str() {
|
||||
"benchmark.article.page" => "page",
|
||||
"benchmark.article.cursor" => "cursor",
|
||||
"benchmark.read.page" => "relations",
|
||||
_ => return Err("unknown Model command".into()),
|
||||
};
|
||||
Ok((
|
||||
database
|
||||
.to_str()
|
||||
.ok_or("database path is not UTF-8")?
|
||||
.into(),
|
||||
operation,
|
||||
&args[4],
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn verify(work: &Work, lease: &mut Option<Lease>) -> Result<()> {
|
||||
work.call(lease, TIMEOUT, |db| {
|
||||
for &(table, expected) in SCHEMAS {
|
||||
let recorded: Option<(String,String)> = db.query_row(
|
||||
"SELECT definition,catalog FROM _dever_history WHERE name=?1", [table],
|
||||
|row| Ok((row.get(0)?,row.get(1)?))).optional()?;
|
||||
let (definition, catalog) = recorded.ok_or("Model schema is missing")?;
|
||||
let mut query = db.prepare("SELECT type,name,sql FROM sqlite_schema WHERE tbl_name=?1 AND sql IS NOT NULL ORDER BY type,name")?;
|
||||
let actual = query.query_map([table], |row| Ok((row.get::<_,String>(0)?,row.get::<_,String>(1)?,row.get::<_,String>(2)?)))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
if definition != expected || catalog != serde_json::to_string(&actual)? {
|
||||
return Err("Model schema is outdated or changed".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}).await
|
||||
}
|
||||
|
||||
fn object<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>(
|
||||
input: D,
|
||||
) -> std::result::Result<T, D::Error> {
|
||||
struct Named<T>(PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> Visitor<'de> for Named<T> {
|
||||
type Value = T;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a named JSON object")
|
||||
}
|
||||
fn visit_map<M: MapAccess<'de>>(self, map: M) -> std::result::Result<T, M::Error> {
|
||||
T::deserialize(MapAccessDeserializer::new(map))
|
||||
}
|
||||
}
|
||||
input.deserialize_map(Named(PhantomData))
|
||||
}
|
||||
pub(super) fn decode<T: serde::de::DeserializeOwned>(input: &str) -> Result<T> {
|
||||
// 本夹具的输入类型最多三层、十一个值;只须在具名解码边界检查字节数。
|
||||
if input.len() > MAX_BYTES {
|
||||
return Err("JSON exceeds 16 MiB".into());
|
||||
}
|
||||
let mut decoder = serde_json::Deserializer::from_str(input);
|
||||
let value = object(&mut decoder)?;
|
||||
decoder.end()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub(super) fn after<'de, D: serde::Deserializer<'de>>(
|
||||
input: D,
|
||||
) -> std::result::Result<Option<Article>, D::Error> {
|
||||
struct OptionalRecord;
|
||||
impl<'de> Visitor<'de> for OptionalRecord {
|
||||
type Value = Option<Article>;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("null or a Model object")
|
||||
}
|
||||
fn visit_none<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_some<D: serde::Deserializer<'de>>(
|
||||
self,
|
||||
input: D,
|
||||
) -> std::result::Result<Self::Value, D::Error> {
|
||||
object(input).map(Some)
|
||||
}
|
||||
}
|
||||
input.deserialize_option(OptionalRecord)
|
||||
}
|
||||
pub(super) fn moment(text: &str, value: chrono::DateTime<chrono::FixedOffset>) -> Result<()> {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let fraction = text.get(19..).and_then(|part| part.strip_prefix('.'));
|
||||
if fraction.is_some_and(|part| part.bytes().take_while(u8::is_ascii_digit).count() > 3)
|
||||
|| value.nanosecond() >= 1_000_000_000
|
||||
|| !value.nanosecond().is_multiple_of(1_000_000)
|
||||
|| !(0..=9999).contains(&value.with_timezone(&chrono::Utc).year())
|
||||
{
|
||||
return Err(
|
||||
"DateTime requires four-digit UTC year, milliseconds and no leap seconds".into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Output(Vec<u8>);
|
||||
impl Write for Output {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if bytes.len() > MAX_BYTES - self.0.len() {
|
||||
return Err(io::Error::other("JSON exceeds 16 MiB"));
|
||||
}
|
||||
self.0.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct Limit {
|
||||
depth: usize,
|
||||
values: usize,
|
||||
}
|
||||
impl Limit {
|
||||
fn open(&mut self) -> io::Result<()> {
|
||||
if self.depth == MAX_DEPTH {
|
||||
return Err(io::Error::other("JSON depth limit"));
|
||||
}
|
||||
self.depth += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn value(&mut self) -> io::Result<()> {
|
||||
if self.values == MAX_VALUES {
|
||||
return Err(io::Error::other("JSON value limit"));
|
||||
}
|
||||
self.values += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Formatter for Limit {
|
||||
fn begin_array<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.open()?;
|
||||
CompactFormatter.begin_array(out)
|
||||
}
|
||||
fn end_array<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.depth -= 1;
|
||||
CompactFormatter.end_array(out)
|
||||
}
|
||||
fn begin_array_value<W: Write + ?Sized>(&mut self, out: &mut W, first: bool) -> io::Result<()> {
|
||||
self.value()?;
|
||||
CompactFormatter.begin_array_value(out, first)
|
||||
}
|
||||
fn begin_object<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.open()?;
|
||||
CompactFormatter.begin_object(out)
|
||||
}
|
||||
fn end_object<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.depth -= 1;
|
||||
CompactFormatter.end_object(out)
|
||||
}
|
||||
fn begin_object_value<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.value()?;
|
||||
CompactFormatter.begin_object_value(out)
|
||||
}
|
||||
}
|
||||
pub(super) fn encode<T: Serialize + ?Sized>(data: &T) -> Result<String> {
|
||||
#[derive(Serialize)]
|
||||
struct Response<'a, T: ?Sized> {
|
||||
code: u16,
|
||||
message: &'static str,
|
||||
data: &'a T,
|
||||
}
|
||||
let mut out = Output(Vec::with_capacity(128));
|
||||
Response {
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data,
|
||||
}
|
||||
.serialize(&mut serde_json::Serializer::with_formatter(
|
||||
&mut out,
|
||||
Limit {
|
||||
depth: 0,
|
||||
values: 1,
|
||||
},
|
||||
))?;
|
||||
Ok(String::from_utf8(out.0)?)
|
||||
}
|
||||
pub(super) fn self_test() -> Result<()> {
|
||||
assert!(encode(&vec![0u8; MAX_VALUES - 4]).is_ok());
|
||||
assert!(encode(&vec![0u8; MAX_VALUES - 3]).is_err());
|
||||
let mut value = serde_json::Value::Null;
|
||||
for _ in 0..MAX_DEPTH - 1 {
|
||||
value = serde_json::json!([value]);
|
||||
}
|
||||
assert!(encode(&value).is_ok());
|
||||
assert!(encode(&serde_json::json!([value])).is_err());
|
||||
let overhead = encode("")?.len();
|
||||
assert_eq!(encode(&"x".repeat(MAX_BYTES - overhead))?.len(), MAX_BYTES);
|
||||
assert!(encode(&"x".repeat(MAX_BYTES - overhead + 1)).is_err());
|
||||
println!("byte/value/depth boundaries passed");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
type PostRow { id: data.post.id, created_at: DateTime, title: Text, author_id: data.author.id, note: Text? }
|
||||
type AuthorRow { id: data.author.id, created_at: DateTime, name: Text, note: Text?, posts: List<PostRow> }
|
||||
type Page { items: List<AuthorRow>, page: Int, size: Int, total: Int, pages: Int }
|
||||
type Error { error NotLoaded }
|
||||
|
||||
loop posts(rows: List<data.post.Post>) (out: List<PostRow>)
|
||||
| each row in rows | result |
|
||||
| out | list PostRow { id = row.id, created_at = row.created_at, title = row.title, author_id = row.author_id, note = row.note } |
|
||||
|
||||
rule loaded(value: Related<List<data.post.Post>>) (out: List<PostRow>)
|
||||
| value | out |
|
||||
| Loaded(rows) | posts(rows) |
|
||||
| Unloaded | fail(Error.NotLoaded) |
|
||||
|
||||
loop authors(rows: List<data.author.Author>) (out: List<AuthorRow>)
|
||||
| each row in rows | result |
|
||||
| out | list AuthorRow { id = row.id, created_at = row.created_at, name = row.name, note = row.note, posts = loaded(row.posts) } |
|
||||
|
||||
flow page(page: Int, size: Int) (out: Page)
|
||||
| step | kind | do |
|
||||
| found | data | data.author.page(order = id.asc, with = [posts], page = page, size = size) |
|
||||
| items | loop | authors(found.items) |
|
||||
| out | calc | Page { items = items, page = found.page, size = found.size, total = found.total, pages = found.pages } |
|
||||
@@ -0,0 +1,239 @@
|
||||
//! 独立 Tokio/deadpool SQLite 对端;每条 SQL 有期限,取消后排空阻塞工作。
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::rusqlite::{self, Connection, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input {
|
||||
numbers: Vec<i64>,
|
||||
title: String,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Output {
|
||||
checksum: i64,
|
||||
count: i64,
|
||||
}
|
||||
struct Article {
|
||||
id: i64,
|
||||
_created_at: i64,
|
||||
_number: i64,
|
||||
_title: String,
|
||||
amount: i64,
|
||||
_note: Option<String>,
|
||||
}
|
||||
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
// 和 Model 一样把完整记录交付给调用方,字段由持有记录的一方释放。
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
_created_at: row.get(1)?,
|
||||
_number: row.get(2)?,
|
||||
_title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
_note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn batch(work: &Work, lease: &mut Option<Lease>, input: Input) -> Result<String> {
|
||||
let timeout = Duration::from_secs(30);
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection
|
||||
.prepare_cached("DELETE FROM benchmark_article WHERE number >= ?1")?
|
||||
.execute([0])?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let mut checksum = 0i64;
|
||||
for number in input.numbers {
|
||||
let title = input.title.clone();
|
||||
let created = work.call(lease, timeout, move |connection| {
|
||||
let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?;
|
||||
let mut statement = connection.prepare_cached("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?1,?2,?3,?4,NULL) RETURNING id,created_at,number,title,amount,note")?;
|
||||
let mut rows = statement.query(params![now, number, title, number])?;
|
||||
let value = article(rows.next()?.ok_or("missing inserted row")?)?;
|
||||
rows.next()?;
|
||||
Ok(value)
|
||||
}).await?;
|
||||
let found = work.call(lease, timeout, move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?1")?
|
||||
.query_row([created.id], article)?)
|
||||
}).await?;
|
||||
let amount = found.amount.checked_add(1).ok_or("amount overflow")?;
|
||||
let updated = work.call(lease, timeout, move |connection| {
|
||||
let mut statement = connection.prepare_cached("UPDATE benchmark_article SET amount = ?2 WHERE id = ?1 RETURNING id,created_at,number,title,amount,note")?;
|
||||
let mut rows = statement.query(params![found.id, amount])?;
|
||||
let value = article(rows.next()?.ok_or("missing updated row")?)?;
|
||||
rows.next()?;
|
||||
Ok(value)
|
||||
}).await?;
|
||||
checksum = checksum
|
||||
.checked_add(updated.amount)
|
||||
.ok_or("checksum overflow")?;
|
||||
}
|
||||
let count = work
|
||||
.call(lease, timeout, |connection| {
|
||||
Ok(connection
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let encoded = serde_json::to_string(&Output { checksum, count })?;
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
async fn execute(path: &str, input: Input) -> Result<String> {
|
||||
let pool = pool(path, 1).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = batch(&work, &mut lease, input).await;
|
||||
if result.is_err() && lease.is_some() {
|
||||
let rollback = work
|
||||
.call(&mut lease, Duration::from_secs(30), |connection| {
|
||||
if !connection.is_autocommit() {
|
||||
connection.execute_batch("ROLLBACK")?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = rollback {
|
||||
eprintln!("rollback: {error}");
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(pool);
|
||||
if let Err(error) = cleanup {
|
||||
if result.is_ok() {
|
||||
return Err(error);
|
||||
}
|
||||
eprintln!("cleanup: {error}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn self_test(path: &str) -> Result<()> {
|
||||
let pool = pool(path, 1).await?;
|
||||
for cancel in [false, true] {
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let call = work.call(&mut lease, Duration::from_millis(50), move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO cancellation VALUES (1)")?;
|
||||
started.send(()).unwrap();
|
||||
connection.query_row("WITH RECURSIVE counter(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM counter WHERE x < 1000000000) SELECT sum(x) FROM counter", [], |row| row.get::<_, i64>(0))?;
|
||||
Ok(())
|
||||
});
|
||||
tokio::pin!(call);
|
||||
if cancel {
|
||||
tokio::select! {
|
||||
result = &mut call => panic!("work ended before cancellation: {result:?}"),
|
||||
result = ready => result?,
|
||||
}
|
||||
} else {
|
||||
assert!(call.await.is_err());
|
||||
ready.await?;
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
work.finish().await?;
|
||||
assert_eq!(work.slots.available_permits(), 8);
|
||||
let object = pool.get().await?;
|
||||
let connection = object.lock().map_err(|_| "poisoned connection")?;
|
||||
assert_eq!(
|
||||
connection.query_row("SELECT COUNT(*) FROM cancellation", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
}
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let call = work.call::<()>(&mut lease, Duration::from_secs(30), move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO cancellation VALUES (2)")?;
|
||||
started.send(()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
panic!("cancelled SQL panic");
|
||||
});
|
||||
tokio::pin!(call);
|
||||
tokio::select! {
|
||||
result = &mut call => panic!("work ended before cancellation: {result:?}"),
|
||||
result = ready => result?,
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
assert!(
|
||||
work.finish()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("cancelled SQL panic")
|
||||
);
|
||||
assert_eq!(work.slots.available_permits(), 8);
|
||||
let object = pool.get().await?;
|
||||
assert_eq!(
|
||||
object
|
||||
.lock()
|
||||
.map_err(|_| "poisoned connection")?
|
||||
.query_row("SELECT COUNT(*) FROM cancellation", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
drop(object);
|
||||
drop(pool);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
if args[1] == "--self-test" {
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&args[2])?;
|
||||
drop(file);
|
||||
let connection = Connection::open(&args[2])?;
|
||||
connection.execute_batch("CREATE TABLE cancellation (value INTEGER NOT NULL)")?;
|
||||
drop(connection);
|
||||
runtime.block_on(self_test(&args[2]))?;
|
||||
println!("deadline, cancellation, rollback and drain passed");
|
||||
return Ok(());
|
||||
}
|
||||
let mut input: Input = serde_json::from_str(&args[2])?;
|
||||
input.title = input.title.trim().into();
|
||||
if !(1..=120).contains(&input.title.chars().count()) {
|
||||
return Err("title range".into());
|
||||
}
|
||||
println!("{}", runtime.block_on(execute(&args[1], input))?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 独立性能参考共用的 SQLite 资源责任;仅依赖官方库,不链接 Dever。
|
||||
use deadpool_sqlite::{
|
||||
Object, Pool, Runtime,
|
||||
rusqlite::{self, Connection},
|
||||
};
|
||||
use std::{
|
||||
error::Error,
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{sync::Semaphore, time::Instant};
|
||||
use tokio_util::{sync::CancellationToken, task::TaskTracker};
|
||||
pub(crate) type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
|
||||
pub(crate) struct Lease {
|
||||
pub(crate) object: Option<Object>,
|
||||
pub(crate) reusable: bool,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
if !self.reusable {
|
||||
drop(Object::take(self.object.take().unwrap()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Work {
|
||||
tasks: TaskTracker,
|
||||
pub(crate) slots: Arc<Semaphore>,
|
||||
faults: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
impl Work {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: TaskTracker::new(),
|
||||
slots: Arc::new(Semaphore::new(8)),
|
||||
faults: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn call<T: Send + 'static>(
|
||||
&self,
|
||||
lease: &mut Option<Lease>,
|
||||
timeout: Duration,
|
||||
run: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let cancelled = CancellationToken::new();
|
||||
let _cancel = cancelled.clone().drop_guard();
|
||||
let slot = tokio::time::timeout_at(deadline, self.slots.clone().acquire_owned()).await??;
|
||||
let mut owned = lease.take().ok_or("discarded connection")?;
|
||||
owned.reusable = false;
|
||||
let faults = self.faults.clone();
|
||||
// 令牌随结果释放,调用取消时也等到连接被归还或丢弃后才算排空。
|
||||
let tracking = self.tasks.token();
|
||||
let job = tokio::task::spawn_blocking(move || {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| -> Result<T> {
|
||||
let mut connection = owned
|
||||
.object
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.map_err(|_| "poisoned SQLite connection")?;
|
||||
if cancelled.is_cancelled() || Instant::now() >= deadline {
|
||||
return Err("SQLite operation cancelled or expired".into());
|
||||
}
|
||||
let signal = cancelled.clone();
|
||||
connection.progress_handler(
|
||||
1000,
|
||||
Some(move || signal.is_cancelled() || Instant::now() >= deadline),
|
||||
)?;
|
||||
let value = run(&mut connection);
|
||||
connection.progress_handler(0, None::<fn() -> bool>)?;
|
||||
if cancelled.is_cancelled() || Instant::now() >= deadline {
|
||||
return Err("SQLite operation cancelled or expired".into());
|
||||
}
|
||||
owned.reusable = connection.is_autocommit();
|
||||
value
|
||||
}));
|
||||
let result = result.unwrap_or_else(|panic| {
|
||||
let message = panic_message(panic);
|
||||
faults.lock().unwrap().push(message.clone());
|
||||
Err(message.into())
|
||||
});
|
||||
drop(slot);
|
||||
(owned, result, tracking)
|
||||
});
|
||||
let (owned, result, _tracking) = tokio::time::timeout_at(deadline, job).await??;
|
||||
*lease = Some(owned);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn finish(&self) -> Result<()> {
|
||||
self.tasks.close();
|
||||
self.tasks.wait().await;
|
||||
let faults = std::mem::take(&mut *self.faults.lock().unwrap());
|
||||
if !faults.is_empty() {
|
||||
return Err(faults.join("; ").into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
|
||||
panic
|
||||
.downcast_ref::<&str>()
|
||||
.copied()
|
||||
.or_else(|| panic.downcast_ref::<String>().map(String::as_str))
|
||||
.unwrap_or("non-text Rust panic")
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
pub(crate) async fn pool(path: &str, connections: usize) -> Result<Pool> {
|
||||
use deadpool_sqlite::{Hook, HookError, Timeouts};
|
||||
// 输入是测量驱动创建的实际路径;URI 编码避免路径中的 '?' 改写打开模式。
|
||||
const URI_PATH: &percent_encoding::AsciiSet =
|
||||
&percent_encoding::CONTROLS.add(b'%').add(b'?').add(b'#');
|
||||
let uri = format!(
|
||||
"file:{}?mode=rw",
|
||||
percent_encoding::utf8_percent_encode(path, URI_PATH)
|
||||
);
|
||||
let timeout = Duration::from_secs(30);
|
||||
Ok(deadpool_sqlite::Config::new(uri).builder(Runtime::Tokio1)?
|
||||
.max_size(connections)
|
||||
.timeouts(Timeouts { wait: Some(Duration::from_secs(5)), create: Some(timeout), recycle: Some(timeout) })
|
||||
.post_create(Hook::async_fn(move |object, _| Box::pin(async move {
|
||||
object.interact(move |connection| {
|
||||
connection.busy_timeout(timeout)?;
|
||||
connection.create_scalar_function("_dever_length", 1,
|
||||
rusqlite::functions::FunctionFlags::SQLITE_UTF8
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_INNOCUOUS,
|
||||
|ctx| Ok(ctx.get_raw(0).as_str()
|
||||
.map_err(|error| rusqlite::Error::UserFunctionError(Box::new(error)))?
|
||||
.chars().count() as i64))?;
|
||||
connection.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;")
|
||||
}).await.map_err(|error| HookError::message(error.to_string()))?
|
||||
.map_err(HookError::Backend)
|
||||
})))
|
||||
.build()?)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
flow echo(value: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| out | port | port.echo(value) |
|
||||
|
||||
loop echoes(values: List<Text>) (out: List<Text>)
|
||||
| each value in values | result |
|
||||
| out | list echo(value) |
|
||||
|
||||
flow batch(values: List<Text>) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| - | port | port.unit() |
|
||||
| out | loop | echoes(values) |
|
||||
@@ -0,0 +1,8 @@
|
||||
echo(value: Text) (out: Text) {
|
||||
out = port.echo(value)
|
||||
}
|
||||
|
||||
batch(values: List<Text>) (out: List<Text>) {
|
||||
port.unit()
|
||||
out = each(echo, values)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// 独立客户端使用标准库的管道、长度帧和进程等待,不导入 Dever。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
const limit = 16 * 1024 * 1024
|
||||
|
||||
type worker struct { command *exec.Cmd; input io.WriteCloser; output io.ReadCloser; next uint64; waited bool }
|
||||
func (w *worker) send(value any) error {
|
||||
body, err := json.Marshal(value)
|
||||
if err != nil { return err }
|
||||
if len(body) > limit { return errors.New("Worker frame exceeds byte limit") }
|
||||
var prefix [4]byte
|
||||
binary.BigEndian.PutUint32(prefix[:],uint32(len(body)))
|
||||
_, err = io.Copy(w.input, io.MultiReader(bytes.NewReader(prefix[:]), bytes.NewReader(body)))
|
||||
return err
|
||||
}
|
||||
func (w *worker) read(target any) error {
|
||||
var prefix [4]byte
|
||||
if _,err:=io.ReadFull(w.output,prefix[:]); err!=nil { return err }
|
||||
length:=binary.BigEndian.Uint32(prefix[:])
|
||||
if length==0 || length>limit { return errors.New("invalid Worker frame length") }
|
||||
body:=make([]byte,length)
|
||||
if _,err:=io.ReadFull(w.output,body); err!=nil { return err }
|
||||
decoder:=json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
func (w *worker) identity(kind string) error {
|
||||
message:=map[string]any{"kind":kind,"id":0}
|
||||
if err:=w.send(message); err!=nil { return err }
|
||||
var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`}
|
||||
if err:=w.read(&reply); err!=nil { return err }
|
||||
if reply.Kind!=kind || reply.ID!=0 { return errors.New("Worker identity mismatch") }
|
||||
return nil
|
||||
}
|
||||
func (w *worker) call(operation string,payload any,target any) error {
|
||||
id:=w.next
|
||||
w.next++
|
||||
if err:=w.send(map[string]any{"kind":"call","id":id,"operation":operation,"payload":payload}); err!=nil { return err }
|
||||
var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`; Payload json.RawMessage `json:"payload"`}
|
||||
if err:=w.read(&reply); err!=nil { return err }
|
||||
if reply.Kind!="result" || reply.ID!=id { return errors.New("Worker response identity mismatch") }
|
||||
decoder:=json.NewDecoder(bytes.NewReader(reply.Payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
func run(path string, values []string) (results []string, failure error) {
|
||||
command:=exec.Command(path)
|
||||
input,err:=command.StdinPipe()
|
||||
if err!=nil { return nil,err }
|
||||
output,err:=command.StdoutPipe()
|
||||
if err!=nil { return nil,err }
|
||||
command.Stderr=os.Stderr
|
||||
if err=command.Start(); err!=nil { return nil,err }
|
||||
w:=worker{command:command,input:input,output:output,next:1}
|
||||
defer func(){
|
||||
if !w.waited {
|
||||
failure=errors.Join(failure,command.Process.Kill(),command.Wait())
|
||||
}
|
||||
}()
|
||||
hello:=map[string]any{"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[]string{},"operations":[]string{"echo","unit"},"setting":nil}
|
||||
if err=w.send(hello); err!=nil { return nil,err }
|
||||
delete(hello,"setting")
|
||||
hello["kind"]="ready"
|
||||
expected,_:=json.Marshal(hello)
|
||||
var ready map[string]json.RawMessage
|
||||
if err=w.read(&ready); err!=nil { return nil,err }
|
||||
actual,_:=json.Marshal(ready)
|
||||
if !bytes.Equal(actual,expected) { return nil,errors.New("Worker handshake mismatch") }
|
||||
if err=w.identity("health"); err!=nil { return nil,err }
|
||||
var unit struct{}
|
||||
if err=w.call("unit",struct{}{},&unit); err!=nil { return nil,err }
|
||||
results=make([]string,0,len(values))
|
||||
for _,value:=range values {
|
||||
var reply struct{Out string `json:"out"`}
|
||||
if err=w.call("echo",map[string]string{"value":value},&reply); err!=nil { return nil,err }
|
||||
results=append(results,reply.Out)
|
||||
}
|
||||
if err=w.identity("shutdown"); err!=nil { return nil,err }
|
||||
failure=command.Wait()
|
||||
w.waited=true
|
||||
return results,failure
|
||||
}
|
||||
func main(){
|
||||
if len(os.Args)!=3 { fmt.Fprintln(os.Stderr,"expected Worker and input");os.Exit(1) }
|
||||
// 输入只有一个必填字段,Token/Decode 直接拒绝未知、重复、缺失与尾随内容。
|
||||
decoder:=json.NewDecoder(bytes.NewBufferString(os.Args[2]))
|
||||
begin,err:=decoder.Token()
|
||||
if err!=nil || begin!=json.Delim('{') { fmt.Fprintln(os.Stderr,"invalid input object");os.Exit(1) }
|
||||
field,err:=decoder.Token()
|
||||
if err!=nil || field!="values" { fmt.Fprintln(os.Stderr,"expected values");os.Exit(1) }
|
||||
start,err:=decoder.Token()
|
||||
if err!=nil || start!=json.Delim('[') { fmt.Fprintln(os.Stderr,"expected text list");os.Exit(1) }
|
||||
values:=[]string{}
|
||||
for decoder.More() {
|
||||
token,err:=decoder.Token()
|
||||
value,ok:=token.(string)
|
||||
if err!=nil || !ok { fmt.Fprintln(os.Stderr,"expected text element",err);os.Exit(1) }
|
||||
values=append(values,value)
|
||||
}
|
||||
if _,err=decoder.Token(); err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
|
||||
end,err:=decoder.Token()
|
||||
if err!=nil || end!=json.Delim('}') { fmt.Fprintln(os.Stderr,"unexpected input field");os.Exit(1) }
|
||||
if _,err=decoder.Token(); !errors.Is(err,io.EOF) { fmt.Fprintln(os.Stderr,"unexpected trailing input");os.Exit(1) }
|
||||
result,err:=run(os.Args[1],values)
|
||||
if err==nil { err=json.NewEncoder(os.Stdout).Encode(result) }
|
||||
if err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! 独立 Worker 客户端;帧、异步管道和期限直接使用 Tokio/tokio-util。
|
||||
use bytes::Bytes;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{error::Error, process::Stdio, time::Duration};
|
||||
use tokio::{process::{Child, ChildStdin, ChildStdout, Command}, time::timeout};
|
||||
use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
|
||||
type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
const LIMIT: usize = 16 * 1024 * 1024;
|
||||
const DEADLINE: Duration = Duration::from_secs(2);
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input { values: Vec<String> }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Reply { kind: String, id: u64, payload: Value }
|
||||
struct Worker {
|
||||
child: Child,
|
||||
input: FramedWrite<ChildStdin, LengthDelimitedCodec>,
|
||||
output: FramedRead<ChildStdout, LengthDelimitedCodec>,
|
||||
next: u64,
|
||||
}
|
||||
impl Worker {
|
||||
async fn start(path: &str) -> Result<Self> {
|
||||
let mut child = Command::new(path).stdin(Stdio::piped()).stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit()).kill_on_drop(true).spawn()?;
|
||||
let mut worker = Self {
|
||||
input: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_write(child.stdin.take().unwrap()),
|
||||
output: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_read(child.stdout.take().unwrap()),
|
||||
child, next: 1,
|
||||
};
|
||||
let hello = json!({"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[],"operations":["echo","unit"],"setting":null});
|
||||
worker.send(&hello).await?;
|
||||
let mut ready = hello;
|
||||
ready.as_object_mut().unwrap().remove("setting");
|
||||
ready["kind"] = "ready".into();
|
||||
if worker.read().await? != ready { return Err("Worker handshake mismatch".into()); }
|
||||
let health = json!({"kind":"health","id":0});
|
||||
worker.send(&health).await?;
|
||||
if worker.read().await? != health { return Err("Worker health mismatch".into()); }
|
||||
Ok(worker)
|
||||
}
|
||||
async fn send(&mut self, value: &Value) -> Result<()> {
|
||||
timeout(DEADLINE, self.input.send(Bytes::from(serde_json::to_vec(value)?))).await??;
|
||||
Ok(())
|
||||
}
|
||||
async fn read(&mut self) -> Result<Value> {
|
||||
let bytes = timeout(DEADLINE, self.output.next()).await?
|
||||
.ok_or("Worker closed its output")??;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
async fn call(&mut self, operation: &str, payload: Value) -> Result<Value> {
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
self.send(&json!({"kind":"call","id":id,"operation":operation,"payload":payload})).await?;
|
||||
let reply: Reply = serde_json::from_value(self.read().await?)?;
|
||||
if reply.kind != "result" || reply.id != id { return Err("Worker response identity mismatch".into()); }
|
||||
Ok(reply.payload)
|
||||
}
|
||||
async fn stop(&mut self) -> Result<()> {
|
||||
let shutdown = json!({"kind":"shutdown","id":0});
|
||||
self.send(&shutdown).await?;
|
||||
if self.read().await? != shutdown { return Err("Worker shutdown mismatch".into()); }
|
||||
if !timeout(DEADLINE, self.child.wait()).await??.success() { return Err("Worker exited unsuccessfully".into()); }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
async fn execute(path: &str, input: Input) -> Result<Vec<String>> {
|
||||
let mut worker = Worker::start(path).await?;
|
||||
let result = async {
|
||||
if worker.call("unit", json!({})).await? != json!({}) { return Err("invalid unit output".into()); }
|
||||
let mut results = Vec::with_capacity(input.values.len());
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Echo { out: String }
|
||||
for value in input.values {
|
||||
let output: Echo = serde_json::from_value(worker.call("echo", json!({"value":value})).await?)?;
|
||||
results.push(output.out);
|
||||
}
|
||||
Ok(results)
|
||||
}.await;
|
||||
match result {
|
||||
Ok(values) => { worker.stop().await?; Ok(values) }
|
||||
Err(error) => {
|
||||
worker.child.kill().await?;
|
||||
worker.child.wait().await?;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let worker = args.next().ok_or("Worker path is required")?;
|
||||
let input: Input = serde_json::from_str(&args.next().ok_or("input is required")?)?;
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
let values = runtime.block_on(execute(&worker, input))?;
|
||||
println!("{}", serde_json::to_string(&values)?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"""顺序 HTTP/1 连接复用;独立 Rust 直接使用相同 Hyper 连接池。"""
|
||||
from http_reference import source as single_source
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == "dever":
|
||||
return '''setting port: Int
|
||||
flow exchange(value: Int, client: dever.system.HttpClient) (out: Int)
|
||||
| step | kind | do |
|
||||
| body | calc | dever.bytes.fromText(int.toText(value)) |
|
||||
| request | calc | dever.http.Request { method = "POST", target = "/echo", headers = [], body = body } |
|
||||
| response | flow | dever.http.request(client, request) |
|
||||
| - | check | response.status == 200 else Invalid |
|
||||
| - | check | response.body == body else Invalid |
|
||||
| out | calc | 1 |
|
||||
loop measure(n: Int, client: dever.system.HttpClient) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum exchange(value, client) |
|
||||
flow start(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| origin | calc | "http://127.0.0.1:" + int.toText(port) |
|
||||
| client | flow | dever.http.client(origin, dever.tls.system(), dever.http.defaultLimits(), dever.http.defaultPoolLimits()) |
|
||||
| out | loop | measure(n, client) |
|
||||
| - | flow | dever.http.closeClient(client) |
|
||||
cmd bench = start
|
||||
'''
|
||||
if language == "go":
|
||||
return single_source("go").replace("DisableKeepAlives: true", "MaxIdleConnsPerHost: 32, MaxConnsPerHost: 32").replace(' request.Host = "localhost"\n', '')
|
||||
if language != "rust":
|
||||
raise ValueError(language)
|
||||
return '''use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper_util::{client::legacy::{Client, connect::HttpConnector}, rt::{TokioExecutor, TokioTimer}};
|
||||
use serde::Deserialize;
|
||||
use std::time::Duration;
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Root { module: Module }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Module { main: Domain }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Domain { main: Settings }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Settings { port: u16 }
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let data = std::fs::read(std::env::args().nth(2).unwrap()).unwrap();
|
||||
let config: Root = serde_json::from_slice(&data).unwrap();
|
||||
let uri: hyper::Uri = format!("http://127.0.0.1:{}/echo", config.module.main.main.port).parse().unwrap();
|
||||
let total = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
|
||||
let mut connector = HttpConnector::new();
|
||||
connector.set_nodelay(true);
|
||||
connector.set_connect_timeout(Some(Duration::from_secs(5)));
|
||||
let client: Client<_, Full<Bytes>> = Client::builder(TokioExecutor::new())
|
||||
.pool_timer(TokioTimer::new()).timer(TokioTimer::new())
|
||||
.pool_idle_timeout(Duration::from_secs(10)).pool_max_idle_per_host(32)
|
||||
.http1_max_buf_size(8192).retry_canceled_requests(false).build(connector);
|
||||
let mut total = 0i64;
|
||||
for value in 0..n {
|
||||
let body = Bytes::from(value.to_string());
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let request = hyper::Request::builder().method("POST").uri(uri.clone()).body(Full::new(body.clone())).unwrap();
|
||||
let response = client.request(request).await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let header_bytes = 32 + response.headers().iter().map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4).sum::<usize>();
|
||||
assert!(header_bytes <= 8192);
|
||||
let response = Limited::new(response.into_body(), 1048576).collect().await.unwrap().to_bytes();
|
||||
assert_eq!(response, body);
|
||||
}).await.unwrap();
|
||||
total = total.checked_add(1).unwrap();
|
||||
}
|
||||
total
|
||||
});
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,121 @@
|
||||
"""HTTP 单次新连接的真实回环对照;共享 Node HTTP 服务只回显收到的正文。"""
|
||||
import atexit
|
||||
import json
|
||||
import select
|
||||
import subprocess
|
||||
|
||||
|
||||
def server(root):
|
||||
script = root / 'http-server.cjs'
|
||||
script.write_text('''const http = require('node:http');
|
||||
const server = http.createServer((request, response) => {
|
||||
const chunks = [];
|
||||
request.on('data', chunk => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
const body = Buffer.concat(chunks);
|
||||
response.sendDate = false;
|
||||
response.writeHead(200, { 'content-length': body.length, 'x-echo': 'yes' });
|
||||
response.end(body);
|
||||
});
|
||||
});
|
||||
server.listen(0, '127.0.0.1', () => console.log(server.address().port));
|
||||
process.on('SIGTERM', () => server.close());
|
||||
''')
|
||||
error = (root / 'http-server.stderr').open('w')
|
||||
process = subprocess.Popen(['node', str(script)], stdout=subprocess.PIPE, stderr=error, text=True)
|
||||
def close():
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
error.close()
|
||||
atexit.register(close)
|
||||
if not select.select([process.stdout], [], [], 10)[0]:
|
||||
raise RuntimeError('HTTP reference server did not report its address')
|
||||
return json.loads(process.stdout.readline())
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting port: Int
|
||||
flow exchange(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| body | calc | dever.bytes.fromText(int.toText(value)) |
|
||||
| request | calc | dever.http.Request { method = "POST", target = "/echo", headers = [dever.http.header("host", "localhost")], body = body } |
|
||||
| response | flow | dever.http.send("127.0.0.1", port, request, dever.http.defaultLimits()) |
|
||||
| - | check | response.status == 200 else Invalid |
|
||||
| - | check | response.body == body else Invalid |
|
||||
| out | calc | 1 |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum exchange(value) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use serde::Deserialize;
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Root { module: Module }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Module { main: Domain }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Domain { main: Settings }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Settings { port: u16 }
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let data = std::fs::read(std::env::args().nth(2).unwrap()).unwrap();
|
||||
let config: Root = serde_json::from_slice(&data).unwrap();
|
||||
let port = config.module.main.main.port;
|
||||
let total = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
|
||||
let mut total = 0i64;
|
||||
for value in 0..n {
|
||||
let body = Bytes::from(value.to_string());
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
let stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
stream.set_nodelay(true).unwrap();
|
||||
let (mut sender, connection) = hyper::client::conn::http1::Builder::new().max_buf_size(8192)
|
||||
.handshake(TokioIo::new(stream)).await.unwrap();
|
||||
let request = hyper::Request::builder().method("POST").uri("/echo").header("host", "localhost")
|
||||
.body(Full::new(body.clone())).unwrap();
|
||||
let response = async {
|
||||
let response = sender.send_request(request).await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let header_bytes: usize = 32 + response.headers().iter().map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4).sum::<usize>();
|
||||
assert!(header_bytes <= 8192);
|
||||
let response = Limited::new(response.into_body(), 1048576).collect().await.unwrap().to_bytes();
|
||||
assert_eq!(response, body);
|
||||
};
|
||||
tokio::pin!(connection, response);
|
||||
tokio::select! { biased; () = &mut response => {}, _ = &mut connection => response.await }
|
||||
}).await.unwrap();
|
||||
total = total.checked_add(1).unwrap();
|
||||
}
|
||||
total
|
||||
});
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("bytes"; "encoding/json"; "fmt"; "io"; "net/http"; "os"; "strconv"; "time")
|
||||
type Settings struct { Port int }
|
||||
type Domain struct { Main Settings }
|
||||
type Module struct { Main Domain }
|
||||
type Root struct { Module Module }
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
data, err := os.ReadFile(os.Args[2]); if err != nil { panic(err) }
|
||||
var config Root
|
||||
decoder := json.NewDecoder(bytes.NewReader(data)); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&config); err != nil { panic(err) }
|
||||
client := &http.Client{Timeout: 5*time.Second, Transport: &http.Transport{DisableKeepAlives: true, MaxResponseHeaderBytes: 8192}}
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
body := []byte(strconv.FormatInt(value, 10))
|
||||
request, err := http.NewRequest("POST", fmt.Sprintf("http://127.0.0.1:%d/echo", config.Module.Main.Main.Port), bytes.NewReader(body)); if err != nil { panic(err) }
|
||||
request.Host = "localhost"
|
||||
response, err := client.Do(request); if err != nil { panic(err) }
|
||||
received, err := io.ReadAll(io.LimitReader(response.Body, 1048577)); if err != nil { panic(err) }
|
||||
if err := response.Body.Close(); err != nil { panic(err) }
|
||||
if response.StatusCode != 200 || len(received) > 1048576 || !bytes.Equal(received, body) { panic("response mismatch") }
|
||||
next := total + 1; if next < total { panic("count overflow") }; total = next
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,116 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Config {
|
||||
module: Module,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Module {
|
||||
main: Domain,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Domain {
|
||||
main: Settings,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings {
|
||||
port: u16,
|
||||
}
|
||||
|
||||
pub(super) fn run() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mode = args.next().unwrap();
|
||||
let count: i64 = args.next().unwrap().parse().unwrap();
|
||||
if mode == "server" {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
let owner = Owner::default();
|
||||
let listener =
|
||||
tokio::net::TcpListener::bind(("127.0.0.1", u16::try_from(count).unwrap()))
|
||||
.await
|
||||
.unwrap();
|
||||
server::serve(listener, CancellationToken::new(), owner.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(owner.take_faults().is_empty());
|
||||
});
|
||||
return;
|
||||
}
|
||||
let config: Config =
|
||||
serde_json::from_slice(&std::fs::read(args.next().unwrap()).unwrap()).unwrap();
|
||||
let port = config.module.main.main.port;
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
if mode == "http" {
|
||||
let address = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let mut total = 0i64;
|
||||
for value in 0..count {
|
||||
let body = Bytes::from(value.to_string());
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/echo")
|
||||
.header("Host", "localhost")
|
||||
.body(Full::new(body.clone()))
|
||||
.unwrap();
|
||||
let response = single::send(address, request).await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.into_body(), body);
|
||||
total = total.checked_add(1).unwrap();
|
||||
}
|
||||
println!("{total}");
|
||||
return;
|
||||
}
|
||||
let pool = Pool::new("127.0.0.1".into(), port, 32).await.unwrap();
|
||||
let uri: Uri = format!("http://127.0.0.1:{port}/echo").parse().unwrap();
|
||||
let result = AssertUnwindSafe(async {
|
||||
let mut total = 0i64;
|
||||
for value in 0..count {
|
||||
let body = Bytes::from(value.to_string());
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri.clone())
|
||||
.body(Full::new(body.clone()))
|
||||
.unwrap();
|
||||
if mode == "http_pool" {
|
||||
let response = pool.request(request).await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.into_body(), body);
|
||||
} else {
|
||||
assert_eq!(mode, "http_stream");
|
||||
let (parts, download) = pool.open(request).await.unwrap();
|
||||
assert_eq!(parts.status, 200);
|
||||
let _close = download.close_on_drop();
|
||||
let mut offset = 0;
|
||||
while let Some(chunk) = download.next().await.unwrap() {
|
||||
let end = offset + chunk.len();
|
||||
assert_eq!(chunk, body.slice(offset..end));
|
||||
offset = end;
|
||||
}
|
||||
assert_eq!(offset, body.len());
|
||||
}
|
||||
total = total.checked_add(1).unwrap();
|
||||
}
|
||||
total
|
||||
})
|
||||
.catch_unwind()
|
||||
.await;
|
||||
pool.close().await;
|
||||
assert!(pool.owner.tasks.is_empty());
|
||||
assert!(pool.owner.take_faults().is_empty());
|
||||
assert_eq!(pool.physical.available_permits(), 32);
|
||||
match result {
|
||||
Ok(total) => println!("{total}"),
|
||||
Err(fault) => std::panic::resume_unwind(fault),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
//! 独立 Rust 资源对照:使用原生 Hyper 值,不导入或复制 Dever 运行库。
|
||||
use bytes::Bytes;
|
||||
use futures_util::FutureExt;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::{Request, Response, Uri, body::Incoming};
|
||||
use hyper_util::{
|
||||
client::legacy::{
|
||||
Client,
|
||||
connect::{Connected, Connection, HttpConnector, dns::Name},
|
||||
},
|
||||
rt::{TokioIo, TokioTimer},
|
||||
};
|
||||
use std::{
|
||||
any::Any,
|
||||
future::{Future, Ready, ready},
|
||||
io,
|
||||
net::{SocketAddr, ToSocketAddrs},
|
||||
panic::AssertUnwindSafe,
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
net::TcpStream,
|
||||
sync::{OwnedSemaphorePermit, Semaphore},
|
||||
};
|
||||
use tokio_util::{sync::CancellationToken, task::TaskTracker};
|
||||
use tower_service::Service;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
type Fault = Box<dyn Any + Send>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Owner {
|
||||
cancel: CancellationToken,
|
||||
tasks: TaskTracker,
|
||||
faults: Arc<Mutex<Vec<Fault>>>,
|
||||
}
|
||||
impl Owner {
|
||||
async fn close(&self) {
|
||||
self.cancel.cancel();
|
||||
self.tasks.close();
|
||||
self.tasks.wait().await;
|
||||
}
|
||||
fn take_faults(&self) -> Vec<Fault> {
|
||||
std::mem::take(&mut *self.faults.lock().unwrap())
|
||||
}
|
||||
async fn run<T>(
|
||||
&self,
|
||||
duration: Duration,
|
||||
work: impl Future<Output = io::Result<T>>,
|
||||
) -> io::Result<T> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = self.cancel.cancelled() => Err(io::Error::new(io::ErrorKind::NotConnected, "closed")),
|
||||
result = tokio::time::timeout(duration, work) => result.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<F: Future<Output = ()> + Send + 'static> hyper::rt::Executor<F> for Owner {
|
||||
fn execute(&self, work: F) {
|
||||
let owner = self.clone();
|
||||
self.tasks.spawn(async move {
|
||||
let result = AssertUnwindSafe(async {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = owner.cancel.cancelled() => {},
|
||||
() = work => {},
|
||||
}
|
||||
})
|
||||
.catch_unwind()
|
||||
.await;
|
||||
if let Err(fault) = result {
|
||||
owner.faults.lock().unwrap().push(fault);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FixedDns(Arc<Vec<SocketAddr>>);
|
||||
impl Service<Name> for FixedDns {
|
||||
type Response = std::vec::IntoIter<SocketAddr>;
|
||||
type Error = io::Error;
|
||||
type Future = Ready<io::Result<Self::Response>>;
|
||||
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
fn call(&mut self, _: Name) -> Self::Future {
|
||||
ready(Ok(self.0.as_ref().clone().into_iter()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Connector {
|
||||
tcp: HttpConnector<FixedDns>,
|
||||
slots: Arc<Semaphore>,
|
||||
}
|
||||
impl Service<Uri> for Connector {
|
||||
type Response = Socket;
|
||||
type Error = io::Error;
|
||||
type Future = Pin<Box<dyn Future<Output = io::Result<Socket>> + Send>>;
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.tcp.poll_ready(cx).map_err(io::Error::other)
|
||||
}
|
||||
fn call(&mut self, uri: Uri) -> Self::Future {
|
||||
let slots = self.slots.clone();
|
||||
let connect = self.tcp.call(uri);
|
||||
Box::pin(async move {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let permit = slots.acquire_owned().await.map_err(io::Error::other)?;
|
||||
Ok(Socket {
|
||||
io: connect.await.map_err(io::Error::other)?,
|
||||
_permit: permit,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// HttpConnector 没有总连接限额;许可随真实传输释放,不把空闲连接上限当作总量。
|
||||
struct Socket {
|
||||
io: TokioIo<TcpStream>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
impl Connection for Socket {
|
||||
fn connected(&self) -> Connected {
|
||||
self.io.connected()
|
||||
}
|
||||
}
|
||||
impl hyper::rt::Read for Socket {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: hyper::rt::ReadBufCursor<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
impl hyper::rt::Write for Socket {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.io).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_shutdown(cx)
|
||||
}
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
self.io.is_write_vectored()
|
||||
}
|
||||
fn poll_write_vectored(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
bufs: &[io::IoSlice<'_>],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.io).poll_write_vectored(cx, bufs)
|
||||
}
|
||||
}
|
||||
|
||||
struct Pool {
|
||||
client: Client<Connector, Full<Bytes>>,
|
||||
owner: Owner,
|
||||
requests: Arc<Semaphore>,
|
||||
physical: Arc<Semaphore>,
|
||||
origin: hyper::http::uri::Authority,
|
||||
}
|
||||
impl Pool {
|
||||
async fn new(host: String, port: u16, capacity: usize) -> io::Result<Self> {
|
||||
let origin = format!("{host}:{port}").parse().map_err(io::Error::other)?;
|
||||
// DNS 只解析一次;超时也等待已启动的阻塞查询退出。
|
||||
let query = tokio::task::spawn_blocking(move || {
|
||||
(host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.map(Iterator::collect::<Vec<_>>)
|
||||
});
|
||||
tokio::pin!(query);
|
||||
let addresses = match tokio::time::timeout(TIMEOUT, &mut query).await {
|
||||
Ok(result) => result.map_err(io::Error::other)??,
|
||||
Err(error) => {
|
||||
query.await.map_err(io::Error::other)??;
|
||||
return Err(io::Error::new(io::ErrorKind::TimedOut, error));
|
||||
}
|
||||
};
|
||||
let owner = Owner::default();
|
||||
let physical = Arc::new(Semaphore::new(capacity));
|
||||
let mut tcp = HttpConnector::new_with_resolver(FixedDns(Arc::new(addresses)));
|
||||
tcp.set_nodelay(true);
|
||||
tcp.set_connect_timeout(Some(TIMEOUT));
|
||||
let client = Client::builder(owner.clone())
|
||||
.pool_timer(TokioTimer::new())
|
||||
.timer(TokioTimer::new())
|
||||
.pool_idle_timeout(Duration::from_secs(10))
|
||||
.pool_max_idle_per_host(capacity)
|
||||
.http1_max_buf_size(8192)
|
||||
.retry_canceled_requests(false)
|
||||
.build(Connector {
|
||||
tcp,
|
||||
slots: physical.clone(),
|
||||
});
|
||||
Ok(Self {
|
||||
client,
|
||||
owner,
|
||||
requests: Arc::new(Semaphore::new(capacity)),
|
||||
physical,
|
||||
origin,
|
||||
})
|
||||
}
|
||||
async fn request(&self, request: Request<Full<Bytes>>) -> io::Result<Response<Bytes>> {
|
||||
self.check_request(&request)?;
|
||||
self.owner
|
||||
.run(TIMEOUT, async {
|
||||
let _permit = self.requests.acquire().await.map_err(io::Error::other)?;
|
||||
let response = self
|
||||
.client
|
||||
.request(request)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let (parts, body) = response.into_parts();
|
||||
check_head(&parts)?;
|
||||
let collected = Limited::new(body, 1048576)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if let Some(trailers) = collected.trailers() {
|
||||
check_headers(trailers, 0)?;
|
||||
}
|
||||
let body = collected.to_bytes();
|
||||
if matches!(parts.status.as_u16(), 204 | 205 | 304) && !body.is_empty() {
|
||||
return Err(io::Error::other("body forbidden for status"));
|
||||
}
|
||||
Ok(Response::from_parts(parts, body))
|
||||
})
|
||||
.await
|
||||
}
|
||||
async fn open(
|
||||
&self,
|
||||
request: Request<Full<Bytes>>,
|
||||
) -> io::Result<(
|
||||
hyper::http::response::Parts,
|
||||
streaming::SharedDownload<
|
||||
impl futures_util::Stream<Item = io::Result<Bytes>> + Send + 'static,
|
||||
>,
|
||||
)> {
|
||||
self.check_request(&request)?;
|
||||
self.owner
|
||||
.run(TIMEOUT, async {
|
||||
let permit = self
|
||||
.requests
|
||||
.clone()
|
||||
.acquire_owned()
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let (parts, body) = self
|
||||
.client
|
||||
.request(request)
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
.into_parts();
|
||||
check_head(&parts)?;
|
||||
let forbidden = matches!(parts.status.as_u16(), 204 | 205 | 304);
|
||||
let download = Download {
|
||||
state: Some((body, permit)),
|
||||
pending: Bytes::new(),
|
||||
owner: self.owner.clone(),
|
||||
forbidden,
|
||||
};
|
||||
let source = futures_util::stream::unfold(Some(download), |state| async move {
|
||||
let mut download = state?;
|
||||
match download.next().await {
|
||||
Ok(Some(bytes)) => {
|
||||
let next = if download.state.is_some() {
|
||||
Some(download)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some((Ok(bytes), next))
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(error) => Some((Err(error), None)),
|
||||
}
|
||||
});
|
||||
Ok((parts, streaming::SharedDownload::new(source)))
|
||||
})
|
||||
.await
|
||||
}
|
||||
async fn close(&self) {
|
||||
self.requests.close();
|
||||
self.owner.close().await;
|
||||
}
|
||||
fn check_request(&self, request: &Request<Full<Bytes>>) -> io::Result<()> {
|
||||
use hyper::body::Body;
|
||||
if request.uri().scheme_str() != Some("http")
|
||||
|| request.uri().authority() != Some(&self.origin)
|
||||
|| request.method() == hyper::Method::CONNECT
|
||||
{
|
||||
return Err(io::Error::other("request differs from fixed origin"));
|
||||
}
|
||||
if request.body().size_hint().exact().unwrap() > 1048576 {
|
||||
return Err(io::Error::other("request body exceeds limit"));
|
||||
}
|
||||
if ["content-length", "transfer-encoding", "upgrade"]
|
||||
.iter()
|
||||
.any(|name| request.headers().contains_key(*name))
|
||||
{
|
||||
return Err(io::Error::other("framing headers belong to Hyper"));
|
||||
}
|
||||
let mut hosts = request.headers().get_all("host").iter();
|
||||
let implicit_host = if let Some(host) = hosts.next() {
|
||||
if hosts.next().is_some()
|
||||
|| !host
|
||||
.as_bytes()
|
||||
.eq_ignore_ascii_case(self.origin.as_str().as_bytes())
|
||||
{
|
||||
return Err(io::Error::other("Host differs from fixed origin"));
|
||||
}
|
||||
0
|
||||
} else {
|
||||
// Hyper 自动加入 Host;发送预算必须包含它,不为了计时再造一份头。
|
||||
8 + self.origin.as_str().len()
|
||||
};
|
||||
check_headers(
|
||||
request.headers(),
|
||||
80 + request.method().as_str().len()
|
||||
+ request.uri().path_and_query().unwrap().as_str().len()
|
||||
+ implicit_host,
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Drop for Pool {
|
||||
fn drop(&mut self) {
|
||||
self.owner.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
struct Download {
|
||||
state: Option<(Incoming, OwnedSemaphorePermit)>,
|
||||
pending: Bytes,
|
||||
owner: Owner,
|
||||
forbidden: bool,
|
||||
}
|
||||
impl Download {
|
||||
async fn next(&mut self) -> io::Result<Option<Bytes>> {
|
||||
use hyper::body::Body;
|
||||
let Some((body, _permit)) = self.state.as_mut() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let result = self
|
||||
.owner
|
||||
.run(READ_TIMEOUT, async {
|
||||
loop {
|
||||
if !self.pending.is_empty() {
|
||||
return Ok(Some(self.pending.split_to(self.pending.len().min(65536))));
|
||||
}
|
||||
let Some(frame) = body.frame().await else {
|
||||
return Ok(None);
|
||||
};
|
||||
match frame.map_err(io::Error::other)?.into_data() {
|
||||
Ok(bytes) => {
|
||||
if self.forbidden && !bytes.is_empty() {
|
||||
return Err(io::Error::other("body forbidden for status"));
|
||||
}
|
||||
self.pending = bytes;
|
||||
}
|
||||
Err(frame) => check_headers(frame.trailers_ref().unwrap(), 0)?,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if !matches!(result, Ok(Some(_))) || (self.pending.is_empty() && body.is_end_stream()) {
|
||||
self.state.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn check_headers(headers: &hyper::HeaderMap, initial: usize) -> io::Result<()> {
|
||||
let size = headers.iter().fold(initial, |size, (name, value)| {
|
||||
size + name.as_str().len() + value.as_bytes().len() + 4
|
||||
});
|
||||
if size > 8192 {
|
||||
return Err(io::Error::other("headers exceed limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_head(parts: &hyper::http::response::Parts) -> io::Result<()> {
|
||||
check_headers(&parts.headers, 32)?;
|
||||
if !(200..=599).contains(&parts.status.as_u16()) {
|
||||
return Err(io::Error::other("invalid response status"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
entry::run();
|
||||
}
|
||||
|
||||
#[path = "http_resource_entry.rs"]
|
||||
mod entry;
|
||||
#[path = "http_resource_stream.rs"]
|
||||
mod streaming;
|
||||
|
||||
#[path = "http_resource_server.rs"]
|
||||
mod server;
|
||||
#[path = "http_resource_single.rs"]
|
||||
mod single;
|
||||
#[cfg(test)]
|
||||
#[path = "http_resource_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 同资源责任的纯回显服务:不构造 Dever DTO,不加入业务无用途的复制。
|
||||
use super::*;
|
||||
use futures_util::{TryStreamExt, stream};
|
||||
use hyper::{StatusCode, service::service_fn};
|
||||
use std::convert::Infallible;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
pub(super) async fn serve(
|
||||
listener: TcpListener,
|
||||
stop: CancellationToken,
|
||||
owner: Owner,
|
||||
) -> io::Result<()> {
|
||||
let accepted = stream::try_unfold((), |()| async {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = stop.cancelled() => Ok(None),
|
||||
() = owner.cancel.cancelled() => Ok(None),
|
||||
result = listener.accept() => result.map(|(stream, _)| Some((stream, ()))),
|
||||
}
|
||||
});
|
||||
let result = accepted
|
||||
.try_for_each_concurrent(32, |socket| {
|
||||
let stopped = stop.clone();
|
||||
let group = owner.clone();
|
||||
let work = owner.tasks.spawn(async move {
|
||||
let connection = async {
|
||||
socket.set_nodelay(true)?;
|
||||
let mut builder = hyper::server::conn::http1::Builder::new();
|
||||
builder
|
||||
.timer(TokioTimer::new())
|
||||
.header_read_timeout(TIMEOUT)
|
||||
.max_buf_size(8192);
|
||||
let connection =
|
||||
builder.serve_connection(TokioIo::new(socket), service_fn(reply));
|
||||
tokio::pin!(connection);
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = group.cancel.cancelled() => return Ok(()),
|
||||
() = stopped.cancelled() => connection.as_mut().graceful_shutdown(),
|
||||
result = &mut connection => return result.map_err(io::Error::other),
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = group.cancel.cancelled() => Ok(()),
|
||||
result = &mut connection => result.map_err(io::Error::other),
|
||||
}
|
||||
};
|
||||
match AssertUnwindSafe(connection).catch_unwind().await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => log("connection", &error.to_string()),
|
||||
Err(fault) => group.faults.lock().unwrap().push(fault),
|
||||
}
|
||||
});
|
||||
async { work.await.map_err(io::Error::other) }
|
||||
})
|
||||
.await;
|
||||
owner.close().await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn reply(request: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let checked = (|| {
|
||||
if parts.method == hyper::Method::CONNECT
|
||||
|| parts.uri.scheme().is_some()
|
||||
|| parts.uri.authority().is_some()
|
||||
|| !(parts.uri.path().starts_with('/')
|
||||
|| (parts.method == hyper::Method::OPTIONS && parts.uri.path() == "*"))
|
||||
{
|
||||
return Err(io::Error::other("invalid request target"));
|
||||
}
|
||||
let mut hosts = parts.headers.get_all("host").iter();
|
||||
let host = hosts
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other("missing host"))?;
|
||||
let authority: hyper::http::uri::Authority = host
|
||||
.to_str()
|
||||
.map_err(io::Error::other)?
|
||||
.parse()
|
||||
.map_err(io::Error::other)?;
|
||||
if hosts.next().is_some() || authority.host().is_empty() || authority.as_str().contains('@')
|
||||
{
|
||||
return Err(io::Error::other("invalid host"));
|
||||
}
|
||||
check_headers(
|
||||
&parts.headers,
|
||||
parts.method.as_str().len() + parts.uri.path_and_query().unwrap().as_str().len() + 16,
|
||||
)
|
||||
})();
|
||||
if let Err(error) = checked {
|
||||
return Ok(reject(StatusCode::BAD_REQUEST, &error.to_string()));
|
||||
}
|
||||
let body = match tokio::time::timeout(TIMEOUT, Limited::new(body, 1048576).collect()).await {
|
||||
Ok(Ok(body)) => body,
|
||||
Ok(Err(error)) => {
|
||||
let status = if error.is::<http_body_util::LengthLimitError>() {
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
} else {
|
||||
StatusCode::BAD_REQUEST
|
||||
};
|
||||
return Ok(reject(status, &error.to_string()));
|
||||
}
|
||||
Err(error) => return Ok(reject(StatusCode::REQUEST_TIMEOUT, &error.to_string())),
|
||||
};
|
||||
if let Some(trailers) = body.trailers()
|
||||
&& let Err(error) = check_headers(trailers, 0)
|
||||
{
|
||||
return Ok(reject(StatusCode::BAD_REQUEST, &error.to_string()));
|
||||
}
|
||||
// 纯 handler 仍有相同的时限及故障隔离;正文直接移动到响应。
|
||||
let response = AssertUnwindSafe(tokio::time::timeout(TIMEOUT, async {
|
||||
Response::new(Full::new(body.to_bytes()))
|
||||
}))
|
||||
.catch_unwind()
|
||||
.await;
|
||||
Ok(match response {
|
||||
Ok(Ok(response)) => response,
|
||||
Ok(Err(error)) => reject(StatusCode::GATEWAY_TIMEOUT, &error.to_string()),
|
||||
Err(fault) => {
|
||||
let message = if let Some(message) = fault.downcast_ref::<String>() {
|
||||
message.as_str()
|
||||
} else if let Some(message) = fault.downcast_ref::<&str>() {
|
||||
message
|
||||
} else {
|
||||
"non-text handler panic"
|
||||
};
|
||||
reject(StatusCode::INTERNAL_SERVER_ERROR, message)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn log(stage: &str, message: &str) {
|
||||
eprintln!(
|
||||
"{}",
|
||||
serde_json::json!({"event": "http_error", "stage": stage, "message": message})
|
||||
);
|
||||
}
|
||||
fn reject(status: StatusCode, reason: &str) -> Response<Full<Bytes>> {
|
||||
log("request", reason);
|
||||
let mut response = Response::new(Full::new(Bytes::new()));
|
||||
*response.status_mut() = status;
|
||||
response
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! 单次连接与响应共属调用 future;独立参考保留 Hyper 原生字段。
|
||||
use super::*;
|
||||
use hyper::body::Body;
|
||||
|
||||
pub(super) async fn send(
|
||||
address: SocketAddr,
|
||||
request: Request<Full<Bytes>>,
|
||||
) -> io::Result<Response<Bytes>> {
|
||||
let uri = request.uri();
|
||||
if request.method() == hyper::Method::CONNECT
|
||||
|| uri.scheme().is_some()
|
||||
|| uri.authority().is_some()
|
||||
|| !(uri.path().starts_with('/')
|
||||
|| (request.method() == hyper::Method::OPTIONS && uri.path() == "*"))
|
||||
{
|
||||
return Err(io::Error::other("invalid target"));
|
||||
}
|
||||
let mut hosts = request.headers().get_all("host").iter();
|
||||
let host: hyper::http::uri::Authority = hosts
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other("missing Host"))?
|
||||
.to_str()
|
||||
.map_err(io::Error::other)?
|
||||
.parse()
|
||||
.map_err(io::Error::other)?;
|
||||
if hosts.next().is_some() || host.host().is_empty() || host.as_str().contains('@') {
|
||||
return Err(io::Error::other("invalid Host"));
|
||||
}
|
||||
if ["content-length", "transfer-encoding", "upgrade"]
|
||||
.iter()
|
||||
.any(|name| request.headers().contains_key(*name))
|
||||
{
|
||||
return Err(io::Error::other("framing headers belong to Hyper"));
|
||||
}
|
||||
if request.body().size_hint().exact().unwrap() > 1048576 {
|
||||
return Err(io::Error::other("request body exceeds limit"));
|
||||
}
|
||||
check_headers(
|
||||
request.headers(),
|
||||
80 + request.method().as_str().len() + uri.path_and_query().unwrap().as_str().len(),
|
||||
)?;
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let socket = TcpStream::connect(address).await?;
|
||||
socket.set_nodelay(true)?;
|
||||
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
|
||||
.max_buf_size(8192)
|
||||
.handshake(TokioIo::new(socket))
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let receiving = async {
|
||||
let (parts, body) = sender
|
||||
.send_request(request)
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
.into_parts();
|
||||
check_head(&parts)?;
|
||||
let body = Limited::new(body, 1048576)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if let Some(trailers) = body.trailers() {
|
||||
check_headers(trailers, 0)?;
|
||||
}
|
||||
let body = body.to_bytes();
|
||||
if matches!(parts.status.as_u16(), 204 | 205 | 304) && !body.is_empty() {
|
||||
return Err(io::Error::other("body forbidden for status"));
|
||||
}
|
||||
Ok(Response::from_parts(parts, body))
|
||||
};
|
||||
tokio::pin!(connection, receiving);
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut receiving => result,
|
||||
result = &mut connection => match (receiving.await, result) {
|
||||
(Ok(response), _) => Ok(response),
|
||||
(Err(_), Err(error)) => Err(io::Error::other(error)),
|
||||
(Err(error), Ok(())) => Err(error),
|
||||
},
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! 使用库提供的取消通知,支持别名读取与不依赖读取者再次 poll 的同步关闭。
|
||||
use super::*;
|
||||
use futures_util::Stream;
|
||||
use std::future::poll_fn;
|
||||
|
||||
pub(super) struct SharedDownload<S>(Arc<Shared<S>>);
|
||||
struct Shared<S> {
|
||||
source: Mutex<Option<Pin<Box<S>>>>,
|
||||
reading: tokio::sync::Mutex<()>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
impl<S> Clone for SharedDownload<S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
impl<S> SharedDownload<S> {
|
||||
pub fn new(source: S) -> Self {
|
||||
Self(Arc::new(Shared {
|
||||
source: Mutex::new(Some(Box::pin(source))),
|
||||
reading: tokio::sync::Mutex::new(()),
|
||||
closed: CancellationToken::new(),
|
||||
}))
|
||||
}
|
||||
pub fn close(&self) {
|
||||
self.0.closed.cancel();
|
||||
// panic 后也必须释放源;已经关闭的 next 直接由取消通知结束。
|
||||
let source = self
|
||||
.0
|
||||
.source
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take();
|
||||
drop(source);
|
||||
}
|
||||
pub fn close_on_drop(&self) -> CloseOnDrop<'_, S> {
|
||||
CloseOnDrop(self)
|
||||
}
|
||||
}
|
||||
impl<S: Stream<Item = io::Result<Bytes>>> SharedDownload<S> {
|
||||
pub async fn next(&self) -> io::Result<Option<Bytes>> {
|
||||
let read = async {
|
||||
let _reader = self.0.reading.lock().await;
|
||||
poll_fn(|cx| {
|
||||
let mut source = self.0.source.lock().unwrap();
|
||||
let value = match source.as_mut() {
|
||||
Some(stream) => stream.as_mut().poll_next(cx),
|
||||
None => return Poll::Ready(Ok(None)),
|
||||
};
|
||||
if matches!(value, Poll::Ready(None | Some(Err(_)))) {
|
||||
source.take();
|
||||
}
|
||||
value.map(Option::transpose)
|
||||
})
|
||||
.await
|
||||
};
|
||||
match self.0.closed.run_until_cancelled(read).await {
|
||||
Some(value) => value,
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) struct CloseOnDrop<'a, S>(&'a SharedDownload<S>);
|
||||
impl<S> Drop for CloseOnDrop<'_, S> {
|
||||
fn drop(&mut self) {
|
||||
self.0.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
use super::*;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn single_call_rejects_invalid_send_before_connect() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
for request in [
|
||||
Request::builder()
|
||||
.uri("http://other.test/")
|
||||
.header("host", "localhost")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "localhost")
|
||||
.header("host", "other")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "localhost")
|
||||
.header("content-length", "0")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "localhost")
|
||||
.header("x-large", "a".repeat(8192))
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "localhost")
|
||||
.body(Full::new(Bytes::from(vec![0; 1048577])))
|
||||
.unwrap(),
|
||||
] {
|
||||
assert!(single::send(address, request).await.is_err());
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_single_call_releases_socket_without_detached_driver() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let (sent, received) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(socket.read_u8().await.unwrap());
|
||||
}
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
sent.send(()).unwrap();
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(1), socket.read(&mut [0]))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
});
|
||||
{
|
||||
let request = Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "localhost")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap();
|
||||
let work = single::send(address, request);
|
||||
tokio::pin!(work);
|
||||
tokio::select! {
|
||||
result = received => result.unwrap(),
|
||||
result = &mut work => panic!("body should remain pending: {result:?}"),
|
||||
}
|
||||
}
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sending_rejects_foreign_origin_headers_and_oversized_body_before_connect() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
|
||||
let uri = format!("http://127.0.0.1:{port}/echo");
|
||||
for request in [
|
||||
Request::builder()
|
||||
.uri("http://other.test/echo")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri(&uri)
|
||||
.header("Host", "other.test")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri(&uri)
|
||||
.header("Transfer-Encoding", "chunked")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri(&uri)
|
||||
.header("x-large", "a".repeat(8192))
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
Request::builder()
|
||||
.uri(&uri)
|
||||
.body(Full::new(Bytes::from(vec![0; 1048577])))
|
||||
.unwrap(),
|
||||
] {
|
||||
assert!(pool.request(request).await.is_err());
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(pool.requests.available_permits(), 1);
|
||||
assert_eq!(pool.physical.available_permits(), 1);
|
||||
pool.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_listener_stop_drains_but_owner_cancel_releases_pending_requests() {
|
||||
for graceful in [true, false] {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let owner = Owner::default();
|
||||
let stop = CancellationToken::new();
|
||||
let serving = tokio::spawn(server::serve(listener, stop.clone(), owner.clone()));
|
||||
let mut socket = TcpStream::connect(address).await.unwrap();
|
||||
socket.write_all(b"POST /echo HTTP/1.1\r\nHost: localhost\r\nContent-Length: 3\r\nExpect: 100-continue\r\n\r\n").await.unwrap();
|
||||
let mut interim = [0; 25];
|
||||
tokio::time::timeout(Duration::from_secs(1), socket.read_exact(&mut interim))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n");
|
||||
if graceful {
|
||||
stop.cancel();
|
||||
socket.write_all(b"abc").await.unwrap();
|
||||
} else {
|
||||
owner.cancel.cancel();
|
||||
}
|
||||
let mut response = Vec::new();
|
||||
tokio::time::timeout(Duration::from_secs(1), socket.read_to_end(&mut response))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if graceful {
|
||||
assert!(response.starts_with(b"HTTP/1.1 200 OK\r\n"));
|
||||
assert!(response.ends_with(b"abc"));
|
||||
} else {
|
||||
assert!(response.is_empty());
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(1), serving)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(owner.tasks.is_empty());
|
||||
assert!(owner.take_faults().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_cancels_pending_body_and_drains_real_socket() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let peer = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut bytes = [0; 2048];
|
||||
assert!(socket.read(&mut bytes).await.unwrap() > 0);
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(socket.read(&mut bytes).await.unwrap(), 0);
|
||||
});
|
||||
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
|
||||
let request = Request::builder()
|
||||
.uri(format!("http://127.0.0.1:{port}/"))
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap();
|
||||
let (_, download) = pool.open(request).await.unwrap();
|
||||
assert_eq!(download.next().await.unwrap().unwrap(), "abc");
|
||||
assert_eq!(pool.requests.available_permits(), 0);
|
||||
let pending = download.next();
|
||||
tokio::pin!(pending);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), &mut pending)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
pool.close().await;
|
||||
assert_eq!(
|
||||
pending.await.unwrap_err().kind(),
|
||||
io::ErrorKind::NotConnected
|
||||
);
|
||||
assert!(download.next().await.unwrap().is_none());
|
||||
assert_eq!(pool.requests.available_permits(), 1);
|
||||
assert_eq!(pool.physical.available_permits(), 1);
|
||||
assert!(pool.owner.tasks.is_empty());
|
||||
tokio::time::timeout(Duration::from_secs(1), peer)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tracker_preserves_panics_and_waits_for_destruction() {
|
||||
use hyper::rt::Executor;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
struct Guard(Arc<AtomicBool>);
|
||||
impl Drop for Guard {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let owner = Owner::default();
|
||||
let destroyed = Arc::new(AtomicBool::new(false));
|
||||
let guard = Guard(destroyed.clone());
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
owner.execute(async move {
|
||||
let _guard = guard;
|
||||
started.send(()).unwrap();
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
ready.await.unwrap();
|
||||
owner.execute(async {
|
||||
panic!("original protocol failure");
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
owner.close().await;
|
||||
assert!(destroyed.load(Ordering::SeqCst));
|
||||
assert!(owner.tasks.is_empty());
|
||||
let faults = owner.take_faults();
|
||||
assert_eq!(faults.len(), 1);
|
||||
assert_eq!(
|
||||
faults[0].downcast_ref::<&str>(),
|
||||
Some(&"original protocol failure")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn physical_permit_lives_until_transport_drop() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let slots = Arc::new(Semaphore::new(1));
|
||||
let mut connector = Connector {
|
||||
tcp: HttpConnector::new_with_resolver(FixedDns(Arc::new(vec![address]))),
|
||||
slots: slots.clone(),
|
||||
};
|
||||
let uri: Uri = format!("http://{address}/").parse().unwrap();
|
||||
let first = connector.call(uri.clone()).await.unwrap();
|
||||
let (first_peer, _) = listener.accept().await.unwrap();
|
||||
let second = connector.call(uri);
|
||||
tokio::pin!(second);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), &mut second)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(slots.available_permits(), 0);
|
||||
drop(first);
|
||||
let second = tokio::time::timeout(Duration::from_secs(1), second)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (second_peer, _) = listener.accept().await.unwrap();
|
||||
drop(second);
|
||||
assert_eq!(slots.available_permits(), 1);
|
||||
drop((first_peer, second_peer));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn body_aliases_share_cursor_and_close_releases_an_unpolled_pending_read() {
|
||||
for early in [true, false] {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let peer = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0; 2048];
|
||||
assert!(socket.read(&mut request).await.unwrap() > 0);
|
||||
let length = if early { 10 } else { 70000 };
|
||||
socket
|
||||
.write_all(
|
||||
format!("HTTP/1.1 200 OK\r\nContent-Length: {length}\r\n\r\n").as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
socket
|
||||
.write_all(&vec![b'x'; if early { 3 } else { length }])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(socket.read(&mut request).await.unwrap(), 0);
|
||||
});
|
||||
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
|
||||
let request = Request::builder()
|
||||
.uri(format!("http://127.0.0.1:{port}/"))
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap();
|
||||
let (_, body) = pool.open(request).await.unwrap();
|
||||
let alias = body.clone();
|
||||
let first = body.next().await.unwrap().unwrap();
|
||||
assert!(first.len() <= 65536 && first.iter().all(|byte| *byte == b'x'));
|
||||
if early {
|
||||
assert_eq!(first, "xxx");
|
||||
let pending = body.next();
|
||||
tokio::pin!(pending);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), &mut pending)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
alias.close();
|
||||
// 不先 poll pending:同步 close 返回时必须已经归还正文许可。
|
||||
assert_eq!(pool.requests.available_permits(), 1);
|
||||
assert!(pending.await.unwrap().is_none());
|
||||
} else {
|
||||
let mut size = first.len();
|
||||
while let Some(chunk) = alias.next().await.unwrap() {
|
||||
assert!(chunk.len() <= 65536 && chunk.iter().all(|byte| *byte == b'x'));
|
||||
size += chunk.len();
|
||||
}
|
||||
assert_eq!(size, 70000);
|
||||
assert_eq!(pool.requests.available_permits(), 1);
|
||||
}
|
||||
assert!(body.next().await.unwrap().is_none());
|
||||
pool.close().await;
|
||||
assert_eq!(pool.physical.available_permits(), 1);
|
||||
tokio::time::timeout(Duration::from_secs(1), peer)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_panicked_shared_source_preserves_fault_and_releases_it() {
|
||||
async fn broken() -> io::Result<Bytes> {
|
||||
panic!("original body fault");
|
||||
}
|
||||
let body = streaming::SharedDownload::new(futures_util::stream::once(broken()));
|
||||
let fault = AssertUnwindSafe(body.next())
|
||||
.catch_unwind()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(fault.downcast_ref::<&str>(), Some(&"original body fault"));
|
||||
body.close();
|
||||
assert!(body.next().await.unwrap().is_none());
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,310 @@
|
||||
"""固定七轮交错 HTTP/1 服务负载;逐个校验响应并保留吞吐与延迟原样本。"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import shutil
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
from http_server_reference import source
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--compiler', type=Path, required=True)
|
||||
parser.add_argument('--core-source', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--size', type=int, default=100000)
|
||||
parser.add_argument('--server-cpu', type=int, default=0)
|
||||
parser.add_argument('--client-cpu', default='1,2,3', help='comma-separated dedicated client CPUs')
|
||||
parser.add_argument('--baseline', type=Path)
|
||||
parser.add_argument('--resource-reference', type=Path)
|
||||
parser.add_argument('--automatic-api', action='store_true', help='measure generated public JSON API through api::serve')
|
||||
parser.add_argument('--old-compiler', type=Path, help='frozen old compiler for the same automatic API workload')
|
||||
parser.add_argument('--runtime-baseline', type=Path, help='runtime source directory for a same-generated-code causal comparison')
|
||||
args = parser.parse_args()
|
||||
if args.size < 1 or str(args.server_cpu) in args.client_cpu.split(','):
|
||||
parser.error('positive size and separate server/client CPUs are required')
|
||||
if (args.old_compiler or args.runtime_baseline) and not args.automatic_api:
|
||||
parser.error('old compiler and runtime baseline require --automatic-api')
|
||||
if args.automatic_api and args.resource_reference:
|
||||
parser.error('the raw echo resource reference does not implement automatic JSON API')
|
||||
core = args.core_source.resolve(strict=True)
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
os.environ['CARGO_BUILD_JOBS'] = '1'
|
||||
os.environ['GOMAXPROCS'] = '1'
|
||||
os.environ['GOTOOLCHAIN'] = 'local'
|
||||
report = dict(compiler_sha256=fingerprint(compiler), size=args.size, concurrency=32,
|
||||
server_cpu=args.server_cpu, client_cpu=args.client_cpu,
|
||||
semantics='HTTP/1 keep-alive, 32 clients, varying body, every status and byte checked. The same native Go driver on dedicated CPUs. One excluded round then seven interleaved rounds. Every client run has 1024 untimed warmup requests. Rust uses the same locked Hyper/Tokio without Dever runtime; Go uses net/http. Successful echo only: no equivalent child-task faults, saturation, TLS or HTTP/2 performance claim.',
|
||||
environment={name: Path('/sys/fs/cgroup', name).read_text().strip() for name in ['cpu.max', 'memory.max']},
|
||||
builds=[], samples=[], versions={}, source_hashes={})
|
||||
report['automatic_api'] = args.automatic_api
|
||||
if args.automatic_api:
|
||||
report['semantics'] = ('Public POST JSON {value:Text} -> {code:0,message:ok,data:Text}, 32 keep-alive clients, '
|
||||
'all statuses and complete responses checked; one warmup then seven rotated rounds. '
|
||||
'Dever uses generated api::serve. Independent Rust/Go use Hyper/Tokio and net/http; '
|
||||
'successful JSON path only, no equivalence claim for authentication, cancellation, failure logs or graceful drain. '
|
||||
'Go JSON decoding does not reject duplicate keys; that unsupported parity is not measured.')
|
||||
def save():
|
||||
(root / 'results.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
inputs = [*core.joinpath('rust/src').rglob('*.rs'), *core.joinpath('lib').rglob('*.dv'),
|
||||
core/'rust/Cargo.toml', core/'rust/src/runtime/Cargo.toml', core/'rust/Cargo.lock',
|
||||
Path(__file__).resolve(), Path(__file__).with_name('http_server_reference.py').resolve(),
|
||||
Path(__file__).with_name('http_server_client.go').resolve()]
|
||||
for path in inputs:
|
||||
relative = str(path.relative_to(core))
|
||||
report['source_hashes'][relative] = fingerprint(path)
|
||||
saved = root/'inputs'/relative
|
||||
saved.parent.mkdir(parents=True, exist_ok=True)
|
||||
saved.write_bytes(path.read_bytes())
|
||||
locked = {(p['name'], p['version'], p.get('source')) for p in tomllib.loads((core/'rust/Cargo.lock').read_text())['package']}
|
||||
client = root/'client'
|
||||
report['client_build'] = execute(['go', 'build', '-trimpath', '-o', str(client), str(inputs[-1])], root, 'client-build', 120)
|
||||
save()
|
||||
if report['client_build']['exit_code']:
|
||||
raise RuntimeError(report['client_build'])
|
||||
report['client_sha256'] = fingerprint(client)
|
||||
programs = {}
|
||||
for name, command in [('rust', ['rustc', '+1.95.0', '--version', '--verbose']), ('go', ['go', 'version'])]:
|
||||
result = execute(command, root, name+'-version', 30)
|
||||
report['versions'][name] = result
|
||||
save()
|
||||
if result['exit_code']:
|
||||
raise RuntimeError(result)
|
||||
for language in ['dever', 'rust', 'go'] + (['old'] if args.old_compiler else []):
|
||||
case = root/language
|
||||
case.mkdir()
|
||||
dever = language in ['dever', 'old']
|
||||
project = case / 'project' if args.automatic_api and dever else case
|
||||
if args.automatic_api and dever:
|
||||
domain = project / 'module/benchmark/echo'
|
||||
path = domain / ('app/main.dever' if language == 'dever' else 'app.dever')
|
||||
else:
|
||||
path = case / ('main.' + {'dever': 'dever', 'old': 'dever', 'rust': 'rs', 'go': 'go'}[language])
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(source('dever' if dever else language, args.automatic_api))
|
||||
if args.automatic_api and dever:
|
||||
api = domain/'api/front/main.dever'
|
||||
api.parent.mkdir(parents=True)
|
||||
api.write_text('public post echo = app.echo' + chr(10))
|
||||
binary = case/'program'
|
||||
if dever:
|
||||
tool = args.old_compiler.resolve(strict=True) if language == 'old' else compiler
|
||||
formatted = execute([str(tool), 'fmt', str(project if args.automatic_api else path)], case, 'fmt', 30)
|
||||
if formatted['exit_code']:
|
||||
raise RuntimeError(formatted)
|
||||
command = [str(tool), 'build', str(project if args.automatic_api else path), '--output', str(binary)]
|
||||
elif language == 'rust':
|
||||
(case/'Cargo.toml').write_text('''[package]
|
||||
name = "http-server-reference"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "http-server-reference"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
bytes = "=1.12.1"
|
||||
tokio = { version = "=1.53.1", features = ["rt", "net", "time", "macros", "sync", "io-util"] }
|
||||
futures-util = { version = "=0.3.34", default-features = false, features = ["std"] }
|
||||
hyper = { version = "=1.11.1", features = ["http1", "http2", "client", "server"] }
|
||||
hyper-util = { version = "=0.1.20", features = ["tokio"] }
|
||||
http-body-util = "=0.1.5"
|
||||
serde = { version = "=1.0.228", features = ["derive"] }
|
||||
serde_json = "=1.0.145"
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = "symbols"
|
||||
''')
|
||||
(case/'Cargo.lock').write_bytes((core/'rust/Cargo.lock').read_bytes())
|
||||
command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case/'Cargo.toml'), '--offline', '--release', '--target-dir', str(core/'target/next-cargo')]
|
||||
binary = core/'target/next-cargo/release/http-server-reference'
|
||||
else:
|
||||
(case/'go.mod').write_text('module http-server-reference\n\ngo 1.25.0\n')
|
||||
command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-ldflags=-s -w', '-o', str(binary), '.']
|
||||
build = dict(language=language, source_sha256=fingerprint(path), source_lines=len(path.read_text().splitlines()), **execute(command, case, 'build', 900))
|
||||
report['builds'].append(build)
|
||||
save()
|
||||
if build['exit_code']:
|
||||
raise RuntimeError(build)
|
||||
if language == 'rust':
|
||||
shutil.copy2(binary, case/'program')
|
||||
binary = case/'program'
|
||||
build['binary_sha256'] = fingerprint(binary)
|
||||
if language == 'rust':
|
||||
packages = tomllib.loads((case/'Cargo.lock').read_text())['package']
|
||||
build['dependency_differences'] = [(p['name'], p['version'], p.get('source')) for p in packages if p.get('source') and (p['name'], p['version'], p['source']) not in locked]
|
||||
build['lock_sha256'] = fingerprint(case/'Cargo.lock')
|
||||
if build['dependency_differences']:
|
||||
save()
|
||||
raise RuntimeError('reference dependency versions differ')
|
||||
programs[language] = binary
|
||||
if dever:
|
||||
build['compiler_sha256'] = fingerprint(tool)
|
||||
build['business_sources'] = {str(p.relative_to(project)): dict(sha256=fingerprint(p), lines=len(p.read_text().splitlines())) for p in project.rglob('*.dever')}
|
||||
save()
|
||||
if args.runtime_baseline:
|
||||
programs['runtime_baseline'] = build_runtime_baseline(core, root, args.runtime_baseline, report, save)
|
||||
if args.baseline:
|
||||
baseline = args.baseline.resolve(strict=True)
|
||||
programs['previous'] = baseline
|
||||
(root/'previous').mkdir()
|
||||
report['baseline'] = dict(binary=str(baseline), sha256=fingerprint(baseline))
|
||||
save()
|
||||
if args.resource_reference:
|
||||
binary = args.resource_reference.resolve(strict=True)
|
||||
project = binary.parents[2]
|
||||
paths = [*sorted(project.glob('http_resource_*.rs')), project / 'Cargo.toml', project / 'Cargo.lock']
|
||||
report['resource_reference'] = dict(binary=str(binary), sha256=fingerprint(binary),
|
||||
sources={str(path): fingerprint(path) for path in paths},
|
||||
contract='32 active connections; header/body/handler deadlines; bounded body/headers; handler panic isolation and error logs; tracked connection tasks; owner cancellation and listener graceful drain. Pure echo route only, no child-task/TLS/H2 performance equivalence claimed.')
|
||||
programs['resource'] = binary
|
||||
(root / 'resource').mkdir()
|
||||
save()
|
||||
measure(args, core, root, programs, report, save, client)
|
||||
|
||||
|
||||
def measure(args, core, root, programs, report, save, client):
|
||||
binaries = {name:dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size) for name,path in programs.items()}
|
||||
if report.get('binaries') and report['binaries'] != binaries:
|
||||
raise RuntimeError('measured binaries changed; results from different identities cannot be resumed together')
|
||||
report['binaries'] = binaries
|
||||
save()
|
||||
for repeat in range(-1, 7):
|
||||
if any(fingerprint(path) != binaries[name]['sha256'] for name,path in programs.items()):
|
||||
raise RuntimeError('binary changed during benchmark')
|
||||
for relative, sha in report['source_hashes'].items():
|
||||
if fingerprint(core/relative) != sha:
|
||||
raise RuntimeError('source changed during benchmark: '+relative)
|
||||
for path, sha in report.get('resource_reference', {}).get('sources', {}).items():
|
||||
if fingerprint(Path(path)) != sha:
|
||||
raise RuntimeError('resource reference changed during benchmark: '+path)
|
||||
order = list(programs)
|
||||
order = order[repeat % len(order):] + order[:repeat % len(order)]
|
||||
for language in order:
|
||||
if any(row['language'] == language and row['repeat'] == repeat and row.get('count') == args.size for row in report['samples']):
|
||||
continue
|
||||
case = root/language
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(('127.0.0.1', 0))
|
||||
port = reservation.getsockname()[1]
|
||||
configuration = case/f'setting-{repeat}.json'
|
||||
settings = {'http': {'host':'127.0.0.1', 'port':port}, 'sites': {'front': {'path':'front','hosts':['127.0.0.1']}}} if args.automatic_api else {'module': {'main': {'main': {'port': port}}}}
|
||||
configuration.write_text(json.dumps(settings))
|
||||
dever = language in ['dever', 'previous', 'old', 'runtime_baseline']
|
||||
command = [str(programs[language]), '--config', str(configuration), *(['api'] if args.automatic_api else ['main.main.server', '{}'])] if dever else [str(programs[language]), str(port)]
|
||||
if language == 'old':
|
||||
command = [str(programs[language]), '--config', str(configuration)]
|
||||
if language == 'resource':
|
||||
command = [str(programs[language]), 'server', str(port)]
|
||||
stdout = case/f'server-{repeat}.stdout'
|
||||
stderr = case/f'server-{repeat}.stderr'
|
||||
with stdout.open('wb') as out, stderr.open('wb') as err:
|
||||
process = subprocess.Popen(['taskset', '-c', str(args.server_cpu), *command], stdout=out, stderr=err)
|
||||
try:
|
||||
deadline = time.monotonic() + 10
|
||||
while True:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError(f'{language} exited before listening: {stderr.read_text()}')
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1', port), timeout=.1):
|
||||
break
|
||||
except ConnectionRefusedError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('server did not listen')
|
||||
time.sleep(.01)
|
||||
before = cpu_seconds(process.pid)
|
||||
if args.automatic_api and repeat == -1:
|
||||
report.setdefault('functional', {})[language] = api_contract(port)
|
||||
save()
|
||||
result = execute(['taskset', '-c', str(args.client_cpu), 'env', '-u', 'GOMAXPROCS', str(client), str(port), str(args.size), 'api' if args.automatic_api else 'echo'], case, f'client-{repeat}', 120)
|
||||
row = dict(language=language, repeat=repeat, server_cpu_seconds_including_warmup=cpu_seconds(process.pid)-before,
|
||||
server_peak_rss_kib=peak_rss(process.pid), **result)
|
||||
report['samples'].append(row)
|
||||
save()
|
||||
if result['exit_code']:
|
||||
raise RuntimeError(result)
|
||||
row.update(json.loads(Path(result['stdout']).read_text()))
|
||||
if row['count'] != args.size or process.poll() is not None:
|
||||
raise RuntimeError('incomplete request workload or server exited')
|
||||
save()
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
raise
|
||||
report['medians'] = {language: {key: statistics.median(row[key] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0)
|
||||
for key in ['seconds', 'requests_per_second', 'p50_ms', 'p95_ms', 'p99_ms', 'server_cpu_seconds_including_warmup', 'server_peak_rss_kib']} for language in programs}
|
||||
save()
|
||||
print(json.dumps(report['medians'], indent=2))
|
||||
|
||||
|
||||
def build_runtime_baseline(core, root, runtime, report, save):
|
||||
runtime = runtime.resolve(strict=True)
|
||||
identity = hashlib.sha256(os.fsencode((root/'dever/project').resolve())).hexdigest()
|
||||
generated = core/'rust/target/generated'/('dever-program-'+identity)/'x86_64'
|
||||
case = root/'runtime_baseline'
|
||||
shutil.copytree(generated, case, ignore=shutil.ignore_patterns('build.lock'))
|
||||
manifest = case/'Cargo.toml'
|
||||
manifest.write_text(manifest.read_text().replace(str(core/'rust/src/runtime'), str(runtime)))
|
||||
row = dict(language='runtime_baseline', sources={str(p):fingerprint(p) for p in runtime.rglob('*.rs')},
|
||||
**execute(['cargo','+1.95.0','build','--manifest-path',str(manifest),'--locked','--offline','--release',
|
||||
'--target-dir',str(core/'target/next-cargo')],case,'build',900))
|
||||
report['builds'].append(row)
|
||||
save()
|
||||
if row['exit_code']:
|
||||
raise RuntimeError(row)
|
||||
binary = case/'program'
|
||||
shutil.copy2(core/'target/next-cargo/release'/('dever-program-'+identity), binary)
|
||||
row['binary_sha256'] = fingerprint(binary)
|
||||
save()
|
||||
return binary
|
||||
|
||||
|
||||
def api_contract(port):
|
||||
results = []
|
||||
for body, expected in [('{}',400), ('{"value":null}',400), ('{"value":1}',400),
|
||||
('{"value":"x","extra":1}',400), ('{"value":"x"} {}',400),
|
||||
(json.dumps({'value':'中文 " 雪'}),200)]:
|
||||
client = http.client.HTTPConnection('127.0.0.1', port, timeout=5)
|
||||
try:
|
||||
client.request('POST','/benchmark/echo/front/main/echo',body.encode(),{'content-type':'application/json'})
|
||||
reply = client.getresponse()
|
||||
data = reply.read().decode()
|
||||
results.append(dict(body=body, expected_status=expected, status=reply.status, response=data))
|
||||
if reply.status != expected:
|
||||
raise AssertionError(results[-1])
|
||||
if expected == 200:
|
||||
assert json.loads(data) == dict(code=0, message='ok', data=json.loads(body)['value'])
|
||||
finally:
|
||||
client.close()
|
||||
return results
|
||||
|
||||
|
||||
def cpu_seconds(pid):
|
||||
# 仅读取本任务子进程的 CPU 计数,不需要 perf 权限。
|
||||
fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
|
||||
return (int(fields[11]) + int(fields[12])) / os.sysconf('SC_CLK_TCK')
|
||||
|
||||
|
||||
def peak_rss(pid):
|
||||
status = Path(f'/proc/{pid}/status').read_text().splitlines()
|
||||
return int(next(line for line in status if line.startswith('VmHWM:')).split()[1])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
// 压测客户端只使用 Go 标准库,逐条核对响应,避免驱动成为服务端吞吐上限。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const concurrency = 32
|
||||
|
||||
func run(client *http.Client, url string, api bool, count int, samples []float64) time.Duration {
|
||||
var workers sync.WaitGroup
|
||||
started := time.Now()
|
||||
for lane := range concurrency {
|
||||
workers.Go(func() {
|
||||
var received bytes.Buffer
|
||||
for i := lane; i < count; i += concurrency {
|
||||
text := strings.Repeat(strconv.Itoa(i), 8)
|
||||
body, expected := text, text
|
||||
if api {
|
||||
body = "{\"value\":\"" + text + "\"}"
|
||||
expected = "{\"code\":0,\"message\":\"ok\",\"data\":\"" + text + "\"}"
|
||||
}
|
||||
begin := time.Now()
|
||||
request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(body))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("User-Agent", "")
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
received.Reset()
|
||||
_, err = received.ReadFrom(response.Body)
|
||||
response.Body.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if response.StatusCode != http.StatusOK || received.String() != expected {
|
||||
panic(fmt.Sprintf("request %d: %s %q", i, response.Status, received.Bytes()))
|
||||
}
|
||||
if samples != nil {
|
||||
samples[i] = float64(time.Since(begin)) / float64(time.Millisecond)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
workers.Wait()
|
||||
return time.Since(started)
|
||||
}
|
||||
|
||||
func main() {
|
||||
port, countText, api := os.Args[1], os.Args[2], os.Args[3] == "api"
|
||||
count, err := strconv.Atoi(countText)
|
||||
if err != nil || count < 1 {
|
||||
panic("request count must be positive")
|
||||
}
|
||||
path := "/echo"
|
||||
if api {
|
||||
path = "/benchmark/echo/front/main/echo"
|
||||
}
|
||||
url := "http://127.0.0.1:" + port + path
|
||||
transport := &http.Transport{
|
||||
MaxConnsPerHost: concurrency, MaxIdleConnsPerHost: concurrency, DisableCompression: true,
|
||||
}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
|
||||
run(client, url, api, 1024, nil)
|
||||
samples := make([]float64, count)
|
||||
seconds := run(client, url, api, count, samples).Seconds()
|
||||
slices.Sort(samples)
|
||||
percentile := func(p float64) float64 { return samples[int(math.Ceil(p*float64(count)))-1] }
|
||||
if err := json.NewEncoder(os.Stdout).Encode(map[string]float64{
|
||||
"count": float64(count), "seconds": seconds, "requests_per_second": float64(count) / seconds,
|
||||
"p50_ms": percentile(.50), "p95_ms": percentile(.95), "p99_ms": percentile(.99),
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
"""HTTP/1 持久连接回显:对端使用成熟库,独立 Rust 不依赖 Dever runtime。"""
|
||||
|
||||
|
||||
def source(language, automatic_api=False):
|
||||
if language == 'dever':
|
||||
if automatic_api:
|
||||
return 'echo(value: Text) (out: Text) { out = value }\n'
|
||||
return '''setting port: Int
|
||||
echo(request: dever.http.Request) (response: dever.http.Response) {
|
||||
response = dever.http.Response { status = 200, headers = [], body = request.body }
|
||||
}
|
||||
flow start() ()
|
||||
| step | kind | do |
|
||||
| listener | flow | dever.net.listen("127.0.0.1", port) |
|
||||
| - | flow | dever.http.serve(echo, listener, dever.http.defaultLimits()) |
|
||||
cmd server = start
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::Bytes;
|
||||
use futures_util::{TryStreamExt, stream};
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::{body::Incoming, service::service_fn};
|
||||
use hyper_util::rt::{TokioIo, TokioTimer};
|
||||
use std::{convert::Infallible, time::Duration};
|
||||
async fn reply(request: hyper::Request<Incoming>) -> Result<hyper::Response<Full<Bytes>>, Infallible> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let size = parts.method.as_str().len() + parts.uri.path_and_query().unwrap().as_str().len() + 16
|
||||
+ parts.headers.iter().map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4).sum::<usize>();
|
||||
let mut hosts = parts.headers.get_all("host").iter();
|
||||
let host = hosts.next().unwrap().to_str().unwrap().parse::<hyper::http::uri::Authority>().unwrap();
|
||||
assert!(hosts.next().is_none() && !host.as_str().contains('@'));
|
||||
assert!(size <= 8192 && parts.uri.path().starts_with('/') && parts.uri.authority().is_none());
|
||||
let body = tokio::time::timeout(Duration::from_secs(5), Limited::new(body, 1048576).collect()).await.unwrap().unwrap().to_bytes();
|
||||
/* reply */
|
||||
}
|
||||
fn main() {
|
||||
let port: u16 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
||||
stream::try_unfold((), |()| async { listener.accept().await.map(|(stream, _)| Some((stream, ()))) })
|
||||
.try_for_each_concurrent(32, |stream| async move {
|
||||
stream.set_nodelay(true)?;
|
||||
hyper::server::conn::http1::Builder::new().timer(TokioTimer::new())
|
||||
.header_read_timeout(Duration::from_secs(5)).max_buf_size(8192)
|
||||
.serve_connection(TokioIo::new(stream), service_fn(reply)).await.map_err(std::io::Error::other)
|
||||
}).await.unwrap();
|
||||
});
|
||||
}
|
||||
'''.replace('/* reply */', RUST_API if automatic_api else 'Ok(hyper::Response::new(Full::new(body)))')
|
||||
if language != 'go':
|
||||
raise ValueError(language)
|
||||
return '''package main
|
||||
import ("fmt"; "io"; "net/http"; "os"; "strconv"; "time" /* imports */)
|
||||
func main() {
|
||||
port, err := strconv.Atoi(os.Args[1]); if err != nil { panic(err) }
|
||||
server := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", port), MaxHeaderBytes: 8192, ReadHeaderTimeout: 5*time.Second, ReadTimeout: 5*time.Second,
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1048576)); if err != nil { panic(err) }
|
||||
/* reply */
|
||||
w.Header()["Date"] = nil
|
||||
/* content-type */
|
||||
w.WriteHeader(200)
|
||||
if _, err := w.Write(data); err != nil { panic(err) }
|
||||
})}
|
||||
if err := server.ListenAndServe(); err != nil { panic(err) }
|
||||
}
|
||||
'''.replace('/* imports */', '; "bytes"; "encoding/json"' if automatic_api else '').replace('/* reply */', GO_API if automatic_api else '').replace('/* content-type */', '' if automatic_api else 'w.Header()["Content-Type"] = nil')
|
||||
|
||||
|
||||
# 参考只比较公开 JSON 成功路径,不冒充完整鉴权、任务故障与取消合同。
|
||||
RUST_API = '''
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input { value: String }
|
||||
#[derive(serde::Serialize)]
|
||||
struct Reply<'a> { code: u16, message: &'static str, data: Option<&'a str> }
|
||||
let input = serde_json::from_slice::<Input>(&body);
|
||||
let (status, message, data) = if host.host() != "127.0.0.1" || parts.uri.path() != "/benchmark/echo/front/main/echo" {
|
||||
(404, "not found", None)
|
||||
} else if parts.method != hyper::Method::POST {
|
||||
(405, "method not allowed", None)
|
||||
} else {
|
||||
match &input {
|
||||
Ok(input) => (200, "ok", Some(input.value.as_str())),
|
||||
Err(_) => (400, "invalid request", None),
|
||||
}
|
||||
};
|
||||
Ok(hyper::Response::builder().status(status).header("content-type", "application/json; charset=utf-8")
|
||||
.body(Full::new(Bytes::from(serde_json::to_vec(&Reply{code:if status==200 {0} else {status},message,data}).unwrap()))).unwrap())
|
||||
'''
|
||||
|
||||
GO_API = '''
|
||||
if r.Host != "127.0.0.1:"+strconv.Itoa(port) || r.URL.Path != "/benchmark/echo/front/main/echo" {
|
||||
http.Error(w, "not found", 404); return
|
||||
}
|
||||
if r.Method != "POST" { http.Error(w, "method not allowed", 405); return }
|
||||
var input struct { Value *string `json:"value"` }
|
||||
decoder := json.NewDecoder(bytes.NewReader(data)); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil || input.Value == nil {
|
||||
http.Error(w, "invalid request", 400); return
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF { http.Error(w, "invalid request", 400); return }
|
||||
data, err = json.Marshal(struct { Code int `json:"code"`; Message string `json:"message"`; Data string `json:"data"` }{0,"ok",*input.Value})
|
||||
if err != nil { panic(err) }
|
||||
w.Header().Set("content-type", "application/json; charset=utf-8")
|
||||
'''
|
||||
@@ -0,0 +1,59 @@
|
||||
"""同一连接池逐帧下载并验证每个字节;独立对端不使用 Dever 运行库。"""
|
||||
from http_pool_reference import source as pool_source
|
||||
|
||||
|
||||
def source(language):
|
||||
base = pool_source(language)
|
||||
if language == "dever":
|
||||
helpers = '''checkedChunk(offset: Int, bytes: Bytes, expected: Bytes) (next: Int) {
|
||||
next = offset + length(bytes)
|
||||
check bytes == dever.bytes.slice(expected, offset, next) else Invalid
|
||||
}
|
||||
rule piece(offset: Int, event: dever.io.ReadEvent, expected: Bytes) (next: Int)
|
||||
| offset | event | expected | next |
|
||||
| - | Chunk(bytes) | - | checkedChunk(offset, bytes, expected) |
|
||||
| - | Failed(message) | - | fail(dever.io.ReadEvent.Failed(message)) |
|
||||
loop download(body: AsyncStream<dever.io.ReadEvent>, expected: Bytes) (size: Int)
|
||||
| each event in body | result |
|
||||
| size | fold(offset = 0, piece(offset, event, expected)) |
|
||||
'''
|
||||
return helpers + base.replace("dever.http.request(client, request)", "dever.http.open(client, request)").replace(
|
||||
"| - | check | response.body == body else Invalid |",
|
||||
"| size | loop | download(response.body, body) |\n| - | check | size == length(body) else Invalid |")
|
||||
if language == "rust":
|
||||
base = base.replace("tokio::time::timeout(Duration::from_secs(5), async {", "{").replace(
|
||||
"let response = client.request(request).await.unwrap();",
|
||||
"let response = tokio::time::timeout(Duration::from_secs(5), client.request(request)).await.unwrap().unwrap();").replace(
|
||||
" }).await.unwrap();", " }")
|
||||
return base.replace("BodyExt, Full, Limited", "BodyExt, Full").replace(
|
||||
"let response = Limited::new(response.into_body(), 1048576).collect().await.unwrap().to_bytes();\n assert_eq!(response, body);",
|
||||
'''let mut incoming = response.into_body();
|
||||
let mut offset = 0;
|
||||
while let Some(frame) = tokio::time::timeout(Duration::from_secs(60), incoming.frame()).await.unwrap() {
|
||||
if let Ok(chunk) = frame.unwrap().into_data() {
|
||||
let end = offset + chunk.len();
|
||||
assert_eq!(chunk, body.slice(offset..end));
|
||||
offset = end;
|
||||
}
|
||||
}
|
||||
assert_eq!(offset, body.len());''')
|
||||
if language == "go":
|
||||
base = base.replace(" total := int64(0)", " buffer := make([]byte, 65536)\n total := int64(0)")
|
||||
return base.replace(
|
||||
'''received, err := io.ReadAll(io.LimitReader(response.Body, 1048577)); if err != nil { panic(err) }
|
||||
if err := response.Body.Close(); err != nil { panic(err) }
|
||||
if response.StatusCode != 200 || len(received) > 1048576 || !bytes.Equal(received, body) { panic("response mismatch") }''',
|
||||
'''offset := 0
|
||||
for {
|
||||
count, err := response.Body.Read(buffer)
|
||||
if count > 0 {
|
||||
end := offset + count
|
||||
if end > len(body) || !bytes.Equal(buffer[:count], body[offset:end]) { panic("response mismatch") }
|
||||
offset = end
|
||||
}
|
||||
if err == io.EOF { break }
|
||||
if err != nil { panic(err) }
|
||||
}
|
||||
if err := response.Body.Close(); err != nil { panic(err) }
|
||||
if response.StatusCode != 200 || offset != len(body) { panic("response mismatch") }''')
|
||||
raise ValueError(language)
|
||||
@@ -0,0 +1,295 @@
|
||||
"""同场持久 Job 对照:入队、去重、事务回滚、过期恢复和真实 Worker 退出。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import sqlite3
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def connect(path):
|
||||
return sqlite3.connect(f"file:{path}?mode=rw", uri=True, timeout=30)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--artifacts", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--functional-only", action="store_true",
|
||||
help="verify freshly built peers without repeating timed samples")
|
||||
parser.add_argument("--resource-reference", type=Path,
|
||||
help="add the per-operation independent resource peer; retain the original Rust peer")
|
||||
parser.add_argument("--resource-baseline", type=Path,
|
||||
help="retain the earlier resource peer without per-Job descendant drain")
|
||||
parser.add_argument("--contract-reference", type=Path,
|
||||
help="add independent System declaration/execution checks; retain all lighter peers")
|
||||
parser.add_argument("--current", type=Path,
|
||||
help="measure a candidate alongside the unchanged original new-version binary")
|
||||
parser.add_argument("--intermediate", type=Path,
|
||||
help="retain a previously measured candidate in the same run")
|
||||
args = parser.parse_args()
|
||||
root = args.artifacts.resolve(strict=True)
|
||||
output = args.output.absolute()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
binaries = {"new": root / "new-app", "old": root / "old-app",
|
||||
"rust": root / "rust/target/release/job-peer", "go": root / "go-app"}
|
||||
databases = {name: root / name / "queue.db" for name in ("new", "old")}
|
||||
tables = {"new": "benchmark_queue", "old": "benchmark_queue_model",
|
||||
"rust": "benchmark_queue", "go": "benchmark_queue"}
|
||||
if args.current:
|
||||
binaries["previous"] = binaries["new"]
|
||||
binaries["new"] = args.current.resolve(strict=True)
|
||||
databases["previous"] = databases["new"]
|
||||
tables["previous"] = tables["new"]
|
||||
if args.intermediate:
|
||||
binaries["intermediate"] = args.intermediate.resolve(strict=True)
|
||||
databases["intermediate"] = databases["new"]
|
||||
tables["intermediate"] = tables["new"]
|
||||
references = ["rust", "go"]
|
||||
if args.resource_reference:
|
||||
binaries["rust-resource"] = args.resource_reference.resolve(strict=True)
|
||||
tables["rust-resource"] = "benchmark_queue"
|
||||
references.append("rust-resource")
|
||||
if args.resource_baseline:
|
||||
binaries["rust-resource-baseline"] = args.resource_baseline.resolve(strict=True)
|
||||
tables["rust-resource-baseline"] = "benchmark_queue"
|
||||
references.append("rust-resource-baseline")
|
||||
if args.contract_reference:
|
||||
binaries["rust-contract"] = args.contract_reference.resolve(strict=True)
|
||||
tables["rust-contract"] = "benchmark_queue"
|
||||
references.append("rust-contract")
|
||||
with connect(databases["new"]) as connection:
|
||||
schema = [row[0] for row in connection.execute(
|
||||
"SELECT sql FROM sqlite_master WHERE sql IS NOT NULL AND (tbl_name='_dever_job' OR tbl_name='benchmark_queue') ORDER BY type DESC")]
|
||||
for name in references:
|
||||
databases[name] = output / (name + ".db")
|
||||
with sqlite3.connect(databases[name]) as connection:
|
||||
for sql in schema:
|
||||
connection.execute(sql)
|
||||
sources = [Path(__file__), Path(__file__).with_name("job_build.py")]
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
sources += list(core.joinpath("rust/src").rglob("*.rs"))
|
||||
sources += list(core.joinpath("lib").rglob("*.dv"))
|
||||
sources += [core / "rust/Cargo.toml", core / "rust/src/runtime/Cargo.toml", core / "rust/Cargo.lock"]
|
||||
sources += list(Path(__file__).parent.joinpath("fixtures/job").iterdir())
|
||||
sources += [p for name in ("new", "old") for p in root.joinpath(name, "module").rglob("*.dever")]
|
||||
sources += [root / name for name in ("rust/main.rs", "rust/Cargo.toml", "rust/Cargo.lock", "go/main.go", "go/go.mod", "go/go.sum", "build.json")]
|
||||
# 冻结的早期轻量参考为单文件;新构建提取了共用 SQL,快照须包含实际模块。
|
||||
if (root / "rust/queue.rs").exists():
|
||||
sources.append(root / "rust/queue.rs")
|
||||
sources += [root / name / "config/setting.json" for name in ("new", "old")]
|
||||
for name in ("rust-resource", "rust-resource-baseline", "rust-contract"):
|
||||
if name in binaries:
|
||||
peer = binaries[name].parents[2]
|
||||
sources += [peer / filename for filename in ("main.rs", "queue.rs", "sqlite_resource.rs", "Cargo.toml", "Cargo.lock")]
|
||||
if name == "rust-contract":
|
||||
sources.append(peer / "contract.rs")
|
||||
report = dict(rounds=0 if args.functional_only else 7, warmups=0 if args.functional_only else 1, sizes=[1, 32, 256, 1024],
|
||||
contract="Single worker, WAL/NORMAL SQLite, two pooled connections, typed JSON payload, active key uniqueness, random 128-bit IDs and lease tokens, 10s lease, 1s handler deadline, two total attempts, 1ms retry/poll. Claim commits separately; business write and owner-checked completion share one transaction. Negative amount rolls back before retry. Stop sends SIGTERM and waits for actual process exit.",
|
||||
limitations="Bounded System Job workload; not full auth/tenant/cron/external Worker equivalence. Rust uses independent Tokio/deadpool/rusqlite, Go database/sql. References perform business write and ack in one worker-side operation; Dever has per-operation async handoffs, generic fault/schema checks and Scope cleanup. Tail SQL polling is included in wall time and recorded; it is not per-job latency. No claim of equal full resource cost from this workload.",
|
||||
binaries={name:dict(path=str(p), sha256=fingerprint(p), bytes=p.stat().st_size) for name,p in binaries.items()},
|
||||
sources={str(p):fingerprint(p) for p in sources},
|
||||
source_lines={str(p):len(p.read_text().splitlines()) for p in sources},
|
||||
schema=schema, functional=[], samples=[])
|
||||
if args.resource_reference:
|
||||
report["resource_contract"] = "Separate BEGIN, each enqueue, full business-record return, owner-checked acknowledgement and COMMIT cross bounded blocking handoffs. Per-operation deadlines, transaction discard on cancellation, eight worker permits and panic recording use the same independent resource module as the Model reference. Every Job drains blocking descendants before acknowledgement, retains handler/cleanup failures including async panic, and rechecks the handler deadline after drain. The single worker reuses its TaskTracker; no other Job can run concurrently on it. The original lighter Rust binary is retained unchanged. This still does not implement generic Dever schema/auth/tenant/cron or nested Task semantics."
|
||||
if args.resource_baseline:
|
||||
report["resource_baseline_contract"] = "Original per-operation independent reference, with handler timeout and process-exit drain but no per-Job descendant drain or post-drain deadline check. Retained unchanged; its earlier results are not replaced by the stronger reference."
|
||||
if args.contract_reference:
|
||||
report["system_contract_reference"] = "Independent per-operation resource peer plus full persisted target/schema/policy/physical queue checks, one typed Execution decode and bounded typed payload decode, rejected jobs blocked without business writes. Reads the same nine claim columns and uses the same pending/expired merge as Dever. Uses its own static declaration and has no user Provider, tenant catalog, cron or external Worker. Rejections may precede BEGIN; valid jobs keep the same operation handoffs and descendant drain. Lighter peers remain unchanged."
|
||||
snapshots = output / "sources"
|
||||
snapshots.mkdir()
|
||||
for index, path in enumerate(sources):
|
||||
shutil.copyfile(path, snapshots / f"{index}-{path.name}")
|
||||
for name, binary in binaries.items():
|
||||
shutil.copyfile(binary, output / (name + "-binary"))
|
||||
|
||||
def save():
|
||||
(output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
def command(name, operation, payload=None):
|
||||
if name == "old" and operation == "submitAll":
|
||||
operation = "submit_all"
|
||||
if name in ("new", "old", "previous", "intermediate"):
|
||||
project = "old" if name == "old" else "new"
|
||||
argv = [str(binaries[name]), "--config", str(root / project / "config/setting.json"),
|
||||
"worker" if operation == "worker" else "benchmark.queue." + operation]
|
||||
if name == "old" and operation == "worker":
|
||||
argv.pop()
|
||||
else:
|
||||
argv = [str(binaries[name]), str(databases[name]), operation]
|
||||
if payload is not None:
|
||||
argv.append(json.dumps(payload, ensure_ascii=False))
|
||||
return argv
|
||||
|
||||
def reset(name):
|
||||
# 只清空本基准新建的数据库;没有工作进程时执行。
|
||||
with connect(databases[name]) as connection:
|
||||
connection.execute("DELETE FROM _dever_job")
|
||||
connection.execute(f'DELETE FROM "{tables[name]}"')
|
||||
|
||||
def submit(name, inputs, label):
|
||||
row = execute(command(name, "submitAll", {"inputs":inputs}), output, label, 120)
|
||||
assert row["exit_code"] == 0, row
|
||||
value = json.loads(Path(row["stdout"]).read_text())
|
||||
if name in ("new", "old", "previous", "intermediate"):
|
||||
assert value["code"] == 0, value
|
||||
value = value["data"]
|
||||
assert len(value) == len(inputs) and all(isinstance(item,str) and item for item in value), value
|
||||
row["checked"] = True
|
||||
return value, row
|
||||
|
||||
def worker(name, completed, label, dead=0, blocked=0):
|
||||
outpath, errpath = output / (label+".stdout"), output / (label+".stderr")
|
||||
started = time.monotonic()
|
||||
polls = 0
|
||||
with outpath.open("xb") as out, errpath.open("xb") as err:
|
||||
process = subprocess.Popen(command(name, "worker"), stdout=out, stderr=err, start_new_session=True)
|
||||
try:
|
||||
with connect(databases[name]) as connection:
|
||||
while True:
|
||||
states = dict(connection.execute("SELECT state,count(*) FROM _dever_job GROUP BY state"))
|
||||
polls += 1
|
||||
if (states.get("completed",0), states.get("dead",0), states.get("blocked",0)) == (completed, dead, blocked):
|
||||
drained = time.monotonic()
|
||||
break
|
||||
assert process.poll() is None, (name, process.returncode, errpath.read_text())
|
||||
assert time.monotonic()-started < 120, (name, states, errpath.read_text())
|
||||
time.sleep(.001)
|
||||
os.kill(process.pid, signal.SIGTERM)
|
||||
deadline = time.monotonic()+10
|
||||
while True:
|
||||
pid, status, usage = os.wait4(process.pid, os.WNOHANG)
|
||||
if pid:
|
||||
process.returncode = os.waitstatus_to_exitcode(status)
|
||||
break
|
||||
assert time.monotonic() < deadline, "worker did not release its process"
|
||||
time.sleep(.001)
|
||||
assert process.returncode == 0, (name, process.returncode, errpath.read_text())
|
||||
finally:
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
return dict(seconds=time.monotonic()-started, drain_seconds=drained-started,
|
||||
shutdown_seconds=time.monotonic()-drained, polls=polls, exit_code=process.returncode,
|
||||
user_cpu_seconds=usage.ru_utime, system_cpu_seconds=usage.ru_stime,
|
||||
peak_rss_kib=usage.ru_maxrss, stdout=str(outpath), stderr=str(errpath), checked=True)
|
||||
|
||||
def verify(name, expected):
|
||||
with connect(databases[name]) as connection:
|
||||
actual = connection.execute(f'SELECT name,amount FROM "{tables[name]}" ORDER BY name').fetchall()
|
||||
assert actual == sorted(expected), (name, actual[:10], expected[:10])
|
||||
metadata = connection.execute(f'SELECT id,created_at FROM "{tables[name]}"').fetchall()
|
||||
assert all(identifier > 0 and 0 < created <= int(time.time()*1000) for identifier,created in metadata)
|
||||
assert connection.execute("SELECT count(*) FROM _dever_job WHERE state IN ('completed','dead') AND (token IS NOT NULL OR lease_until IS NOT NULL)").fetchone() == (0,)
|
||||
assert connection.execute("PRAGMA quick_check").fetchone() == ("ok",)
|
||||
|
||||
save()
|
||||
for name in binaries:
|
||||
reset(name)
|
||||
payloads = [{"name":"中文 ' OR 1=1 --", "amount":7}, {"name":"reject", "amount":-10},
|
||||
{"name":"expired", "amount":2}, {"name":"future", "amount":3}]
|
||||
ids, row = submit(name, payloads, name+"-submit")
|
||||
duplicate, duplicate_row = submit(name, payloads, name+"-duplicate")
|
||||
assert duplicate == ids
|
||||
with connect(databases[name]) as connection:
|
||||
connection.execute("UPDATE _dever_job SET state='running',attempt=1,token='expired-owner',lease_until=0 WHERE task_key='expired'")
|
||||
connection.execute("UPDATE _dever_job SET available_at=? WHERE task_key='future'", (4102444800000,))
|
||||
worked = worker(name, 2, name+"-functional-worker", dead=1)
|
||||
verify(name, [(payloads[0]["name"],28), ("expired",13)])
|
||||
with connect(databases[name]) as connection:
|
||||
states = {key:(state,attempt) for key,state,attempt in connection.execute("SELECT task_key,state,attempt FROM _dever_job")}
|
||||
assert states["reject"] == ("dead",2) and states["expired"] == ("completed",2) and states["future"] == ("pending",0), states
|
||||
repeated, repeated_row = submit(name, payloads[:1], name+"-reuse-key")
|
||||
assert repeated[0] != ids[0]
|
||||
worker(name, 3, name+"-reuse-worker", dead=1)
|
||||
verify(name, [(payloads[0]["name"],28)]*2+[("expired",13)])
|
||||
report["functional"].append(dict(implementation=name, checked=True, enqueue=row, duplicate=duplicate_row,
|
||||
worker=worked, reuse=repeated_row, states=states)); save()
|
||||
if name == "rust-contract":
|
||||
columns = ["target", "schema", "payload", "execution", "execution_tenant", "retries", "timeout_ms"]
|
||||
records = []
|
||||
for implementation in ("new", name):
|
||||
with connect(databases[implementation]) as connection:
|
||||
records.append(connection.execute(
|
||||
f'SELECT {",".join(columns)} FROM _dever_job WHERE task_key=? LIMIT 1', (payloads[0]["name"],)).fetchone())
|
||||
assert records[0] == records[1], ("persisted System contract differs", records)
|
||||
report["system_contract_persisted_record"] = dict(zip(columns, records[0])); save()
|
||||
|
||||
if args.contract_reference:
|
||||
changes = [
|
||||
("target", "missing.handler"), ("schema", "obsolete"),
|
||||
("retries", 3), ("timeout_ms", 1001), ("execution_tenant", 1),
|
||||
("execution", '{"kind":"System","tenant":1}'),
|
||||
("execution", '{"kind":"System","tenant":null,"unknown":true}'),
|
||||
("execution", '{"kind":"System","kind":"System"}'),
|
||||
("execution", '{"kind":"System","tenant":"wrong"}'),
|
||||
("execution", '{"kind":"User","provider":"absent","subject":"user","session":"session","site":"front","tenant":null,"tenant_id":null,"permission":"benchmark.queue.publish"}'),
|
||||
("payload", '{"name":"wrong","amount":"wrong"}'),
|
||||
("payload", '{"name":"duplicate","amount":1,"amount":2}'),
|
||||
("payload", '{"name":"unknown","amount":1,"unknown":true}'),
|
||||
("payload", '["positional",1]'),
|
||||
("payload", 'null'),
|
||||
("payload", '{"name":"missing"}'),
|
||||
("payload", '{"name":"trailing","amount":1} true'),
|
||||
]
|
||||
for name in ("new", "rust-contract"):
|
||||
reset(name)
|
||||
payloads = [{"name":f"contract-{index}", "amount":2} for index in range(len(changes)+1)]
|
||||
submit(name, payloads, name+"-contract-submit")
|
||||
with connect(databases[name]) as connection:
|
||||
for index, (column, value) in enumerate(changes):
|
||||
connection.execute(f'UPDATE _dever_job SET "{column}"=? WHERE task_key=?', (value, payloads[index]["name"]))
|
||||
worked = worker(name, 1, name+"-contract-worker", blocked=len(changes))
|
||||
verify(name, [(payloads[-1]["name"], 13)])
|
||||
with connect(databases[name]) as connection:
|
||||
states = connection.execute("SELECT task_key,state,attempt FROM _dever_job ORDER BY task_key").fetchall()
|
||||
assert all(attempt == 1 for _, _, attempt in states), states
|
||||
assert connection.execute("SELECT count(*) FROM _dever_job WHERE token IS NOT NULL OR lease_until IS NOT NULL").fetchone() == (0,)
|
||||
report["functional"].append(dict(implementation=name, contract_checked=True,
|
||||
rejected=len(changes), valid_control=1, states=states, worker=worked)); save()
|
||||
|
||||
if args.functional_only:
|
||||
print(json.dumps({"functional": len(report["functional"]), "timed_samples": 0}))
|
||||
return
|
||||
|
||||
os.sched_setaffinity(0, {0})
|
||||
os.environ["GOMAXPROCS"] = "1"
|
||||
names = list(binaries)
|
||||
for repeat in range(-1,7):
|
||||
assert all(fingerprint(Path(path)) == sha for path,sha in report["sources"].items())
|
||||
assert all(fingerprint(p) == report["binaries"][name]["sha256"] for name,p in binaries.items())
|
||||
for size in report["sizes"]:
|
||||
payloads = [{"name":f"job-{i:06}","amount":i} for i in range(size)]
|
||||
for offset in range(len(names)):
|
||||
name = names[(repeat+1+offset)%len(names)]
|
||||
reset(name)
|
||||
label = f"{repeat+1}-{size}-{name}"
|
||||
ids, row = submit(name, payloads, label+"-enqueue")
|
||||
assert len(set(ids)) == size
|
||||
queued, duplicate = submit(name, payloads, label+"-duplicate")
|
||||
assert queued == ids
|
||||
finished = worker(name, size, label+"-worker")
|
||||
verify(name, [(p["name"],p["amount"]*3+7) for p in payloads])
|
||||
report["samples"].append(dict(implementation=name,size=size,warmup=repeat<0,
|
||||
enqueue=row, duplicate=duplicate, worker=finished, checked=True)); save()
|
||||
report["medians"] = []
|
||||
for size in report["sizes"]:
|
||||
for name in names:
|
||||
rows = [r for r in report["samples"] if not r["warmup"] and r["size"]==size and r["implementation"]==name]
|
||||
for phase in ("enqueue","duplicate","worker"):
|
||||
report["medians"].append(dict(size=size,implementation=name,phase=phase,
|
||||
seconds=statistics.median(r[phase]["seconds"] for r in rows),
|
||||
cpu_seconds=statistics.median(r[phase]["user_cpu_seconds"]+r[phase]["system_cpu_seconds"] for r in rows)))
|
||||
save()
|
||||
print(json.dumps(report["medians"], indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,140 @@
|
||||
"""构建真实持久队列四方对端;冻结编译器仅复用,不改 bak 或系统工具。"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--old-compiler", type=Path, required=True)
|
||||
parser.add_argument("--baseline-identity", type=Path, required=True,
|
||||
help="existing R0 compiler identity; do not substitute an unrelated old executable")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
fixture = core / "test/performance/fixtures/job"
|
||||
root = args.output.absolute()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = {"commands": [], "compilers": {}, "sources": {
|
||||
str(p): fingerprint(p) for p in [Path(__file__), fixture.parent / "sqlite_resource.rs.txt", *fixture.iterdir()]}}
|
||||
baseline = json.loads(args.baseline_identity.read_text())
|
||||
assert fingerprint(args.old_compiler) == baseline["original_compiler"]["sha256"], "old compiler differs from frozen R0"
|
||||
report["baseline_identity"] = baseline
|
||||
|
||||
def run(label, command):
|
||||
row = execute(list(map(str, command)), root, label, 1800)
|
||||
report["commands"].append(row)
|
||||
(root / "build.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["exit_code"] == 0, row
|
||||
|
||||
for name, tool in [("new", args.compiler), ("old", args.old_compiler)]:
|
||||
tool = tool.resolve(strict=True)
|
||||
report["compilers"][name] = {"path": str(tool), "sha256": fingerprint(tool)}
|
||||
project = root / name
|
||||
module = project / "module/benchmark/queue"
|
||||
module.mkdir(parents=True)
|
||||
for role in ("model", "app"):
|
||||
source = "old.dever.txt" if name == "old" and role == "app" else f"{role}.dever"
|
||||
directory = "data" if role == "model" else role
|
||||
target = module / (f"{directory}/main.dever" if name == "new" else f"{role}.dever")
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
shutil.copyfile(fixture / source, target)
|
||||
if name == "new":
|
||||
shutil.copyfile(fixture / "api.dever", module / "api.dever")
|
||||
else:
|
||||
(module / "api.dever").write_text("cmd submit = app.submit\ncmd submit_all = app.submitAll\n")
|
||||
(module / "job.dever").write_text(
|
||||
"database default\njob publish(input: app.Payload) () retry(2) timeout(1000) { app.apply(input) }\n")
|
||||
(project / "config").mkdir()
|
||||
config = project / "config/setting.json"
|
||||
config.write_text(json.dumps({"database": {"default": {"type": "sqlite",
|
||||
"path": "queue.db" if name == "new" else "old/queue.db", "max_connections": 2}},
|
||||
"job": {"workers": 1, "poll_ms": 1, "lease_ms": 10000,
|
||||
"retry_base_ms": 1, "retry_max_ms": 10, "shutdown_ms": 5000}}) + "\n")
|
||||
if name == "old":
|
||||
settings = json.loads(config.read_text())
|
||||
del settings["job"]["shutdown_ms"]
|
||||
settings["runtime"] = {"mode": "worker", "shutdown_ms": 5000}
|
||||
config.write_text(json.dumps(settings) + "\n")
|
||||
run(name + "-fmt", [tool, "fmt", project])
|
||||
run(name + "-build", [tool, "build", project, "--output", root / (name + "-app")])
|
||||
command = [root / (name + "-app"), "--config", config]
|
||||
run(name + "-initialize", command + (["migrate"] if name == "new" else ["benchmark.queue.submit_all", '{"inputs":[]}']))
|
||||
build_references(core, root, run)
|
||||
|
||||
|
||||
def build_references(core, root, run):
|
||||
fixture = core / "test/performance/fixtures/job"
|
||||
peer = root / "rust"
|
||||
peer.mkdir()
|
||||
shutil.copyfile(fixture / "peer.rs.txt", peer / "main.rs")
|
||||
shutil.copyfile(fixture / "queue.rs.txt", peer / "queue.rs")
|
||||
shutil.copyfile(core / "rust/Cargo.lock", peer / "Cargo.lock")
|
||||
(peer / "Cargo.toml").write_text('''[package]
|
||||
name = "job-peer"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "job-peer"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
deadpool-sqlite = { version = "=0.14.0", features = ["bundled", "hooks", "functions"] }
|
||||
tokio = { version = "=1.53.1", features = ["rt", "time", "macros", "sync", "signal"] }
|
||||
serde = { version = "=1.0.228", features = ["derive"] }
|
||||
serde_json = "=1.0.145"
|
||||
getrandom = "=0.2.17"
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = true
|
||||
''')
|
||||
run("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
|
||||
"--manifest-path", peer / "Cargo.toml", "--target-dir", peer / "target"])
|
||||
locked = {(p["name"], p["version"]) for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]}
|
||||
dependencies = tomllib.loads((peer / "Cargo.lock").read_text())["package"]
|
||||
assert all((p["name"], p["version"]) in locked for p in dependencies if "source" in p)
|
||||
peer = root / "go"
|
||||
peer.mkdir()
|
||||
shutil.copyfile(fixture / "peer.go.txt", peer / "main.go")
|
||||
for name in ("go.mod", "go.sum"):
|
||||
shutil.copyfile(core / "test/performance/fixtures/model" / (name + ".txt"), peer / name)
|
||||
run("go-build", ["go", "-C", peer, "build", "-buildvcs=false", "-mod=readonly",
|
||||
"-trimpath", "-ldflags=-s -w", "-o", root / "go-app", "."])
|
||||
build_resource(core, root, run, target_dir=root / "rust/target")
|
||||
build_resource(core, root, run, contract=True, target_dir=root / "rust/target")
|
||||
|
||||
|
||||
def build_resource(core, root, run, contract=False, target_dir=None):
|
||||
label = "rust-contract" if contract else "rust-resource"
|
||||
binary_name = "job-contract-peer" if contract else "job-resource-peer"
|
||||
peer = root / label
|
||||
peer.mkdir()
|
||||
for source, target in [("job/resource.rs.txt", "main.rs"), ("job/queue.rs.txt", "queue.rs"),
|
||||
("sqlite_resource.rs.txt", "sqlite_resource.rs")]:
|
||||
shutil.copyfile(core / "test/performance/fixtures" / source, peer / target)
|
||||
if contract:
|
||||
shutil.copyfile(core / "test/performance/fixtures/job/contract.rs.txt", peer / "contract.rs")
|
||||
shutil.copyfile(core / "rust/Cargo.lock", peer / "Cargo.lock")
|
||||
manifest = (root / "rust/Cargo.toml").read_text().replace("job-peer", binary_name)
|
||||
manifest = manifest.replace("[profile.release]", 'tokio-util = { version = "=0.7.19", features = ["rt"] }\nfutures-util = "=0.3.34"\npercent-encoding = "=2.3.2"\n[profile.release]')
|
||||
manifest += '\n[features]\ncontract = []\ndefault = ' + ('["contract"]' if contract else '[]') + '\n'
|
||||
(peer / "Cargo.toml").write_text(manifest)
|
||||
target_dir = target_dir or peer / "target"
|
||||
run(label + "-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
|
||||
"--manifest-path", peer / "Cargo.toml", "--target-dir", target_dir])
|
||||
if target_dir != peer / "target":
|
||||
output = peer / "target/release"
|
||||
output.mkdir(parents=True)
|
||||
shutil.copy2(target_dir / "release" / binary_name, output / binary_name)
|
||||
locked = {(p["name"],p["version"]) for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]}
|
||||
assert all((p["name"],p["version"]) in locked for p in tomllib.loads((peer / "Cargo.lock").read_text())["package"] if "source" in p)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""不透明 JSON 验证与原文往返:独立事件库 Rust 对照,固定七轮,不共享 Dever runtime。"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
DEVER = '''loop measure(source: Text, n: Int) (total: Int)
|
||||
| each iteration in range(0, n) | result |
|
||||
| total | sum length(dever.json.toText(dever.json.fromText(source))) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
|
||||
# 独立实现使用库的高层事件接口和递归遍历,不引用 Dever 的类型、验证器或生成代码。
|
||||
RUST = r'''use json_event_parser::{JsonEvent, SliceJsonParser};
|
||||
use std::{borrow::Cow, collections::HashSet};
|
||||
fn value<'a>(event: JsonEvent<'a>, parser: &mut SliceJsonParser<'a>, count: &mut usize, depth: usize) -> Result<(), String> {
|
||||
*count += 1;
|
||||
if *count > 65536 { return Err("value limit".into()); }
|
||||
match event {
|
||||
JsonEvent::StartArray => {
|
||||
if depth == 64 { return Err("depth limit".into()); }
|
||||
loop {
|
||||
let event = parser.parse_next().map_err(|e| e.to_string())?;
|
||||
if event == JsonEvent::EndArray { break; }
|
||||
value(event, parser, count, depth + 1)?;
|
||||
}
|
||||
}
|
||||
JsonEvent::StartObject => {
|
||||
if depth == 64 { return Err("depth limit".into()); }
|
||||
let mut names: HashSet<Cow<'a, str>> = HashSet::new();
|
||||
loop {
|
||||
let event = parser.parse_next().map_err(|e| e.to_string())?;
|
||||
if event == JsonEvent::EndObject { break; }
|
||||
let JsonEvent::ObjectKey(name) = event else { return Err("key expected".into()); };
|
||||
if !names.insert(name) { return Err("duplicate key".into()); }
|
||||
let event = parser.parse_next().map_err(|e| e.to_string())?;
|
||||
value(event, parser, count, depth + 1)?;
|
||||
}
|
||||
}
|
||||
JsonEvent::String(_) | JsonEvent::Number(_) | JsonEvent::Boolean(_) | JsonEvent::Null => {}
|
||||
_ => return Err("value expected".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn validated(source: String) -> Result<String, String> {
|
||||
if source.len() > 16 * 1024 * 1024 { return Err("byte limit".into()); }
|
||||
let mut parser = SliceJsonParser::new(source.as_bytes());
|
||||
let first = parser.parse_next().map_err(|e| e.to_string())?;
|
||||
value(first, &mut parser, &mut 0, 0)?;
|
||||
if parser.parse_next().map_err(|e| e.to_string())? != JsonEvent::Eof { return Err("trailing content".into()); }
|
||||
Ok(source)
|
||||
}
|
||||
fn main() {
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
let count: i64 = args[2].parse().unwrap();
|
||||
let mut total = 0i64;
|
||||
for _ in 0..count {
|
||||
let raw = validated(args[1].clone()).unwrap();
|
||||
total = total.checked_add(raw.chars().count() as i64).unwrap();
|
||||
}
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--compiler', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--core-source', type=Path, required=True)
|
||||
parser.add_argument('--iterations', type=int, default=1000)
|
||||
args = parser.parse_args()
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
core = args.core_source.resolve(strict=True)
|
||||
inputs = [core / 'rust/Cargo.lock']
|
||||
inputs += sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.is_file() and path.suffix in {'.rs', '.toml'})
|
||||
inputs += sorted((core / 'lib').rglob('*.dv'))
|
||||
source_hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs}
|
||||
for path in inputs:
|
||||
saved = root / 'inputs' / path.relative_to(core)
|
||||
saved.parent.mkdir(parents=True, exist_ok=True)
|
||||
saved.write_bytes(path.read_bytes())
|
||||
for name in ['json_roundtrip.py', 'scale.py']:
|
||||
(root / name).write_bytes(Path(__file__).with_name(name).read_bytes())
|
||||
source = '[\n' + ',\n'.join('{"number":1e9999,"text":"雪\\u96ea","flags":[true,null]}' for _ in range(1000)) + '\n]'
|
||||
(root / 'input.json').write_text(source)
|
||||
os.environ['CARGO_BUILD_JOBS'] = '1'
|
||||
report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler),
|
||||
driver_sha256=fingerprint(root / 'json_roundtrip.py'), input_sha256=fingerprint(root / 'input.json'),
|
||||
iterations=args.iterations, rounds=7, builds=[], samples=[],
|
||||
core_source=str(core), source_hashes=source_hashes,
|
||||
scope='Whole process: validated owned raw text, no AST, exact raw number/whitespace preservation, then Unicode scalar length. Both use json-event-parser 0.2.3. Rust has independent traversal, no Dever runtime. Dever additionally decodes CMD JSON.',
|
||||
missing=['old Dever on this workload', 'Go with equivalent Unicode/duplicate/budget contract'],
|
||||
memory_scope='wait4 may include Python fork; not application-only RSS',
|
||||
environment={name: Path('/sys/fs/cgroup', name).read_text().strip() for name in ['cpu.max', 'memory.max']})
|
||||
def save():
|
||||
(root / 'results.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
programs = {}
|
||||
for language, text in [('dever', DEVER), ('rust', RUST)]:
|
||||
case = root / language
|
||||
case.mkdir()
|
||||
path = case / ('main.dever' if language == 'dever' else 'main.rs')
|
||||
path.write_text(text)
|
||||
binary = case / 'program'
|
||||
if language == 'dever':
|
||||
formatted = execute([str(compiler), 'fmt', str(path)], case, 'format', 30)
|
||||
if formatted['exit_code']: raise SystemExit(formatted['stderr'])
|
||||
command = [str(compiler), 'build', str(path), '--output', str(binary)]
|
||||
else:
|
||||
(case / 'Cargo.toml').write_text('''[package]
|
||||
name = "json-reference"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "json-reference"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
json-event-parser = "=0.2.3"
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = "symbols"
|
||||
''')
|
||||
command = ['cargo', '+1.95.0', 'build', '--offline', '--release', '--manifest-path', str(case / 'Cargo.toml'), '--target-dir', str(case / 'target')]
|
||||
binary = case / 'target/release/json-reference'
|
||||
build = dict(language=language, source_sha256=fingerprint(path), **execute(command, case, 'build', 900))
|
||||
report['builds'].append(build)
|
||||
save()
|
||||
if build['exit_code']: raise SystemExit(build['stderr'])
|
||||
build['binary_sha256'] = fingerprint(binary)
|
||||
programs[language] = binary
|
||||
for repeat in range(-1, 7):
|
||||
assert source_hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime/library inputs changed during measurement'
|
||||
for language in (['dever', 'rust'] if repeat % 2 else ['rust', 'dever']):
|
||||
binary = programs[language]
|
||||
command = [str(binary), 'main.main.bench', json.dumps(dict(source=source, n=args.iterations), ensure_ascii=False)] if language == 'dever' else [str(binary), source, str(args.iterations)]
|
||||
row = dict(language=language, repeat=repeat, **execute(command, binary.parent, f'run-{repeat}', 60))
|
||||
output = Path(row['stdout']).read_text()
|
||||
row['expected'] = len(source) * args.iterations
|
||||
row['correct'] = row['exit_code'] == 0 and (json.loads(output)['data'] if language == 'dever' else int(output)) == row['expected']
|
||||
report['samples'].append(row)
|
||||
save()
|
||||
print(json.dumps({key: row[key] for key in ['language', 'repeat', 'seconds', 'correct']}), flush=True)
|
||||
if not row['correct']: raise SystemExit(row['stderr'])
|
||||
report['medians'] = {language: statistics.median(row['seconds'] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0) for language in programs}
|
||||
save()
|
||||
print(json.dumps(report['medians']), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,185 @@
|
||||
"""四方内核对照:固定 R0 旧版/Go,原 Rust 源码使用当前锁重建,构建当前三表源码。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import statistics
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
CASES = {
|
||||
"integer": (16384, 65536), "float": (16384, 65536),
|
||||
**{name: (512, 1024, 2048, 4096) for name in (
|
||||
"list", "map", "list_read", "list_record", "list_record_read",
|
||||
"record_update", "record_inspect", "call_read", "map_read", "map_lookup",
|
||||
"map_text_lookup", "text_equal", "text_contains")},
|
||||
"text_concat": (512, 2048, 8192, 32768),
|
||||
"bytes_concat": (512, 2048, 8192, 32768),
|
||||
}
|
||||
for name in ("record_update", "record_inspect"):
|
||||
CASES[name] += (16384, 65536)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", required=True, type=Path)
|
||||
parser.add_argument("--baseline", required=True, type=Path, help="R0 kernel directory containing manifest.json")
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--previous", type=Path, help="same-contract prior candidate binary for interleaved comparison")
|
||||
parser.add_argument("--earlier", type=Path, help="additional same-contract pre-regression Dever binary; retain the immediate previous candidate")
|
||||
parser.add_argument("--project", type=Path, help="reuse the original formatted workload path without modifying its source")
|
||||
parser.add_argument("--rust-reference", type=Path, help="reuse a previously built locked Rust peer without replacing its binary")
|
||||
parser.add_argument("--aligned-rust-reference", type=Path, help="additional independent Rust peer with aligned optimizations; original Rust remains in the comparison")
|
||||
parser.add_argument("--resource-rust-reference", type=Path, help="additional independent Rust peer aligning record input ownership, typed sample storage and monotonic clock API; retain original and algorithm-aligned peers")
|
||||
parser.add_argument("--borrowed-text-rust-reference", type=Path, help="additional independent peer borrowing split Text pieces; retain all owned-piece references")
|
||||
parser.add_argument("--argv0", help="use the same explicit process name for every measured binary; retain original-path measurements")
|
||||
args = parser.parse_args()
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
root = args.output.absolute()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
baseline = args.baseline.resolve(strict=True)
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
original = json.loads((baseline / "manifest.json").read_text())
|
||||
binaries = {}
|
||||
for name, artifact in original.items():
|
||||
path = Path(artifact["path"])
|
||||
assert fingerprint(path) == artifact["sha256"], f"R0 artifact changed: {name}"
|
||||
binaries["old" if name == "dever" else name] = path
|
||||
# 独立 Rust 仍不链接 Dever;不重写参考算法或更换较慢的依赖制造通过。
|
||||
locked = {(p["name"], p["version"], p.get("source"))
|
||||
for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]}
|
||||
reference = root / "rust-reference"
|
||||
reference.mkdir()
|
||||
for name in ("main.rs", "Cargo.toml"):
|
||||
shutil.copyfile(baseline / "rust-peer" / name, reference / name)
|
||||
assert fingerprint(reference / "main.rs") == original["rust"]["source"]["sha256"]
|
||||
rust_binary = args.rust_reference.resolve(strict=True) if args.rust_reference else None
|
||||
if rust_binary:
|
||||
peer = rust_binary.parents[2]
|
||||
for name in ("main.rs", "Cargo.toml"):
|
||||
assert fingerprint(peer / name) == fingerprint(reference / name)
|
||||
shutil.copyfile(peer / "Cargo.lock", reference / "Cargo.lock")
|
||||
else:
|
||||
shutil.copyfile(core / "rust/Cargo.lock", reference / "Cargo.lock")
|
||||
project = args.project.resolve(strict=True) if args.project else root / "project"
|
||||
module = project / "module/benchmark/kernel"
|
||||
if not args.project:
|
||||
module.mkdir(parents=True)
|
||||
for source in (Path(__file__).parent / "fixtures/kernel").iterdir():
|
||||
shutil.copyfile(source, module / source.name)
|
||||
report = dict(rounds=7, warmups=1, samples_per_process=10, cpu_affinity=[0],
|
||||
contract="Same R0 input and checked checksum. Internal monotonic timing excludes preparation and final checksum. Each process emits ten raw samples; its first is retained but excluded from steady-state median. Process CPU/time also recorded. Kernel success paths only; no full application/error/ownership parity claim.",
|
||||
baseline=original, compiler_sha256=fingerprint(compiler), builds=[], samples=[])
|
||||
if args.argv0 is not None:
|
||||
report["argv0"] = args.argv0
|
||||
def save():
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
binaries["new"] = root / "new"
|
||||
if args.previous:
|
||||
binaries["previous"] = args.previous.resolve(strict=True)
|
||||
if args.earlier:
|
||||
binaries["earlier"] = args.earlier.resolve(strict=True)
|
||||
binaries["rust"] = rust_binary or reference / "target/release/kernel-peer"
|
||||
for selected, binary_name, source_key in (
|
||||
(args.aligned_rust_reference, "rust_aligned", "aligned_rust_reference"),
|
||||
(args.resource_rust_reference, "rust_resource", "resource_rust_reference"),
|
||||
(args.borrowed_text_rust_reference, "rust_text_borrowed", "borrowed_text_rust_reference"),
|
||||
):
|
||||
if selected is None:
|
||||
continue
|
||||
binary = selected.resolve(strict=True)
|
||||
peer = binary.parents[2]
|
||||
for name in ("Cargo.toml", "Cargo.lock"):
|
||||
assert fingerprint(peer / name) == fingerprint(reference / name)
|
||||
binaries[binary_name] = binary
|
||||
report[source_key] = {
|
||||
str(peer / name): fingerprint(peer / name)
|
||||
for name in ("main.rs", "Cargo.toml", "Cargo.lock")}
|
||||
commands = []
|
||||
if not rust_binary:
|
||||
commands.append(("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
|
||||
"--manifest-path", str(reference / "Cargo.toml"),
|
||||
"--target-dir", str(reference / "target")]))
|
||||
commands += [("format", [str(compiler), "fmt", str(project)] + (["--check"] if args.project else [])),
|
||||
("build", [str(compiler), "build", str(project), "--output", str(binaries["new"])])]
|
||||
for label, command in commands:
|
||||
row = execute(command, root, label, 900)
|
||||
report["builds"].append(row)
|
||||
save()
|
||||
assert row["exit_code"] == 0, row
|
||||
peer = 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 peer)
|
||||
report["rust_reference"] = dict(source_sha256=fingerprint(reference / "main.rs"),
|
||||
lock_sha256=fingerprint(reference / "Cargo.lock"),
|
||||
policy="Unchanged R0 Rust source/profile, current locked dependencies. Existing binary reused when explicitly selected; original R0 artifact retained in baseline.",
|
||||
reused_binary=bool(rust_binary), reused_project=bool(args.project))
|
||||
report["binaries"] = {name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size)
|
||||
for name, path in binaries.items()}
|
||||
inputs = [*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"),
|
||||
*module.glob("*.dever"), Path(__file__), Path(__file__).with_name("scale.py")]
|
||||
inputs += [Path(path) for path in report.get("aligned_rust_reference", {})]
|
||||
inputs += [Path(path) for path in report.get("resource_rust_reference", {})]
|
||||
inputs += [Path(path) for path in report.get("borrowed_text_rust_reference", {})]
|
||||
report["sources"] = {str(p): fingerprint(p) for p in inputs}
|
||||
report["business_sources"] = {
|
||||
"new": [dict(path=str(p), lines=len(p.read_text().splitlines()), sha256=fingerprint(p)) for p in module.glob("*.dever")],
|
||||
"old": [dict(path=str(p), lines=len(p.read_text().splitlines()), sha256=fingerprint(p)) for p in (baseline / "module").rglob("*.dever")],
|
||||
"rust": dict(path=str(baseline / "rust-peer/main.rs"), lines=len((baseline / "rust-peer/main.rs").read_text().splitlines())),
|
||||
"go": dict(path=original["go"]["source"]["path"], lines=len(Path(original["go"]["source"]["path"]).read_text().splitlines())),
|
||||
}
|
||||
os.sched_setaffinity(0, {0})
|
||||
os.environ["GOMAXPROCS"] = "1"
|
||||
names = ["new", "old", "rust", "go"]
|
||||
if args.previous:
|
||||
names.append("previous")
|
||||
if args.earlier:
|
||||
names.append("earlier")
|
||||
if args.aligned_rust_reference:
|
||||
names.append("rust_aligned")
|
||||
if args.resource_rust_reference:
|
||||
names.append("rust_resource")
|
||||
if args.borrowed_text_rust_reference:
|
||||
names.append("rust_text_borrowed")
|
||||
for repeat in range(-1, 7):
|
||||
assert all(fingerprint(Path(path)) == digest for path, digest in report["sources"].items())
|
||||
for operation, sizes in CASES.items():
|
||||
for count in sizes:
|
||||
ticks = ",".join(["x"] * count) if operation == "text_concat" else "x" * count
|
||||
for offset in range(len(names)):
|
||||
name = names[(repeat + 1 + offset) % len(names)]
|
||||
action = "continuous_" + operation
|
||||
if name in ("old", "new", "previous", "earlier"):
|
||||
action = "benchmark.kernel." + action
|
||||
row = dict(name=name, operation=operation, count=count, repeat=repeat,
|
||||
**execute([str(binaries[name]), action, json.dumps({"ticks": ticks})],
|
||||
root, f"{repeat}-{operation}-{count}-{name}", 120, argv0=args.argv0))
|
||||
value = json.loads(Path(row["stdout"]).read_text()) if row["exit_code"] == 0 else None
|
||||
if name in ("old", "new", "previous", "earlier") and value is not None:
|
||||
value = value["data"]
|
||||
row["values"] = value
|
||||
row["correct"] = isinstance(value, list) and len(value) == 10 and all(
|
||||
v["checksum"] == count * 120 and v["elapsed_ns"] > 0 for v in value)
|
||||
report["samples"].append(row)
|
||||
if not row["correct"]:
|
||||
save()
|
||||
raise AssertionError(row)
|
||||
# 原始输出逐进程落盘;每组汇总一次,避免反复重写不断增长的全部历史。
|
||||
save()
|
||||
print("round", repeat, "complete", flush=True)
|
||||
report["medians"] = []
|
||||
for operation, sizes in CASES.items():
|
||||
for count in sizes:
|
||||
item = dict(operation=operation, count=count, nanoseconds={})
|
||||
for name in names:
|
||||
rows = [r for r in report["samples"] if r["repeat"] >= 0 and r["name"] == name
|
||||
and r["operation"] == operation and r["count"] == count]
|
||||
item["nanoseconds"][name] = statistics.median(v["elapsed_ns"] for row in rows for v in row["values"][1:])
|
||||
report["medians"].append(item)
|
||||
save()
|
||||
print(json.dumps(report["medians"], indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""冻结旧语言的标准库工作负载;运算与当前三表夹具一致,不翻译业务源码。"""
|
||||
|
||||
SHAPES = {"standard", "uuid", "calendar"}
|
||||
|
||||
|
||||
def source(shape):
|
||||
if shape == "standard":
|
||||
return '''required(value: Int?) (out: Int) {
|
||||
check value != null else Invalid
|
||||
out = value
|
||||
}
|
||||
roundtrip(value: Int) (out: Int) {
|
||||
decorated = " " + int.toText(value) + "雪 "
|
||||
trimmed = text.trim(decorated)
|
||||
joined = text.join(text.split(trimmed, ""), "")
|
||||
out = required(int.parse(text.replace(joined, "雪", "")))
|
||||
}
|
||||
measure(n: Int) (out: Int) { out = sum(each(roundtrip, range(0, n))) }
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if shape == "uuid":
|
||||
return '''requiredUuid(value: Uuid?) (out: Uuid) {
|
||||
check value != null else Invalid
|
||||
out = value
|
||||
}
|
||||
requiredText(value: Text?) (out: Text) {
|
||||
check value != null else Invalid
|
||||
out = value
|
||||
}
|
||||
requiredInt(value: Int?) (out: Int) {
|
||||
check value != null else Invalid
|
||||
out = value
|
||||
}
|
||||
roundtrip(value: Int) (out: Int) {
|
||||
source = "550e8400-e29b-41d4-a716-" + int.toText(value + 100000000000)
|
||||
parsed = requiredUuid(uuid.parse(source))
|
||||
last = requiredText(text.at(uuid.toText(parsed), 35))
|
||||
out = requiredInt(int.parse(last))
|
||||
}
|
||||
measure(n: Int) (out: Int) { out = sum(each(roundtrip, range(0, n))) }
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if shape == "calendar":
|
||||
return '''roundtrip(offset: Int, start: DateTime) (out: Int) {
|
||||
span = dever.time.duration(offset)
|
||||
changed = dever.time.add(start, span)
|
||||
text = dever.time.formatDatetime(changed)
|
||||
restored = dever.time.parseDatetime(text)
|
||||
check dever.time.difference(restored, start) == span else Invalid
|
||||
out = 1
|
||||
}
|
||||
measure(n: Int) (out: Int) {
|
||||
start = dever.time.parseDatetime("2024-02-29T12:34:56.12+08:00")
|
||||
out = sum(each(roundtrip, range(0, n), start))
|
||||
}
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
raise ValueError(f"no frozen-language fixture for {shape}")
|
||||
@@ -0,0 +1,709 @@
|
||||
"""顺序 loop 的独立 Rust/Go 运行对照;先完成全部构建,再交错测量真实程序。"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
from legacy_reference import SHAPES as LEGACY_SHAPES, source as legacy_source
|
||||
from token_reference import source as token_source
|
||||
from file_reference import source as file_source
|
||||
from file_stream_reference import source as file_stream_source
|
||||
from bytes_reference import source as bytes_source
|
||||
from standard_reference import source as standard_source
|
||||
from uuid_reference import source as uuid_source
|
||||
from calendar_reference import source as calendar_source
|
||||
from settings_reference import source as settings_source, config as settings_config, expected as settings_expected
|
||||
from port_reference import source as port_source, config as port_config, project as port_project
|
||||
from async_reference import source as async_source
|
||||
from parallel_reference import source as parallel_source
|
||||
from concurrent_reference import source as concurrent_source
|
||||
from stdout_reference import source as stdout_source
|
||||
from arguments_reference import source as arguments_source
|
||||
from net_reference import source as net_source
|
||||
from tls_reference import source as tls_source
|
||||
from http_reference import source as http_source, server as http_server
|
||||
from http_pool_reference import source as http_pool_source
|
||||
from http_stream_reference import source as http_stream_source
|
||||
from crypto_reference import source as crypto_source, config as crypto_config, expected as crypto_expected
|
||||
|
||||
|
||||
def group_source(language):
|
||||
if language == 'dever':
|
||||
return '''loop grouped(n: Int) (out: Map<Int, List<Int>>)
|
||||
| each value in range(0, n) | result |
|
||||
| out | group value % 64 |
|
||||
loop total(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
loop checksum(values: List<MapEntry<Int, List<Int>>>) (out: Int)
|
||||
| each entry in values | result |
|
||||
| out | sum total(entry.value) + entry.key |
|
||||
measure(n: Int) (out: Int) { out = checksum(entries(grouped(n))) }
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use indexmap::IndexMap;
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut groups: IndexMap<i64, Vec<i64>, ahash::RandomState> = IndexMap::with_capacity_and_hasher(0, ahash::RandomState::new());
|
||||
for value in 0..n { groups.entry(value % 64).or_default().push(value); }
|
||||
let entries: Vec<_> = groups.into_iter().collect();
|
||||
let mut checksum = 0i64;
|
||||
for (key, values) in entries {
|
||||
let mut total = 0i64;
|
||||
for value in values { total = total.checked_add(value).expect("sum overflow"); }
|
||||
checksum = checksum.checked_add(total.checked_add(key).expect("key overflow")).expect("checksum overflow");
|
||||
}
|
||||
println!("{checksum}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func add(a, b int64) int64 {
|
||||
result := a + b
|
||||
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
|
||||
return result
|
||||
}
|
||||
type entry struct { key int64; values []int64 }
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
positions := make(map[int64]int)
|
||||
groups := make([]entry, 0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
key := value % 64
|
||||
position, exists := positions[key]
|
||||
if !exists {
|
||||
position = len(groups)
|
||||
positions[key] = position
|
||||
groups = append(groups, entry{key: key})
|
||||
}
|
||||
groups[position].values = append(groups[position].values, value)
|
||||
}
|
||||
checksum := int64(0)
|
||||
for _, group := range groups {
|
||||
total := int64(0)
|
||||
for _, value := range group.values { total = add(total, value) }
|
||||
checksum = add(checksum, add(total, group.key))
|
||||
}
|
||||
fmt.Println(checksum)
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def index_source(language):
|
||||
if language == 'dever':
|
||||
return '''loop indexed(n: Int) (out: Map<Int, Int>)
|
||||
| each value in range(0, n) | result |
|
||||
| out | index value |
|
||||
loop checksum(values: List<MapEntry<Int, Int>>) (out: Int)
|
||||
| each entry in values | result |
|
||||
| out | sum entry.value + entry.key |
|
||||
measure(n: Int) (out: Int) { out = checksum(entries(indexed(n))) }
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use indexmap::{IndexMap, map::Entry};
|
||||
#[derive(Debug)]
|
||||
enum Error { DuplicateKey }
|
||||
fn measure(n: i64) -> Result<i64, Error> {
|
||||
let mut indexed: IndexMap<i64, i64, ahash::RandomState> = IndexMap::with_capacity_and_hasher(0, ahash::RandomState::new());
|
||||
for value in 0..n {
|
||||
match indexed.entry(value) {
|
||||
Entry::Vacant(entry) => { entry.insert(value); }
|
||||
Entry::Occupied(_) => return Err(Error::DuplicateKey),
|
||||
}
|
||||
}
|
||||
let entries: Vec<_> = indexed.into_iter().collect();
|
||||
let mut checksum = 0i64;
|
||||
for (key, value) in entries {
|
||||
checksum = checksum.checked_add(value.checked_add(key).expect("value overflow")).expect("checksum overflow");
|
||||
}
|
||||
Ok(checksum)
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{}", measure(n).unwrap());
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("errors"; "fmt"; "os"; "strconv")
|
||||
func add(a, b int64) int64 {
|
||||
result := a + b
|
||||
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
|
||||
return result
|
||||
}
|
||||
type entry struct { key int64; value int64 }
|
||||
func measure(n int64) (int64, error) {
|
||||
positions := make(map[int64]int)
|
||||
entries := make([]entry, 0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
if _, exists := positions[value]; exists { return 0, errors.New("DuplicateKey") }
|
||||
positions[value] = len(entries)
|
||||
entries = append(entries, entry{key: value, value: value})
|
||||
}
|
||||
checksum := int64(0)
|
||||
for _, entry := range entries { checksum = add(checksum, add(entry.value, entry.key)) }
|
||||
return checksum, nil
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
checksum, err := measure(n)
|
||||
if err != nil { panic(err) }
|
||||
fmt.Println(checksum)
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def source(language, shape):
|
||||
if shape == 'http':
|
||||
return http_source(language)
|
||||
if shape == 'http_stream':
|
||||
return http_stream_source(language)
|
||||
if shape == 'http_pool':
|
||||
return http_pool_source(language)
|
||||
if shape == 'net':
|
||||
return net_source(language)
|
||||
if shape == 'tls':
|
||||
return tls_source(language)
|
||||
if shape == 'arguments':
|
||||
return arguments_source(language)
|
||||
if shape == 'stdout':
|
||||
return stdout_source(language)
|
||||
if shape == 'concurrent':
|
||||
return concurrent_source(language)
|
||||
if shape == 'file_stream':
|
||||
return file_stream_source(language)
|
||||
if shape in ('file', 'file_stream'):
|
||||
return file_source(language)
|
||||
if shape == 'token':
|
||||
return token_source(language)
|
||||
if shape == 'parallel':
|
||||
return parallel_source(language)
|
||||
if shape == 'calendar':
|
||||
return calendar_source(language)
|
||||
if shape == 'async':
|
||||
return async_source(language)
|
||||
if shape == 'port':
|
||||
return port_source(language)
|
||||
if shape == 'settings':
|
||||
return settings_source(language)
|
||||
if shape == 'crypto':
|
||||
return crypto_source(language)
|
||||
if shape == 'uuid':
|
||||
return uuid_source(language)
|
||||
if shape == 'standard':
|
||||
return standard_source(language)
|
||||
if shape == 'bytes':
|
||||
return bytes_source(language)
|
||||
if shape == 'fields':
|
||||
return field_source(language)
|
||||
if shape == 'walk':
|
||||
return walk_source(language)
|
||||
if shape in ('fold', 'foldUntil'):
|
||||
return fold_source(language, shape == 'foldUntil')
|
||||
if shape == 'index':
|
||||
return index_source(language)
|
||||
if shape == 'group':
|
||||
return group_source(language)
|
||||
filtered = shape == 'filtered'
|
||||
if language == 'dever':
|
||||
body = (
|
||||
'loop totals(n: Int) (total: Int, count: Int)\n'
|
||||
'| each value in range(0, n) | value % 2 | result |\n'
|
||||
'| total | 0 | sum value |\n| count | - | count |\n'
|
||||
'measure(n: Int) (out: Int) { result = totals(n)\nout = result.total + result.count }\n'
|
||||
if filtered else
|
||||
'loop measure(n: Int) (out: Int)\n| each value in range(0, n) | result |\n| out | sum value |\n'
|
||||
)
|
||||
return body + 'cmd bench = app.measure\n'
|
||||
if language == 'rust':
|
||||
accumulation = 'if value % 2 == 0 { total = total.checked_add(value).expect("sum overflow"); }\ncount = count.checked_add(1).expect("count overflow");' if filtered else 'total = total.checked_add(value).expect("sum overflow");'
|
||||
result = 'total.checked_add(count).expect("result overflow")' if filtered else 'total'
|
||||
return '''use std::env;
|
||||
fn measure(n: i64) -> i64 {
|
||||
let mut total = 0i64;
|
||||
''' + (' let mut count = 0i64;\n' if filtered else '') + f''' for value in 0..n {{
|
||||
{accumulation}
|
||||
}}
|
||||
{result}
|
||||
}}
|
||||
fn main() {{
|
||||
let n = env::args().nth(1).unwrap().parse::<i64>().unwrap();
|
||||
println!("{{}}", measure(n));
|
||||
}}
|
||||
'''
|
||||
accumulation = 'if value % 2 == 0 { total = add(total, value) }; count = add(count, 1)' if filtered else 'total = add(total, value)'
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func add(a, b int64) int64 {
|
||||
result := a + b
|
||||
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
|
||||
return result
|
||||
}
|
||||
func measure(n int64) int64 {
|
||||
total := int64(0)
|
||||
''' + (' count := int64(0)\n' if filtered else '') + f''' for value := int64(0); value < n; value++ {{
|
||||
{accumulation}
|
||||
}}
|
||||
return {"add(total, count)" if filtered else "total"}
|
||||
}}
|
||||
func main() {{
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil {{ panic(err) }}
|
||||
fmt.Println(measure(n))
|
||||
}}
|
||||
'''
|
||||
|
||||
|
||||
def fold_source(language, until):
|
||||
if language == 'dever':
|
||||
update = ('update(value: Int, previous: Int, limit: Int) (acc: Int, stop: Bool) { acc = previous + value\nstop = value >= limit }\n' if until else
|
||||
'update(value: Int, previous: Int) (out: Int) { out = previous + value }\n')
|
||||
aggregation = 'foldUntil(acc = 0, update(value, acc, n // 2))' if until else 'fold(acc = 0, update(value, acc))'
|
||||
return update + 'loop measure(n: Int) (out: Int)\n| each value in range(0, n) | result |\n| out | ' + aggregation + ' |\ncmd bench = app.measure\n'
|
||||
if language == 'rust':
|
||||
update = ('fn update(value: i64, previous: i64, limit: i64) -> (i64, bool) { (previous.checked_add(value).expect("sum overflow"), value >= limit) }' if until else
|
||||
'fn update(value: i64, previous: i64) -> i64 { previous.checked_add(value).expect("sum overflow") }')
|
||||
step = 'let (next, stop) = update(value, acc, n / 2); acc = next; if stop { break; }' if until else 'acc = update(value, acc);'
|
||||
return update + f'''
|
||||
fn measure(n: i64) -> i64 {{
|
||||
let mut acc = 0;
|
||||
for value in 0..n {{ {step} }}
|
||||
acc
|
||||
}}
|
||||
fn main() {{
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{{}}", measure(n));
|
||||
}}
|
||||
'''
|
||||
update = ('func update(value, previous, limit int64) (int64, bool) { return add(previous, value), value >= limit }' if until else
|
||||
'func update(value, previous int64) int64 { return add(previous, value) }')
|
||||
step = 'next, stop := update(value, acc, n / 2); acc = next; if stop { break }' if until else 'acc = update(value, acc)'
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func add(a, b int64) int64 {
|
||||
result := a + b
|
||||
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
|
||||
return result
|
||||
}
|
||||
''' + update + f'''
|
||||
func measure(n int64) int64 {{
|
||||
acc := int64(0)
|
||||
for value := int64(0); value < n; value++ {{ {step} }}
|
||||
return acc
|
||||
}}
|
||||
func main() {{
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil {{ panic(err) }}
|
||||
fmt.Println(measure(n))
|
||||
}}
|
||||
'''
|
||||
|
||||
|
||||
def walk_source(language):
|
||||
if language == 'dever':
|
||||
return '''rule next(state: Int) (out: Walk<Int, Int>)
|
||||
| state | out |
|
||||
| > 0 | Next(state - 1, state - 1) |
|
||||
| <= 0 | Done |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in walk(n, next) | result |
|
||||
| out | sum value |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''enum Step { Next(i64, i64), Done }
|
||||
fn next(state: i64) -> Step {
|
||||
if state > 0 { Step::Next(state.checked_sub(1).expect("state overflow"), state.checked_sub(1).expect("state overflow")) } else { Step::Done }
|
||||
}
|
||||
fn measure(mut state: i64) -> i64 {
|
||||
let mut total = 0i64;
|
||||
loop {
|
||||
let item = match next(state) { Step::Next(item, next_state) => { state = next_state; item }, Step::Done => break };
|
||||
total = total.checked_add(item).expect("sum overflow");
|
||||
}
|
||||
total
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{}", measure(n));
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
type step struct { item, state int64; done bool }
|
||||
func next(state int64) step {
|
||||
if state > 0 { return step{item: state - 1, state: state - 1} }
|
||||
return step{done: true}
|
||||
}
|
||||
func measure(state int64) int64 {
|
||||
total := int64(0)
|
||||
for {
|
||||
result := next(state)
|
||||
if result.done { break }
|
||||
state = result.state
|
||||
sum := total + result.item
|
||||
if (result.item > 0 && sum < total) || (result.item < 0 && sum > total) { panic("sum overflow") }
|
||||
total = sum
|
||||
}
|
||||
return total
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
fmt.Println(measure(n))
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def field_source(language):
|
||||
if language == 'dever':
|
||||
return '''type Pair { left: List<Int>, right: List<Int> }
|
||||
swap(previous: Pair) (out: Pair) { out = Pair { left = previous.right, right = previous.left } }
|
||||
loop values(n: Int, offset: Int) (out: List<Int>)
|
||||
| each value in range(0, n) | result |
|
||||
| out | list value + offset |
|
||||
loop swapped(seed: Pair) (out: Pair)
|
||||
| each value in range(0, 1001) | result |
|
||||
| out | fold(acc = seed, swap(acc)) |
|
||||
loop total(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
measure(n: Int) (out: Int) {
|
||||
pair = swapped(Pair { left = values(n, 0), right = values(n, 1) })
|
||||
out = total(pair.left) + 2 * total(pair.right)
|
||||
}
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''struct Pair { left: Vec<i64>, right: Vec<i64> }
|
||||
fn swap(previous: Pair) -> Pair { Pair { left: previous.right, right: previous.left } }
|
||||
fn total(values: &[i64]) -> i64 {
|
||||
values.iter().fold(0i64, |sum, value| sum.checked_add(*value).expect("sum overflow"))
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut left = Vec::with_capacity(n as usize);
|
||||
let mut right = Vec::with_capacity(n as usize);
|
||||
for value in 0..n { left.push(value); }
|
||||
for value in 0..n { right.push(value.checked_add(1).expect("value overflow")); }
|
||||
let mut pair = Pair { left, right };
|
||||
for _ in 0..1001 { pair = swap(pair); }
|
||||
let checksum = total(&pair.left).checked_add(total(&pair.right).checked_mul(2).expect("multiply overflow")).expect("checksum overflow");
|
||||
println!("{checksum}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
type pair struct { left, right []int64 }
|
||||
func swap(previous pair) pair { return pair{left: previous.right, right: previous.left} }
|
||||
func add(a, b int64) int64 {
|
||||
result := a + b
|
||||
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
|
||||
return result
|
||||
}
|
||||
func total(values []int64) int64 {
|
||||
sum := int64(0)
|
||||
for _, value := range values { sum = add(sum, value) }
|
||||
return sum
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
left, right := make([]int64, 0, n), make([]int64, 0, n)
|
||||
for value := int64(0); value < n; value++ { left = append(left, value) }
|
||||
for value := int64(0); value < n; value++ { right = append(right, add(value, 1)) }
|
||||
state := pair{left: left, right: right}
|
||||
for i := 0; i < 1001; i++ { state = swap(state) }
|
||||
subtotal := total(state.right)
|
||||
fmt.Println(add(total(state.left), add(subtotal, subtotal)))
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--compiler', type=Path, required=True)
|
||||
parser.add_argument('--old-compiler', type=Path, help='frozen R0 compiler for the supported standard-library workloads')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--size', type=int, default=300_000_000)
|
||||
parser.add_argument('--shape', nargs='+', choices=['sum', 'filtered', 'group', 'index', 'fold', 'foldUntil', 'walk', 'fields', 'bytes', 'standard', 'uuid', 'calendar', 'settings', 'port', 'crypto', 'token', 'file', 'file_stream', 'async', 'parallel', 'concurrent', 'stdout', 'arguments', 'net', 'tls', 'http', 'http_pool', 'http_stream'], default=['sum', 'filtered'])
|
||||
parser.add_argument('--core-source', type=Path)
|
||||
parser.add_argument('--runtime-reference', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.old_compiler and not set(args.shape) <= LEGACY_SHAPES:
|
||||
parser.error('old-compiler currently supports standard, uuid and calendar')
|
||||
if not 1 <= args.size <= 1_000_000_000:
|
||||
parser.error('size must be between 1 and 1000000000')
|
||||
if args.runtime_reference and (args.shape not in (['concurrent'], ['arguments'], ['net']) or not args.core_source):
|
||||
parser.error('runtime-reference requires --shape concurrent|arguments|net and --core-source')
|
||||
languages = ['dever', 'rust', 'go'] + (['old'] if args.old_compiler else []) + (['runtime'] if args.runtime_reference else [])
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
(root / 'legacy_reference.py').write_bytes(Path(__file__).with_name('legacy_reference.py').read_bytes())
|
||||
for name in ['loop.py', 'scale.py', 'bytes_reference.py', 'standard_reference.py', 'uuid_reference.py', 'calendar_reference.py', 'settings_reference.py', 'port_reference.py', 'crypto_reference.py', 'token_reference.py', 'file_reference.py', 'file_stream_reference.py', 'async_reference.py', 'parallel_reference.py', 'concurrent_reference.py', 'stdout_reference.py', 'arguments_reference.py', 'net_reference.py', 'tls_reference.py', 'http_reference.py', 'http_pool_reference.py', 'http_stream_reference.py']:
|
||||
(root / name).write_bytes(Path(__file__).with_name(name).read_bytes())
|
||||
os.environ['CARGO_BUILD_JOBS'] = '1'
|
||||
os.environ['GOMAXPROCS'] = '1'
|
||||
os.environ['GOTOOLCHAIN'] = 'local'
|
||||
cgroup = Path('/sys/fs/cgroup')
|
||||
report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler),
|
||||
cpu_affinity=sorted(os.sched_getaffinity(0)),
|
||||
driver_sha256=fingerprint(root / 'loop.py'), rounds=7, size=args.size,
|
||||
semantics='signed 64-bit checked sum; lazy half-open range; filtered rows keep declaration order; group uses 64 buckets in first-key order and checksums every value; index keeps key order, checks duplicates and checksums every key/value; fold uses a named state update; foldUntil adopts the updated state before stopping at value >= n/2; walk uses a named Next/Done stepper counting down from n-1 to 0; fields swaps two n-element lists 1001 times and computes a weighted sum; bytes creates n integers modulo 256, validates and converts to Bytes, shares slice [1,n), then checksums every byte; standard decorates each integer with Unicode whitespace and snow, trims, splits into scalars, rejoins, replaces snow, parses and checksums every integer; uuid creates a varying canonical identifier, strictly parses, formats, reads its last Unicode scalar and sums that decimal digit; calendar adds successive millisecond offsets, formats canonical UTC, parses and checks the exact difference; settings loads a valid typed configuration once, borrows its corpus and sums every value whose decimal residue modulo 1000 appears in the corpus; crypto uses a public benchmark key from configuration and hashes each varying decimal message with HMAC-SHA256 then SHA256 and sums every digest byte; async executes ordered direct async calls with one 1ms timer per million inputs and checksums every value; Go uses its native sleep and has a different timer resolution',
|
||||
scope='whole-process time; Dever additionally decodes one small JSON argument and encodes its response; Rust/Go parse one decimal argument',
|
||||
memory_scope='wait4 peak_rss may include the Python fork before exec; these samples do not establish application-only RSS',
|
||||
environment=dict(cpu_max=(cgroup/'cpu.max').read_text().strip(),
|
||||
memory_max=(cgroup/'memory.max').read_text().strip()),
|
||||
versions={}, builds=[], samples=[])
|
||||
if args.old_compiler:
|
||||
old = args.old_compiler.resolve(strict=True)
|
||||
report['old_compiler'] = dict(path=str(old), sha256=fingerprint(old))
|
||||
report['old_semantics'] = 'Frozen language uses sum(each(..., range(...))); current language uses loop tables. Same operations, inputs, checked checksum and locked reference dependencies. Old and new language implementations retain their own allocation strategies; no full standard-library contract parity claim.'
|
||||
if 'port' in args.shape:
|
||||
report['port_semantics'] = 'Two concrete implementations, contains and prefix, selected once from the same startup configuration; contains selected in this workload. Each call dispatches over the selected implementation, borrows its text corpus and searches the decimal residue. Rust uses a concrete enum and directly owned private settings, the same locked Serde versions, and no Dever runtime. Go uses a checked startup selector. All results are checked against the settings checksum; invalid configuration, effects, task sharing and error obligations are covered by functional tests, not this timing.'
|
||||
if 'parallel' in args.shape:
|
||||
report['parallel_semantics'] = 'Each input concurrently calls item(value) and item(value+1), waits for both, checks signed 64-bit addition and sums all pairs. Each item sleeps 1ms when divisible by one million. Rust uses the same Tokio biased try_join and direct futures; Go uses two goroutines and a WaitGroup with GOMAXPROCS=1. This measures successful completion, not cancellation/error equivalence; timer resolution and scheduling differ.'
|
||||
if 'token' in args.shape:
|
||||
report['token_semantics'] = 'Generate a new 32-byte key from the real OS secure random source for each varying decimal input, compute two HMAC-SHA256 digests, compare all digest bytes and checksum the validated inputs. Rust uses the same getrandom/RustCrypto/Bytes/Zeroizing without Dever runtime. Go uses crypto/rand, hmac and clear; this does not prove equivalent zeroization or RNG failure behavior.'
|
||||
report['cpu_affinity'] = sorted(os.sched_getaffinity(0))
|
||||
if any(shape in ('file', 'file_stream') for shape in args.shape):
|
||||
fixture = root / 'input.bin'
|
||||
pattern = bytes(range(64)) * 1024
|
||||
with fixture.open('xb') as output:
|
||||
full, tail = divmod(args.size, 1024)
|
||||
for _ in range(full):
|
||||
output.write(pattern)
|
||||
output.write(bytes(range(64)) * tail)
|
||||
report['file_fixture'] = dict(path=str(fixture), sha256=fingerprint(fixture), bytes=fixture.stat().st_size)
|
||||
report['file_semantics'] = 'Shared file cursor, n synchronous 64-byte reads, checked sum of every returned byte, explicit EOF probe and close. File prepared before builds/timing; warm page cache. Independent Rust uses std File/Mutex/Arc and Bytes, no Dever runtime; Go uses os.File and Mutex. This measures successful reads, not durable writes, cold storage or cancellation.'
|
||||
if 'file_stream' in args.shape:
|
||||
report['file_stream_semantics'] = 'Lazily read the same shared file through a shared synchronous stream at 64 bytes per chunk, sum every byte and count every chunk, close the stream and verify a second traversal is empty while retaining the file alias for explicit close. Independent Rust uses std Arc/Mutex and Bytes without Dever runtime. Go uses os.File and Mutex. Error and short-circuit behavior tested separately.'
|
||||
if 'arguments' in args.shape:
|
||||
report['arguments_semantics'] = 'All peers receive identical argv[1..]: command name and JSON input. Each iteration obtains a fresh argument list, checks UTF-8 and sums every Unicode character with checked Int arithmetic. Rust uses std args_os without Dever runtime; Go copies its slice and shares immutable string contents. Allocation contracts are language-specific.'
|
||||
report['arguments_scope'] = 'Whole-process time; all peers decode the same JSON object. Dever wraps the final checksum in its response envelope. The optional runtime peer only diagnoses generated-layer cost and is not an independent Rust reference.'
|
||||
if 'net' in args.shape:
|
||||
report['net_semantics'] = 'One persistent loopback TCP pair, TCP_NODELAY on both ends; each iteration writes value modulo 251 as one byte, reads and verifies it, then increments a checked count. Rust uses Tokio directly without Dever runtime; no alias-close, cancellation or read/write-lock equivalence is claimed by this success-path timing. Go uses its standard TCP stack with GOMAXPROCS=1. Tests separately cover close, cancellation, streams and deadlines.'
|
||||
if 'stdout' in args.shape:
|
||||
report['stdout_semantics'] = 'Write decimal values 0..n as separate lines, then the checked count; validate every line outside the timed process. Rust uses std stdout lock and writeln without Dever runtime. Files retain real output; this is successful writing, not equivalent error handling or durable storage.'
|
||||
if 'concurrent' in args.shape:
|
||||
report['concurrent_semantics'] = 'n ordered results, capacity 64 including pending delivery, one real 1ms timer per 4096 inputs, validate each delivered value against its position. Rust uses futures-util buffered without Dever runtime; Go uses 64 workers with a bounded ordered window. This success workload does not establish equivalent failure observation/cancellation contracts.'
|
||||
source_hashes = {}
|
||||
if 'tls' in args.shape:
|
||||
report['tls_semantics'] = 'Repeatedly parse the same CA PEM and construct a shared TLS client configuration with the default session cache; count only successful configurations. Rust directly uses the same locked rustls/ring without Dever runtime. Go uses crypto/x509 and crypto/tls. This is configuration cost, not handshake throughput or equivalent certificate-policy behavior; real handshake rejection is tested separately.'
|
||||
if args.core_source:
|
||||
core = args.core_source.resolve(strict=True)
|
||||
inputs = [core / 'rust/Cargo.lock']
|
||||
inputs += sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.is_file() and path.suffix in {'.rs', '.toml'})
|
||||
inputs += sorted((core / 'lib').rglob('*.dv'))
|
||||
source_hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs}
|
||||
locked_packages = {
|
||||
(p['name'], p['version'], p.get('source'))
|
||||
for p in tomllib.loads((core/'rust/Cargo.lock').read_text())['package']
|
||||
}
|
||||
for path in inputs:
|
||||
saved = root / 'inputs' / path.relative_to(core)
|
||||
saved.parent.mkdir(parents=True, exist_ok=True)
|
||||
saved.write_bytes(path.read_bytes())
|
||||
report.update(core_source=str(core), source_hashes=source_hashes)
|
||||
def save():
|
||||
(root/'results.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
for language, command in [('rust', ['rustc', '+1.95.0', '--version', '--verbose']), ('go', ['go', 'version'])]:
|
||||
result = execute(command, root, language + '-version', 30)
|
||||
if result['exit_code']: raise SystemExit(result['stderr'])
|
||||
report['versions'][language] = Path(result['stdout']).read_text()
|
||||
programs = {}
|
||||
if any(shape in args.shape for shape in ['http', 'http_pool', 'http_stream']):
|
||||
port = http_server(root)
|
||||
if 'http' in args.shape:
|
||||
report['http_semantics'] = 'Each iteration opens a new loopback HTTP/1 connection to the same Node echo fixture, sends the varying decimal input, checks status, bounds the response body and verifies every returned byte. CPU affinity includes the fixture. Rust uses the same locked Hyper/Tokio without Dever runtime; Go uses net/http with keep-alive disabled. No pool, TLS, HTTP/2, load/concurrency or full protocol-error equivalence is claimed by this successful sequential workload.'
|
||||
if 'http_pool' in args.shape:
|
||||
report['http_pool_semantics'] = 'Same varying body, status/header/body bounds and every returned byte checked; one shared HTTP/1 client per process, 10000ms idle timeout, no retries. Independent Rust uses locked Hyper legacy Client directly; Go uses net/http keep-alive. Sequential successful calls only; TLS/H2, concurrency, cancellation, fault tracking and DNS lifecycle are covered by separate functional tests, not equivalent performance claims.'
|
||||
if 'http_stream' in args.shape:
|
||||
report['http_stream_semantics'] = 'Same HTTP/1 pool and varying body as http_pool; download incrementally, compare every chunk at its exact offset and verify final length without collecting the response. Rust uses Hyper frames directly, Go uses Body.Read. Successful small-response cost only, not full timeout/TLS/cancellation or bounded-memory large-stream equivalence.'
|
||||
report['http_server_sha256'] = fingerprint(root/'http-server.cjs')
|
||||
for shape in args.shape:
|
||||
for language in languages:
|
||||
case = root/f'{shape}-{language}'
|
||||
case.mkdir()
|
||||
path = case/('main.' + dict(dever='dever', old='dever', rust='rs', go='go', runtime='rs')[language])
|
||||
if language == 'old':
|
||||
domain = case / 'module/main/main'
|
||||
domain.mkdir(parents=True)
|
||||
path = domain / 'app.dever'
|
||||
(domain / 'api.dever').write_text('cmd bench = app.measure\n')
|
||||
text = legacy_source(shape).removesuffix('cmd bench = app.measure\n') if language == 'old' else source(language, shape)
|
||||
path.write_text(text)
|
||||
binary = case/'program'
|
||||
if language in ('dever', 'old'):
|
||||
tool = old if language == 'old' else compiler
|
||||
application = case if language == 'old' else port_project(case, path.read_text()) if shape == 'port' else path
|
||||
formatted = execute([str(tool), 'fmt', str(application)], case, 'format', 30)
|
||||
if formatted['exit_code']: raise SystemExit(formatted['stderr'])
|
||||
command = [str(tool), 'build', str(application), '--output', str(binary)]
|
||||
elif language in ('rust', 'runtime') and shape in ('group', 'index', 'bytes', 'uuid', 'calendar', 'settings', 'port', 'crypto', 'token', 'file', 'file_stream', 'async', 'parallel', 'concurrent', 'arguments', 'net', 'tls', 'http', 'http_pool', 'http_stream'):
|
||||
dependencies = 'bytes = "=1.12.1"' if shape == 'bytes' else 'indexmap = "=2.14.0"\nahash = "=0.8.12"'
|
||||
if shape in ('async', 'parallel', 'concurrent'):
|
||||
dependencies = 'tokio = { version = "=1.53.1", features = ["rt", "time", "macros", "sync"] }'
|
||||
if shape == 'concurrent':
|
||||
dependencies += '\nfutures-util = "=0.3.34"'
|
||||
if shape == 'arguments':
|
||||
dependencies = 'serde_json = "=1.0.145"'
|
||||
if shape == 'net':
|
||||
dependencies = 'tokio = { version = "=1.53.1", features = ["rt", "net", "io-util", "time"] }\nbytes = "=1.12.1"'
|
||||
if language == 'runtime':
|
||||
features = ', features = ["net"]' if shape == 'net' else ''
|
||||
dependencies += '\ndever-runtime = { path = ' + json.dumps(str(core / 'rust/src/runtime')) + features + ' }'
|
||||
if shape == 'uuid':
|
||||
dependencies = 'uuid = "=1.28.0"'
|
||||
if shape == 'calendar':
|
||||
dependencies = 'chrono = { version = "=0.4.45", default-features = false, features = ["std"] }'
|
||||
if shape in ('settings', 'port'):
|
||||
dependencies = 'serde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"'
|
||||
if shape == 'tls':
|
||||
dependencies = 'rustls = { version = "=0.23.44", default-features = false, features = ["std", "ring", "tls12"] }\nserde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"'
|
||||
if shape in ('http', 'http_pool', 'http_stream'):
|
||||
dependencies = '\n'.join(['hyper = { version = "=1.11.1", features = ["http1", "http2", "client", "server"] }', 'hyper-util = { version = "=0.1.20", features = ["tokio"] }', 'http-body-util = "=0.1.5"', 'tokio = { version = "=1.53.1", features = ["rt", "net", "io-util", "time", "macros"] }', 'bytes = "=1.12.1"', 'serde = { version = "=1.0.228", features = ["derive"] }', 'serde_json = "=1.0.145"'])
|
||||
if shape in ('http_pool', 'http_stream'):
|
||||
dependencies = dependencies.replace('features = ["tokio"]', 'features = ["tokio", "client-legacy", "http1", "http2"]')
|
||||
if shape in ('file', 'file_stream'):
|
||||
dependencies = chr(10).join(['bytes = "=1.12.1"', 'serde = { version = "=1.0.228", features = ["derive"] }', 'serde_json = "=1.0.145"'])
|
||||
if shape == 'token':
|
||||
dependencies = chr(10).join(['getrandom = "=0.2.17"', 'sha2 = "=0.10.9"', 'hmac = "=0.12.1"', 'bytes = "=1.12.1"', 'zeroize = "=1.9.0"', 'subtle = "=2.6.1"'])
|
||||
if shape == 'crypto':
|
||||
dependencies = 'serde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"\nsha2 = "=0.10.9"\nhmac = "=0.12.1"\nbytes = "=1.12.1"\nzeroize = "=1.9.0"'
|
||||
(case/'Cargo.toml').write_text('''[package]
|
||||
name = "collection-reference"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "collection-reference"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
''' + dependencies + '''
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = "symbols"
|
||||
''')
|
||||
if args.core_source:
|
||||
# 参考端沿用核心锁中的传递依赖,避免离线缓存选出不同版本。
|
||||
(case/'Cargo.lock').write_bytes((core/'rust/Cargo.lock').read_bytes())
|
||||
command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case/'Cargo.toml'), '--offline', '--release', '--target-dir', str(case/'target')]
|
||||
binary = case/'target/release/collection-reference'
|
||||
elif language == 'rust':
|
||||
command = ['rustc', '+1.95.0', '--edition=2024', '-C', 'opt-level=3', '-C', 'lto=fat', '-C', 'codegen-units=1', '-C', 'overflow-checks=true', '-C', 'strip=symbols', str(path), '-o', str(binary)]
|
||||
else:
|
||||
(case/'go.mod').write_text(f'module loop-reference/{root.name}/{shape}\n\ngo 1.25.0\n')
|
||||
command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-o', str(binary), '.']
|
||||
result = dict(language=language, shape=shape, source_sha256=fingerprint(path),
|
||||
source_lines=len(path.read_text().splitlines()), **execute(command, case, 'build', 900))
|
||||
if (shape == 'port' and language == 'dever') or language == 'old':
|
||||
result['project_sources'] = {str(p.relative_to(case)): fingerprint(p) for p in sorted((case/'module').rglob('*.dever'))}
|
||||
result['source_lines'] = sum(len(p.read_text().splitlines()) for p in (case/'module').rglob('*.dever'))
|
||||
report['builds'].append(result)
|
||||
if result['exit_code']:
|
||||
save()
|
||||
raise SystemExit(result['stderr'])
|
||||
result['binary_sha256'] = fingerprint(binary)
|
||||
if language in ('rust', 'runtime') and (case/'Cargo.lock').exists():
|
||||
result['lock_sha256'] = fingerprint(case/'Cargo.lock')
|
||||
if args.core_source:
|
||||
packages = tomllib.loads((case/'Cargo.lock').read_text())['package']
|
||||
different = [(p['name'], p['version'], p.get('source')) for p in packages
|
||||
if p.get('source') and (p['name'], p['version'], p['source']) not in locked_packages]
|
||||
result['dependency_differences'] = different
|
||||
if different:
|
||||
save()
|
||||
raise SystemExit(f'reference dependencies differ from core lock: {different}')
|
||||
if shape in ('settings', 'port', 'crypto', 'file', 'file_stream', 'tls', 'http', 'http_pool', 'http_stream'):
|
||||
config = case / 'setting.json'
|
||||
value = port_config() if shape == 'port' else settings_config() if shape == 'settings' else crypto_config()
|
||||
if shape in ('http', 'http_pool', 'http_stream'):
|
||||
value = {'module': {'main': {'main': {'port': port}}}}
|
||||
if shape == 'tls':
|
||||
ca_pem = (Path(__file__).parent.parent/'fixtures/tls/root.pem').read_text()
|
||||
value = {'module': {'main': {'main': {'ca_pem': ca_pem}}}}
|
||||
if shape in ('file', 'file_stream'):
|
||||
value = {'module': {'main': {'main': {'input': str(root / 'input.bin')}}}}
|
||||
config.write_text(json.dumps(value, ensure_ascii=False))
|
||||
result['config_sha256'] = fingerprint(config)
|
||||
programs[shape, language] = binary
|
||||
save()
|
||||
# 预热也核验并留原始结果,不混入固定七轮统计。输入由进程参数传入。
|
||||
for repeat in range(-1, 7):
|
||||
if source_hashes:
|
||||
assert source_hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime/library inputs changed during measurement'
|
||||
for shape in args.shape:
|
||||
for offset in range(len(languages)):
|
||||
language = languages[(repeat + 1 + offset) % len(languages)]
|
||||
binary = programs[shape, language]
|
||||
n = args.size
|
||||
count = (n + 1) // 2
|
||||
expected = n * (n - 1) // 2 if shape != 'filtered' else count * (count - 1) + n
|
||||
if shape == 'group':
|
||||
expected += min(n, 64) * (min(n, 64) - 1) // 2
|
||||
elif shape == 'index':
|
||||
expected *= 2
|
||||
elif shape == 'foldUntil':
|
||||
consumed = min(n, n // 2 + 1)
|
||||
expected = consumed * (consumed - 1) // 2
|
||||
elif shape == 'fields':
|
||||
expected = 3 * expected + n
|
||||
elif shape == 'calendar':
|
||||
expected = n
|
||||
elif shape == 'parallel':
|
||||
expected = n * n
|
||||
elif shape in ('concurrent', 'stdout', 'net', 'tls', 'http', 'http_pool', 'http_stream'):
|
||||
expected = n
|
||||
elif shape == 'arguments':
|
||||
expected = n * (len('main.main.bench') + len(json.dumps(dict(n=n))))
|
||||
elif shape in ('settings', 'port'):
|
||||
expected = settings_expected(n)
|
||||
elif shape in ('file', 'file_stream'):
|
||||
expected = n * sum(range(64))
|
||||
elif shape == 'crypto':
|
||||
expected = crypto_expected(n)
|
||||
elif shape == 'uuid':
|
||||
expected = (n // 10) * 45 + (n % 10) * ((n % 10) - 1) // 2
|
||||
elif shape == 'bytes':
|
||||
expected = (n // 256) * 32640 + (n % 256) * ((n % 256) - 1) // 2
|
||||
command = [str(binary), 'main.main.bench', json.dumps(dict(n=n))] if language in ('dever', 'old') or shape == 'arguments' else [str(binary), str(n)]
|
||||
if shape in ('settings', 'port', 'crypto', 'file', 'file_stream', 'tls', 'http', 'http_pool', 'http_stream'):
|
||||
config = root / f'{shape}-{language}' / 'setting.json'
|
||||
if language == 'dever':
|
||||
command[1:1] = ['--config', str(config)]
|
||||
else:
|
||||
command.append(str(config))
|
||||
result = dict(language=language, shape=shape, repeat=repeat, expected=expected,
|
||||
**execute(command, binary.parent, f'run-{repeat}', 60))
|
||||
output = Path(result['stdout']).read_text()
|
||||
if shape == 'stdout':
|
||||
rows = output.splitlines()
|
||||
result['correct'] = (result['exit_code'] == 0 and len(rows) == n + 1
|
||||
and all(row == str(index) for index, row in enumerate(rows[:-1]))
|
||||
and (json.loads(rows[-1])['data'] if language == 'dever' else int(rows[-1])) == expected)
|
||||
else:
|
||||
result['correct'] = result['exit_code'] == 0 and (json.loads(output)['data'] if language in ('dever', 'old') else int(output)) == expected
|
||||
report['samples'].append(result)
|
||||
save()
|
||||
print(json.dumps(result), flush=True)
|
||||
if not result['correct']: raise SystemExit('incorrect result: ' + result['stderr'])
|
||||
report['medians'] = {shape: {language: statistics.median(
|
||||
sample['seconds'] for sample in report['samples']
|
||||
if sample['shape'] == shape and sample['language'] == language and sample['repeat'] >= 0
|
||||
) for language in languages} for shape in args.shape}
|
||||
save()
|
||||
print(json.dumps(report['medians']), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,227 @@
|
||||
"""真实 Model CMD 四方对照:原子 CRUD、输入拒绝和失败回滚;原生对端不链接 Dever。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import statistics
|
||||
import time
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def snapshot(database, table):
|
||||
with sqlite3.connect(f"file:{database}?mode=ro", uri=True) as connection:
|
||||
connection.create_function("_dever_length", 1, len, deterministic=True)
|
||||
rows = connection.execute(
|
||||
f'SELECT id,created_at,number,title,amount,note FROM "{table}" ORDER BY number'
|
||||
).fetchall()
|
||||
assert connection.execute("PRAGMA quick_check").fetchone() == ("ok",)
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--artifacts", type=Path,
|
||||
help="contains new-app, old-app, go-app, rust/target/release/model-peer and new/old projects")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--reads", action="store_true", help="build and measure full-row page/cursor/batched-relation reads")
|
||||
parser.add_argument("--compiler", type=Path, help="current compiler for --reads")
|
||||
parser.add_argument("--argv0", help="fixed process argv[0] for the read comparison; executable identity is retained")
|
||||
parser.add_argument("--title", default="中文 benchmark",
|
||||
help="title for timed batches; retained verbatim in the result identity")
|
||||
parser.add_argument("--previous", type=Path, help="same-workload prior new-version binary")
|
||||
parser.add_argument("--current", type=Path, help="candidate binary; preserves existing artifacts/new-app")
|
||||
parser.add_argument("--resource-reference", type=Path,
|
||||
help="independent Tokio/deadpool reference with SQL deadlines and cancellation drain")
|
||||
parser.add_argument("--resource-baseline", type=Path,
|
||||
help="retain the earlier independent resource reference in the same timed run")
|
||||
args = parser.parse_args()
|
||||
if args.reads:
|
||||
if not args.compiler:
|
||||
parser.error("--reads requires --compiler")
|
||||
from model_reads import run
|
||||
run(args)
|
||||
return
|
||||
if not args.artifacts:
|
||||
parser.error("CRUD comparison requires --artifacts")
|
||||
artifacts = args.artifacts.resolve(strict=True)
|
||||
output = args.output.absolute()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
binaries = {"new": artifacts / "new-app", "old": artifacts / "old-app",
|
||||
"rust": artifacts / "rust/target/release/model-peer", "go": artifacts / "go-app"}
|
||||
if args.current:
|
||||
binaries["new"] = args.current.resolve(strict=True)
|
||||
if args.previous:
|
||||
binaries["previous"] = args.previous.resolve(strict=True)
|
||||
if args.resource_reference:
|
||||
binaries["rust-resource"] = args.resource_reference.resolve(strict=True)
|
||||
if args.resource_baseline:
|
||||
binaries["rust-resource-baseline"] = args.resource_baseline.resolve(strict=True)
|
||||
databases = {name: artifacts / name / "data/model.db" for name in binaries}
|
||||
# 旧版以可执行文件目录解析数据库相对路径;新版以 config 的项目根解析。
|
||||
databases["old"] = artifacts / "data/model.db"
|
||||
references = [name for name in binaries if name in ("rust", "rust-resource", "rust-resource-baseline", "go")]
|
||||
for name in references:
|
||||
databases[name] = output / (name + ".db")
|
||||
tables = {"new": "benchmark_article", "old": "benchmark_article_model",
|
||||
"rust": "benchmark_article", "go": "benchmark_article", "rust-resource": "benchmark_article"}
|
||||
if args.resource_baseline:
|
||||
tables["rust-resource-baseline"] = "benchmark_article"
|
||||
if args.previous:
|
||||
databases["previous"] = databases["new"]
|
||||
tables["previous"] = tables["new"]
|
||||
report = dict(rounds=7, warmups=1, sizes=[0, 1, 32, 256, 1024], cpu_affinity=[0],
|
||||
timed_title=args.title,
|
||||
contract="Each process parses one CMD, opens its SQLite database, begins IMMEDIATE, deletes prior nonnegative records, creates/reads/updates a full record per input, counts, encodes and commits. WAL/NORMAL, one connection, prepared statements, checked Int arithmetic, Unicode title and nullable note. Compare complete stored rows and transaction rollback. Wall/CPU include process startup and shutdown; verification is outside timing.",
|
||||
limitation="Rust is synchronous rusqlite; Go uses database/sql. They do not implement Dever async Scope cancellation/deadline/pool ownership or the entire Model/permission/tenant contract. Independent peers normalize title once at entry; Dever normalizes each Model write, so title-heavy cases compare each implementation's current behavior, not equal normalization cost. This is a CLI business-workload comparison, not proof of equal async resource costs. Database engine versions are recorded; differences must not be hidden.",
|
||||
binaries={name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size)
|
||||
for name, path in binaries.items()}, functional=[], samples=[])
|
||||
sources = [Path(__file__), *core.joinpath("test/performance/fixtures/model").iterdir(),
|
||||
*core.joinpath("rust/src").rglob("*.rs"),
|
||||
*core.joinpath("lib").rglob("*.dv"),
|
||||
core / "rust/Cargo.toml", core / "rust/src/runtime/Cargo.toml",
|
||||
core / "rust/Cargo.lock",
|
||||
artifacts / "rust/Cargo.toml", artifacts / "rust/Cargo.lock",
|
||||
artifacts / "go/go.mod", artifacts / "go/go.sum"]
|
||||
sources += [p for name in ("new", "old") for p in (artifacts / name / "module").rglob("*.dever")]
|
||||
if args.resource_reference:
|
||||
peer = binaries["rust-resource"].parents[2]
|
||||
sources += [peer / name for name in ("main.rs", "Cargo.toml", "Cargo.lock")]
|
||||
if (peer / "sqlite_resource.rs").exists():
|
||||
sources.append(peer / "sqlite_resource.rs")
|
||||
report["resource_reference_contract"] = "Independent Tokio current-thread runtime, deadpool SQLite pool (one connection), per-SQL blocking handoff, eight worker permits, 30s deadlines, SQLite progress cancellation, tracked blocking-result disposal, unfinished transaction discard, rollback and unclaimed panic reporting. It does not implement all Dever schema validation, named FaultInfo, multi-backend or tenant semantics; this remains a bounded resource/workload comparison."
|
||||
if args.resource_baseline:
|
||||
peer = binaries["rust-resource-baseline"].parents[2]
|
||||
sources += [peer / name for name in ("main.rs", "Cargo.toml", "Cargo.lock")]
|
||||
report["resource_baseline_contract"] = "Earlier resource peer decodes all columns but returns only id/amount across the blocking boundary. Retained as a lighter reference; full-record transfer is measured separately."
|
||||
report["sources"] = {str(p): fingerprint(p) for p in sources}
|
||||
snapshots = output / "sources"
|
||||
snapshots.mkdir()
|
||||
for index, path in enumerate(sources):
|
||||
shutil.copyfile(path, snapshots / f"{index}-{path.name}")
|
||||
for name, binary in binaries.items():
|
||||
shutil.copyfile(binary, output / (name + "-binary"))
|
||||
report["source_lines"] = {str(p): len(p.read_text().splitlines()) for p in sources}
|
||||
business = {name: sorted((artifacts / name / "module").rglob("*.dever")) for name in ("new", "old")}
|
||||
business.update(rust=[artifacts / "rust/main.rs"], go=sorted((artifacts / "go").glob("*.go")))
|
||||
if args.resource_reference:
|
||||
business["rust-resource"] = sorted(binaries["rust-resource"].parents[2].glob("*.rs"))
|
||||
report["business_sources"] = {name: [dict(path=str(p), sha256=fingerprint(p),
|
||||
physical_lines=len(p.read_text().splitlines()), nonblank_lines=sum(bool(line.strip()) for line in p.read_text().splitlines()))
|
||||
for p in paths] for name,paths in business.items()}
|
||||
report["old_source_verification"] = json.loads((artifacts / "baseline-identity.json").read_text())
|
||||
report["rust_lock_dependencies"] = [dict(name=p["name"], version=p["version"]) for p in
|
||||
tomllib.loads((artifacts / "rust/Cargo.lock").read_text())["package"]]
|
||||
|
||||
def save():
|
||||
(output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
save()
|
||||
with sqlite3.connect(f"file:{databases['new']}?mode=ro", uri=True) as connection:
|
||||
schema = connection.execute("SELECT sql FROM sqlite_master WHERE name = ?", (tables["new"],)).fetchone()[0]
|
||||
report["reference_schema"] = schema
|
||||
with sqlite3.connect(f"file:{databases['old']}?mode=ro", uri=True) as connection:
|
||||
report["old_schema"] = connection.execute("SELECT sql FROM sqlite_master WHERE name = ?", (tables["old"],)).fetchone()[0]
|
||||
for name in references:
|
||||
databases[name].parent.mkdir(exist_ok=True)
|
||||
assert not databases[name].exists(), "reference database must be new"
|
||||
with sqlite3.connect(databases[name]) as connection:
|
||||
connection.create_function("_dever_length", 1, len, deterministic=True)
|
||||
connection.execute(schema)
|
||||
version = execute([str(binaries[name]), "--sqlite-version"], output, name + "-version", 30)
|
||||
assert version["exit_code"] == 0, version
|
||||
report[name + "_sqlite_version"] = Path(version["stdout"]).read_text().strip()
|
||||
save()
|
||||
|
||||
if args.resource_reference:
|
||||
row = execute([str(binaries["rust-resource"]), "--self-test", str(output / "resource-cleanup.db")],
|
||||
output, "resource-cleanup", 30)
|
||||
report["resource_cleanup"] = row
|
||||
save()
|
||||
assert row["exit_code"] == 0, row
|
||||
|
||||
def call(name, payload, label):
|
||||
data = json.dumps(payload, ensure_ascii=False)
|
||||
if name in ("new", "old", "previous"):
|
||||
project = "new" if name == "previous" else name
|
||||
command = [str(binaries[name]), "--config", str(artifacts / project / "config/setting.json"),
|
||||
"benchmark.article.batch", data]
|
||||
else:
|
||||
command = [str(binaries[name]), str(databases[name]), data]
|
||||
return execute(command, output, label, 120)
|
||||
|
||||
def checked(name, payload, row):
|
||||
assert row["exit_code"] == 0, row
|
||||
answer = json.loads(Path(row["stdout"]).read_text())
|
||||
if name in ("new", "old", "previous"):
|
||||
assert answer["code"] == 0, answer
|
||||
answer = answer["data"]
|
||||
numbers = payload["numbers"]
|
||||
assert answer == {"checksum": sum(n + 1 for n in numbers), "count": len(numbers)}, answer
|
||||
stored = snapshot(databases[name], tables[name])
|
||||
assert [(r[2], r[3], r[4], r[5]) for r in stored] == [
|
||||
(n, payload["title"].strip(), n + 1, None) for n in sorted(numbers)]
|
||||
assert all(r[0] > 0 and 0 < r[1] <= int(time.time() * 1000) for r in stored)
|
||||
row["checked"] = True
|
||||
|
||||
invalid = [
|
||||
("unique-rollback", {"numbers": [11, 12, 11], "title": "must rollback"}),
|
||||
("overflow-rollback", {"numbers": [11, 9223372036854775807], "title": "overflow"}),
|
||||
("blank-title", {"numbers": [11], "title": " "}),
|
||||
("long-title", {"numbers": [11], "title": "中" * 121}),
|
||||
("wrong-number-type", {"numbers": ["11"], "title": "typed"}),
|
||||
("missing-numbers", {"title": "required"}),
|
||||
("unknown-field", {"numbers": [11], "title": "typed", "extra": 1}),
|
||||
]
|
||||
for name in binaries:
|
||||
payload = {"numbers": [1, 7, 3], "title": " 中文 ' OR 1=1 -- "}
|
||||
row = call(name, payload, name + "-functional-commit")
|
||||
report["functional"].append(dict(implementation=name, case="commit", **row)); save()
|
||||
checked(name, payload, row)
|
||||
report["functional"][-1]["checked"] = True
|
||||
before = snapshot(databases[name], tables[name])
|
||||
for case, payload in invalid:
|
||||
row = call(name, payload, name + "-" + case)
|
||||
report["functional"].append(dict(implementation=name, case=case, **row)); save()
|
||||
assert row["exit_code"] != 0 and not row["timeout"], row
|
||||
assert Path(row["stderr"]).read_text().strip(), row
|
||||
assert snapshot(databases[name], tables[name]) == before, (name, case, "rollback mismatch")
|
||||
report["functional"][-1]["checked"] = True
|
||||
save()
|
||||
|
||||
os.sched_setaffinity(0, {0})
|
||||
os.environ["GOMAXPROCS"] = "1"
|
||||
names = list(binaries)
|
||||
for repeat in range(-1, 7):
|
||||
assert all(fingerprint(Path(path)) == digest for path, digest in report["sources"].items())
|
||||
assert all(fingerprint(binaries[name]) == report["binaries"][name]["sha256"] for name in names)
|
||||
for size in report["sizes"]:
|
||||
payload = {"numbers": list(range(1, size + 1)), "title": args.title}
|
||||
for offset in range(len(names)):
|
||||
name = names[(repeat + 1 + offset) % len(names)]
|
||||
row = call(name, payload, f"{repeat + 1}-{size}-{name}")
|
||||
report["samples"].append(dict(implementation=name, size=size, warmup=repeat < 0, **row)); save()
|
||||
checked(name, payload, row)
|
||||
report["samples"][-1]["checked"] = True
|
||||
save()
|
||||
report["medians"] = []
|
||||
for size in report["sizes"]:
|
||||
for name in names:
|
||||
rows = [row for row in report["samples"] if not row["warmup"] and row["size"] == size and row["implementation"] == name]
|
||||
seconds = statistics.median(row["seconds"] for row in rows)
|
||||
quantiles = statistics.quantiles([row["seconds"] for row in rows], n=100, method="inclusive")
|
||||
report["medians"].append(dict(size=size, implementation=name,
|
||||
seconds=seconds, records_per_second=size / seconds,
|
||||
batch_p95_seconds=quantiles[94], batch_p99_seconds=quantiles[98],
|
||||
cpu_seconds=statistics.median(row["user_cpu_seconds"] + row["system_cpu_seconds"] for row in rows)))
|
||||
report["latency_scope"] = "p95/p99 describe seven whole-CMD batch samples, not individual SQL/request latency or a high-confidence production tail. Zero-size measures startup/schema/empty transaction overhead."
|
||||
save()
|
||||
print(json.dumps(report["medians"], indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,151 @@
|
||||
"""从冻结 R0 源码与当前编译器准备 Model 四方对端;不覆盖基线或系统工具。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def build_resource(core, root, directory="rust-resource", *, source="resource.rs.txt", target=None, dependencies="", read_boundary=None):
|
||||
"""为既有四方产物补建独立异步对端,不重建或覆盖原始产物。"""
|
||||
peer = root / directory
|
||||
peer.mkdir()
|
||||
shutil.copyfile(core / "test/performance/fixtures/model" / source, peer / "main.rs")
|
||||
shutil.copyfile(core / "test/performance/fixtures/sqlite_resource.rs.txt", peer / "sqlite_resource.rs")
|
||||
shutil.copyfile(core / "rust/Cargo.lock", peer / "Cargo.lock")
|
||||
features = []
|
||||
if read_boundary:
|
||||
shutil.copyfile(core / "test/performance/fixtures/model/reads_boundary.rs.txt", peer / "boundary.rs")
|
||||
with sqlite3.connect(f"file:{read_boundary}?mode=ro", uri=True) as db:
|
||||
schemas = db.execute("SELECT name,definition FROM _dever_history ORDER BY name").fetchall()
|
||||
# 这些是两方共用的声明输入;结构核验由独立参考自行实现。
|
||||
(peer / "schemas.rs").write_text("const SCHEMAS: &[(&str,&str)] = &[" +
|
||||
"".join(f"({json.dumps(name)},{json.dumps(sql)})," for name, sql in schemas) + "];\n")
|
||||
features = ["--features", "read-boundary"]
|
||||
manifest = '''[package]
|
||||
name = "model-resource-peer"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "model-resource-peer"
|
||||
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"
|
||||
serde = { version = "=1.0.228", features = ["derive"] }
|
||||
serde_json = "=1.0.145"
|
||||
[features]
|
||||
read-boundary = []
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = true
|
||||
'''
|
||||
(peer / "Cargo.toml").write_text(manifest.replace("[features]", dependencies + "[features]"))
|
||||
row = execute(["cargo", "+1.95.0", "build", "--offline", "--release", *features,
|
||||
"--manifest-path", str(peer / "Cargo.toml"), "--target-dir", str(target or peer / "target")],
|
||||
peer, "build", 1800)
|
||||
(peer / "build.json").write_text(json.dumps(row, indent=2) + "\n")
|
||||
assert row["exit_code"] == 0, row
|
||||
return (target or peer / "target") / "release/model-resource-peer"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--baseline", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
baseline = args.baseline.resolve(strict=True)
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.absolute()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
manifest = json.loads((baseline / "baseline-source-manifest.json").read_text())
|
||||
sources = {name: item["sha256"] for name, item in manifest["files"].items()
|
||||
if name.startswith(("rust/", "lib/"))}
|
||||
assert all(fingerprint(baseline / "restored" / name) == digest for name, digest in sources.items())
|
||||
original = json.loads((baseline / "baseline-build.json").read_text())["compiler"]
|
||||
identity = dict(verified_sources=sources, original_compiler=original,
|
||||
action="Build frozen source to separate target; retain R0 outputs")
|
||||
(root / "baseline-identity.json").write_text(json.dumps(identity, indent=2) + "\n")
|
||||
report = dict(compiler=dict(path=str(compiler), sha256=fingerprint(compiler)), commands=[])
|
||||
os.environ["CARGO_BUILD_JOBS"] = "2"
|
||||
|
||||
def run(label, command):
|
||||
row = execute([str(value) for value in command], root, label, 1800)
|
||||
report["commands"].append(row)
|
||||
(root / "build.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["exit_code"] == 0, row
|
||||
|
||||
old = root / "old-compiler-target/release/dever"
|
||||
run("old-compiler-build", ["cargo", "+1.95.0", "build", "--locked", "--offline", "--release",
|
||||
"--features", "postgres", "--bin", "dever", "--manifest-path",
|
||||
baseline / "restored/rust/Cargo.toml", "--target-dir", root / "old-compiler-target"])
|
||||
fixture = Path(__file__).parent / "fixtures/model"
|
||||
for name, tool in [("new", compiler), ("old", old)]:
|
||||
project = root / name
|
||||
module = project / "module/benchmark/article"
|
||||
module.mkdir(parents=True)
|
||||
for source in ("api.dever", "model.dever", "app.dever"):
|
||||
target = module / source
|
||||
if name == "new" and source != "api.dever":
|
||||
target = module / ("data" if source == "model.dever" else "app") / "main.dever"
|
||||
target.parent.mkdir()
|
||||
shutil.copyfile(fixture / ("old.dever.txt" if name == "old" and source == "app.dever" else source), target)
|
||||
(project / "config").mkdir()
|
||||
(project / "data").mkdir()
|
||||
config = project / "config/setting.json"
|
||||
config.write_text(json.dumps({"database": {"default": {
|
||||
"type": "sqlite", "path": "data/model.db", "max_connections": 1}}}) + "\n")
|
||||
run(name + "-format", [tool, "fmt", project])
|
||||
run(name + "-build", [tool, "build", project, "--output", root / (name + "-app")])
|
||||
if name == "new":
|
||||
run(name + "-migrate", [root / "new-app", "--config", config, "migrate"])
|
||||
else:
|
||||
run(name + "-initialize", [root / "old-app", "--config", config, "benchmark.article.count", "{}"])
|
||||
peer = root / "rust"
|
||||
peer.mkdir()
|
||||
shutil.copyfile(fixture / "peer.rs.txt", peer / "main.rs")
|
||||
shutil.copyfile(core / "rust/Cargo.lock", peer / "Cargo.lock")
|
||||
(peer / "Cargo.toml").write_text('''[package]
|
||||
name = "model-peer"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "model-peer"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
rusqlite = { version = "=0.40.2", features = ["bundled", "functions"] }
|
||||
serde = { version = "=1.0.228", features = ["derive"] }
|
||||
serde_json = "=1.0.145"
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = true
|
||||
''')
|
||||
run("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
|
||||
"--manifest-path", peer / "Cargo.toml", "--target-dir", peer / "target"])
|
||||
build_resource(core, root)
|
||||
peer = root / "go"
|
||||
peer.mkdir()
|
||||
shutil.copyfile(fixture / "peer.go.txt", peer / "main.go")
|
||||
for name in ("go.mod", "go.sum"):
|
||||
shutil.copyfile(fixture / (name + ".txt"), peer / name)
|
||||
run("go-download", ["go", "-C", peer, "mod", "download", "github.com/mattn/go-sqlite3"])
|
||||
run("go-build", ["go", "-C", peer, "build", "-buildvcs=false", "-mod=readonly", "-trimpath",
|
||||
"-ldflags=-s -w", "-o", root / "go-app", "."])
|
||||
assert all(fingerprint(baseline / "restored" / name) == digest for name, digest in sources.items())
|
||||
report["old_compiler_sha256"] = fingerprint(old)
|
||||
(root / "build.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,310 @@
|
||||
"""model.py --reads:完整行分页、游标、批量关系的同资源独立对照。"""
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import statistics
|
||||
|
||||
from model_build import build_resource
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def build(core, compiler, root):
|
||||
root.mkdir()
|
||||
identity = dict(compiler_sha256=fingerprint(compiler),
|
||||
sources={str(p): fingerprint(p) for p in [*core.joinpath("rust/src").rglob("*.rs"),
|
||||
*core.joinpath("lib").rglob("*.dv"), core / "rust/Cargo.lock"]})
|
||||
(root / "identity.json").write_text(json.dumps(identity, indent=2))
|
||||
fixture = core / "test/performance/fixtures/model"
|
||||
article = root / "project/module/benchmark/article"
|
||||
(article / "data").mkdir(parents=True)
|
||||
(article / "app").mkdir()
|
||||
shutil.copyfile(fixture / "model.dever", article / "data/main.dever")
|
||||
shutil.copyfile(fixture / "reads.dever.txt", article / "app/main.dever")
|
||||
(article / "api.dever").write_text("cmd page = app.page\ncmd cursor = app.cursor\n")
|
||||
domain = root / "project/module/benchmark/read"
|
||||
(domain / "data").mkdir(parents=True)
|
||||
(domain / "data/author.dever").write_text(
|
||||
"type Author { name: Text(1,120), note: Text? raw }\nrelation posts = data.post.author_id\n")
|
||||
(domain / "data/post.dever").write_text(
|
||||
"type Post { title: Text(1,120), author_id: data.author.id, note: Text? raw }\n")
|
||||
(domain / "app").mkdir()
|
||||
shutil.copyfile(fixture / "relations.dever.txt", domain / "app/main.dever")
|
||||
(domain / "api.dever").write_text("cmd page = app.page\n")
|
||||
config = root / "project/config/setting.json"
|
||||
config.parent.mkdir()
|
||||
(root / "project/data").mkdir()
|
||||
config.write_text(json.dumps({"database": {"default": {"type": "sqlite",
|
||||
"path": "data/model.db", "max_connections": 1, "max_page_size": 1024}}}) + "\n")
|
||||
commands = []
|
||||
|
||||
def command(label, args):
|
||||
row = execute([str(x) for x in args], root, label, 1800)
|
||||
commands.append(row)
|
||||
(root / "build.json").write_text(json.dumps(commands, indent=2) + "\n")
|
||||
assert row["exit_code"] == 0, row
|
||||
|
||||
command("format", [compiler, "fmt", root / "project"])
|
||||
command("build", [compiler, "build", root / "project", "--output", root / "new-app"])
|
||||
command("migrate", [root / "new-app", "--config", config, "migrate"])
|
||||
reference = build_resource(core, root, source="reads.rs.txt", target=core / "target/next-cargo",
|
||||
dependencies='chrono = { version = "=0.4.45", default-features = false, features = ["std"] }\n')
|
||||
shutil.copyfile(reference, root / "peer-app")
|
||||
shutil.copymode(reference, root / "peer-app")
|
||||
return root
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
text = datetime.fromtimestamp(value // 1000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
|
||||
return text + (f".{value % 1000:03d}" if value % 1000 else "") + "Z"
|
||||
|
||||
|
||||
def seed(path, count):
|
||||
"""只写本次创建的基准库;输入包含 Unicode、引号、NULL、空串和 NUL。"""
|
||||
with sqlite3.connect(path) as db:
|
||||
db.create_function("_dever_length", 1, len, deterministic=True)
|
||||
db.execute("PRAGMA foreign_keys=ON")
|
||||
for table in ("benchmark_read_post", "benchmark_read_author", "benchmark_article"):
|
||||
db.execute(f'DELETE FROM "{table}"')
|
||||
notes = (None, "", " 雪 ' \x00 raw ")
|
||||
db.executemany("INSERT INTO benchmark_article(id,created_at,number,title,amount,note) VALUES(?,?,?,?,?,?)",
|
||||
((i, 1700000000000 + i, i * 3, f"中文 article {i}", -i, notes[i % 3]) for i in range(1, count + 1)))
|
||||
db.executemany("INSERT INTO benchmark_read_author(id,created_at,name,note) VALUES(?,?,?,?)",
|
||||
((i, 1700000000000 + i, f"作者 {i}", notes[i % 3]) for i in range(1, count + 1)))
|
||||
db.executemany("INSERT INTO benchmark_read_post(id,created_at,title,author_id,note) VALUES(?,?,?,?,?)",
|
||||
((i * 3 + j, 1700000100000 + i * 3 + j, f"文章 {i}/{j}", i, notes[j])
|
||||
for i in range(1, count + 1) for j in range(i % 4)))
|
||||
|
||||
|
||||
def contents(path):
|
||||
with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db:
|
||||
assert db.execute("PRAGMA quick_check").fetchone() == ("ok",)
|
||||
columns = {"benchmark_article": ("id", "created_at", "number", "title", "amount", "note"),
|
||||
"benchmark_read_author": ("id", "created_at", "name", "note"),
|
||||
"benchmark_read_post": ("id", "created_at", "title", "author_id", "note")}
|
||||
rows = {table: [dict(zip(names, row)) for row in db.execute(
|
||||
f'SELECT {",".join(names)} FROM "{table}" ORDER BY id')] for table, names in columns.items()}
|
||||
digest = hashlib.sha256(json.dumps(rows, ensure_ascii=False).encode()).hexdigest()
|
||||
for values in rows.values():
|
||||
for row in values:
|
||||
row["created_at"] = timestamp(row["created_at"])
|
||||
return rows, digest
|
||||
|
||||
|
||||
def cases(rows):
|
||||
articles = rows["benchmark_article"]
|
||||
groups = {}
|
||||
for row in reversed(rows["benchmark_read_post"]):
|
||||
groups.setdefault(row["author_id"], []).append(row)
|
||||
authors = [dict(row, posts=groups.get(row["id"], [])) for row in rows["benchmark_read_author"]]
|
||||
result = []
|
||||
for size in (1, 32, 256, 1024):
|
||||
for position in ("first", "deep"):
|
||||
for operation, records in (("page", articles), ("cursor", articles), ("relations", authors)):
|
||||
page = 1 if position == "first" else max(2, (len(records) - 1) // size + 1)
|
||||
offset = (page - 1) * size
|
||||
items = records[offset:offset + size]
|
||||
if operation == "cursor":
|
||||
after = records[min(offset, len(records)) - 1] if records and offset else None
|
||||
payload = dict(after=after, size=size)
|
||||
has_more = offset + size < len(records)
|
||||
expected = dict(items=items, next=items[-1] if has_more else None, has_more=has_more)
|
||||
else:
|
||||
payload = dict(page=page, size=size)
|
||||
expected = dict(items=items, page=page, size=size, total=len(records),
|
||||
pages=(len(records) + size - 1) // size)
|
||||
result.append((f"{operation}-{size}-{position}", operation, payload, expected))
|
||||
return result
|
||||
|
||||
|
||||
def run(args):
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
output = args.output.absolute()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
report = dict(rounds=7, warmups=1, record_counts=[0, 4096, 65536], sizes=[1, 32, 256, 1024],
|
||||
contract="Read-only CMD; complete typed rows. OFFSET page COUNT+SELECT; composite-key cursor SELECT size+1; relation page COUNT+SELECT+one batched window SELECT for nonempty pages. Both peers own one SQLite pool connection, per-SQL blocking handoff, 30s deadline/cancellation/drain and eight permits. Identical schema/data and release/fat LTO/single CGU/checked arithmetic.",
|
||||
limitation="SQLite workload, not full four-way Model acceptance. The lighter rust-resource peer omits schema startup verification and input/wire budgets; rust-boundary adds the responsibilities explicitly listed in boundary_contract. Neither covers named Dever faults, PostgreSQL or authorization. Wall/CPU include process startup, encoding and shutdown; seven batch samples do not establish production request p99.",
|
||||
compiler=dict(path=str(compiler), sha256=fingerprint(compiler)), process_argv0=args.argv0,
|
||||
functional=[], samples=[])
|
||||
|
||||
def save():
|
||||
(output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
save()
|
||||
os.environ["CARGO_BUILD_JOBS"] = "2"
|
||||
artifacts = args.artifacts.resolve(strict=True) if args.artifacts else build(core, compiler, output / "artifacts")
|
||||
identity = json.loads((artifacts / "identity.json").read_text())
|
||||
assert identity["compiler_sha256"] == fingerprint(compiler), "artifact/compiler identity mismatch"
|
||||
assert all(fingerprint(Path(p)) == value for p, value in identity["sources"].items()), "artifact/source mismatch"
|
||||
binaries = {"new": artifacts / "new-app", "rust-resource": artifacts / "peer-app"}
|
||||
if args.previous:
|
||||
binaries["previous"] = args.previous.resolve(strict=True)
|
||||
if args.resource_baseline:
|
||||
binaries["rust-resource-baseline"] = args.resource_baseline.resolve(strict=True)
|
||||
if args.resource_reference:
|
||||
binaries["rust-boundary"] = args.resource_reference.resolve(strict=True)
|
||||
report["boundary_contract"] = "Independent Rust additionally reads the same named configuration, verifies all three compiled schema declarations against persistent history and actual SQLite catalog, and enforces named JSON objects plus byte/value/depth output limits. It still does not cover PostgreSQL, authorization, every Model operation or the entire language."
|
||||
sources = [Path(__file__), Path(__file__).with_name("model.py"), Path(__file__).with_name("model_build.py"),
|
||||
*artifacts.joinpath("project/module").rglob("*.dever"), *artifacts.joinpath("rust-resource").glob("*.rs"),
|
||||
artifacts / "rust-resource/Cargo.toml", artifacts / "rust-resource/Cargo.lock",
|
||||
*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"),
|
||||
core / "rust/Cargo.toml", core / "rust/src/runtime/Cargo.toml", core / "rust/Cargo.lock"]
|
||||
if args.resource_reference:
|
||||
reference = binaries["rust-boundary"].parent / "rust-resource"
|
||||
sources += [*reference.glob("*.rs"), reference / "Cargo.toml", reference / "Cargo.lock"]
|
||||
report["sources"] = {str(p): fingerprint(p) for p in sources}
|
||||
frozen = output / "sources"
|
||||
frozen.mkdir()
|
||||
for i, path in enumerate(sources):
|
||||
shutil.copyfile(path, frozen / f"{i}-{path.name}")
|
||||
report["binaries"] = {name: dict(path=str(binary), sha256=fingerprint(binary), bytes=binary.stat().st_size)
|
||||
for name, binary in binaries.items()}
|
||||
databases = {}
|
||||
config = output / "new/config/setting.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
(output / "new/data").mkdir()
|
||||
shutil.copyfile(artifacts / "project/config/setting.json", config)
|
||||
for name, binary in binaries.items():
|
||||
shutil.copyfile(binary, output / (name + "-binary"))
|
||||
databases[name] = output / ("new/data/model.db" if name in ("new", "previous", "rust-boundary") else name + ".db")
|
||||
with sqlite3.connect(artifacts / "project/data/model.db") as source, sqlite3.connect(databases[name]) as destination:
|
||||
source.backup(destination)
|
||||
version = execute([str(binaries["rust-resource"]), "--sqlite-version"], output, "sqlite-version", 30)
|
||||
assert version["exit_code"] == 0, version
|
||||
report["sqlite_version"] = Path(version["stdout"]).read_text().strip()
|
||||
save()
|
||||
|
||||
def call(name, operation, payload, label):
|
||||
data = json.dumps(payload, ensure_ascii=False)
|
||||
command = ([str(binaries[name]), "--config", str(config),
|
||||
"benchmark.read.page" if operation == "relations" else "benchmark.article." + operation, data]
|
||||
if name in ("new", "previous", "rust-boundary") else [str(binaries[name]), str(databases[name]), operation, data])
|
||||
return execute(command, output, label, 120, argv0=args.argv0)
|
||||
|
||||
def check(name, row, expected):
|
||||
assert row["exit_code"] == 0 and not row["timeout"], row
|
||||
answer = json.loads(Path(row["stdout"]).read_text())
|
||||
if name in ("new", "previous", "rust-boundary"):
|
||||
assert answer["code"] == 0, answer
|
||||
answer = answer["data"]
|
||||
assert answer == expected, (name, row["stdout"], "full row/page mismatch")
|
||||
row["checked"] = True
|
||||
|
||||
if args.resource_reference:
|
||||
# 同一份实际结构及篡改同时交给两方;不让参考少做启动责任。
|
||||
for case, mutation in [
|
||||
("valid", None),
|
||||
("missing-file", None),
|
||||
("missing-history", "DELETE FROM _dever_history WHERE name='benchmark_read_post'"),
|
||||
("changed-declaration", "UPDATE _dever_history SET definition='changed' WHERE name='benchmark_article'"),
|
||||
("changed-column", "ALTER TABLE benchmark_read_author ADD COLUMN changed TEXT"),
|
||||
("missing-table", "DROP TABLE benchmark_read_post"),
|
||||
("changed-index", "CREATE INDEX unexpected ON benchmark_read_author(name)"),
|
||||
]:
|
||||
directory = output / ("boundary-" + case)
|
||||
(directory / "data").mkdir(parents=True)
|
||||
(directory / "config").mkdir()
|
||||
database = directory / "data/model.db"
|
||||
if case != "missing-file":
|
||||
with sqlite3.connect(artifacts / "project/data/model.db") as source, sqlite3.connect(database) as destination:
|
||||
source.backup(destination)
|
||||
if mutation:
|
||||
destination.execute(mutation)
|
||||
test_config = directory / "config/setting.json"
|
||||
shutil.copyfile(config, test_config)
|
||||
if case == "valid":
|
||||
valid_config = test_config
|
||||
for name in ("new", "rust-boundary"):
|
||||
row = dict(implementation=name, case="schema-" + case,
|
||||
**execute([str(binaries[name]), "--config", str(test_config), "benchmark.article.page",
|
||||
'{"page":1,"size":1}'], output, "schema-" + case + "-" + name, 30, argv0=args.argv0))
|
||||
report["functional"].append(row); save()
|
||||
assert not row["timeout"], row
|
||||
if case == "valid":
|
||||
check(name, row, dict(items=[], page=1, size=1, total=0, pages=0))
|
||||
else:
|
||||
assert row["exit_code"] != 0 and Path(row["stderr"]).read_text().strip(), row
|
||||
row["checked"] = True
|
||||
if case == "missing-file":
|
||||
assert not database.exists(), "opening a missing database created a file"
|
||||
anchor = dict(id=1, created_at="2023-11-14T22:13:20.001Z", number=3, title="中文", amount=-1, note=None)
|
||||
invalid = [("root-array", "page", "[1,1]"), ("root-null", "page", "null"),
|
||||
("duplicate", "page", '{"page":1,"page":2,"size":1}'),
|
||||
("unknown", "page", '{"page":1,"size":1,"extra":0}'),
|
||||
("trailing", "page", '{"page":1,"size":1}{}'),
|
||||
("wrong-type", "page", '{"page":"1","size":1}'),
|
||||
("after-array", "cursor", json.dumps(dict(after=list(anchor.values()), size=1)))]
|
||||
for field, value in [("id", 0),
|
||||
("created_at", "2023-11-14T22:13:20.0001Z"), ("extra", 1)]:
|
||||
invalid.append(("after-" + field + "-" + str(len(invalid)), "cursor",
|
||||
json.dumps(dict(after=dict(anchor, **{field:value}), size=1))))
|
||||
for case, operation, payload in invalid:
|
||||
for name in ("new", "rust-boundary"):
|
||||
row = dict(implementation=name, case=case, **execute([str(binaries[name]), "--config", str(valid_config),
|
||||
"benchmark.article." + operation, payload], output, case + "-" + name, 30, argv0=args.argv0))
|
||||
report["functional"].append(row); save()
|
||||
assert row["exit_code"] != 0 and not row["timeout"] and Path(row["stderr"]).read_text().strip(), row
|
||||
row["checked"] = True
|
||||
# 长度和规范化属于写入边界;游标不清洗或重验这些非排序字段。
|
||||
for index, title in enumerate(("", "中" * 121, " Mixed ")):
|
||||
payload = json.dumps(dict(after=dict(anchor, title=title), size=1))
|
||||
for name in ("new", "rust-boundary"):
|
||||
row = dict(implementation=name, case="cursor-preserves-fields-" + str(index),
|
||||
**execute([str(binaries[name]), "--config", str(valid_config),
|
||||
"benchmark.article.cursor", payload], output,
|
||||
"cursor-preserves-fields-" + str(index) + "-" + name, 30, argv0=args.argv0))
|
||||
report["functional"].append(row); save()
|
||||
check(name, row, dict(items=[], next=None, has_more=False))
|
||||
save()
|
||||
|
||||
os.sched_setaffinity(0, {0})
|
||||
for count in report["record_counts"]:
|
||||
for path in set(databases.values()):
|
||||
seed(path, count)
|
||||
rows, digest = contents(databases["new"])
|
||||
assert contents(databases["rust-resource"])[1] == digest
|
||||
workloads = cases(rows)
|
||||
for repeat in range(-1, 7):
|
||||
assert all(fingerprint(Path(p)) == value for p, value in report["sources"].items())
|
||||
assert all(fingerprint(path) == report["binaries"][name]["sha256"] for name, path in binaries.items())
|
||||
for case, operation, payload, expected in workloads:
|
||||
names = list(binaries)
|
||||
offset = (repeat + 1) % len(names)
|
||||
names = names[offset:] + names[:offset]
|
||||
for name in names:
|
||||
row = dict(implementation=name, records=count, case=case, warmup=repeat < 0,
|
||||
**call(name, operation, payload, f"{count}-{repeat + 1}-{case}-{name}"))
|
||||
report["samples"].append(row)
|
||||
save()
|
||||
check(name, row, expected)
|
||||
for name in binaries:
|
||||
for case, operation, payload in [
|
||||
("zero-page", "page", dict(page=0, size=1)),
|
||||
("large-size", "page", dict(page=1, size=1025)),
|
||||
("offset-overflow", "page", dict(page=9223372036854775807, size=1024)),
|
||||
("zero-cursor", "cursor", dict(after=None, size=0)),
|
||||
("relation-large", "relations", dict(page=1, size=1025)),
|
||||
]:
|
||||
row = dict(implementation=name, records=count, case=case,
|
||||
**call(name, operation, payload, f"{count}-{case}-{name}"))
|
||||
report["functional"].append(row)
|
||||
save()
|
||||
assert row["exit_code"] != 0 and not row["timeout"] and Path(row["stderr"]).read_text().strip(), row
|
||||
row["checked"] = True
|
||||
assert contents(databases[name])[1] == digest, (name, "reads changed stored records")
|
||||
save()
|
||||
report["medians"] = []
|
||||
keys = sorted({(row["records"], row["case"], row["implementation"]) for row in report["samples"]})
|
||||
for count, case, name in keys:
|
||||
rows = [row for row in report["samples"] if not row["warmup"] and
|
||||
(row["records"], row["case"], row["implementation"]) == (count, case, name)]
|
||||
report["medians"].append(dict(records=count, case=case, implementation=name,
|
||||
seconds=statistics.median(row["seconds"] for row in rows),
|
||||
cpu_seconds=statistics.median(row["user_cpu_seconds"] + row["system_cpu_seconds"] for row in rows)))
|
||||
save()
|
||||
print(json.dumps(dict(samples=len(report["samples"]), functional=len(report["functional"]),
|
||||
checked=all(row["checked"] for row in report["samples"] + report["functional"])) ))
|
||||
@@ -0,0 +1,105 @@
|
||||
"""真实项目模块增删、重命名及干净构建对照;保留每次源码和输出。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import shutil
|
||||
|
||||
from scale import execute, fingerprint, source
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--profile", choices=["dev", "release"], required=True)
|
||||
parser.add_argument("--syntax", choices=["old", "next"], default="next")
|
||||
parser.add_argument("--sizes", nargs="+", type=int, default=[100, 1000, 10000])
|
||||
parser.add_argument("--shape", choices=["owned", "linear"], default="owned")
|
||||
args = parser.parse_args()
|
||||
if args.syntax == "old" and args.profile != "release":
|
||||
parser.error("old syntax has no public dev build profile")
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.absolute()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
resource.setrlimit(resource.RLIMIT_AS, (6 * 1024 ** 3, 6 * 1024 ** 3))
|
||||
os.environ["CARGO_BUILD_JOBS"] = "1"
|
||||
report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler),
|
||||
rounds=3, profile=args.profile, syntax=args.syntax, shape=args.shape, samples=[])
|
||||
(root / "modules.py").write_bytes(Path(__file__).read_bytes())
|
||||
(root / "scale.py").write_bytes(Path(__file__).with_name("scale.py").read_bytes())
|
||||
cgroup = Path("/sys/fs/cgroup")
|
||||
report["environment"] = dict(cpu_max=(cgroup / "cpu.max").read_text(),
|
||||
memory_max=(cgroup / "memory.max").read_text(), virtual_limit_bytes=6 * 1024 ** 3)
|
||||
initial_oom = dict(line.split() for line in (cgroup / "memory.events").read_text().splitlines())["oom_kill"]
|
||||
for count in args.sizes:
|
||||
original, expected = source(count, args.shape)
|
||||
body, ending = original.rsplit("\n}", 1)
|
||||
added = body + "\n answer = answer + support.value.app.increment()\n}" + ending
|
||||
renamed = added.replace("support.value.app.increment()", "support.renamed.app.increment()")
|
||||
for repeat in range(3):
|
||||
case = root / f"{count}-{repeat}"
|
||||
domain = case / "project/module/main/main"
|
||||
(domain / "app").mkdir(parents=True)
|
||||
(domain / "api.dever").write_text("cmd main = app.main\n")
|
||||
extra = case / "project/module/support/value/app/main.dever"
|
||||
moved = case / "project/module/support/renamed/app/main.dever"
|
||||
for scenario, text, answer in [("first", original, expected),
|
||||
("module-added", added, expected + 7),
|
||||
("module-renamed", renamed, expected + 7),
|
||||
("module-removed", original, expected)]:
|
||||
if scenario == "module-added":
|
||||
extra.parent.mkdir(parents=True)
|
||||
extra.write_text("increment() (answer: Int) { answer = 7 }\n")
|
||||
elif scenario == "module-renamed":
|
||||
extra.parent.parent.rename(moved.parent.parent)
|
||||
elif scenario == "module-removed":
|
||||
moved.unlink()
|
||||
(domain / "app/main.dever").write_text(text)
|
||||
formatted = execute([str(compiler), "fmt", str(case / "project")], case, scenario + "-fmt", 900)
|
||||
assert formatted["exit_code"] == 0, formatted
|
||||
snapshot = case / (scenario + "-sources.json")
|
||||
snapshot.write_text(json.dumps({str(p.relative_to(case / "project")): p.read_text()
|
||||
for p in (case / "project").rglob("*.dever")}, indent=2) + "\n")
|
||||
binary = case / scenario
|
||||
command = [str(compiler), "build", str(case / "project"), "--output", str(binary)]
|
||||
if args.syntax == "next":
|
||||
command += ["--profile", args.profile]
|
||||
row = dict(count=count, repeat=repeat, scenario=scenario, expected=answer,
|
||||
sources_sha256=fingerprint(snapshot), **execute(command, case, scenario, 900))
|
||||
report["samples"].append(row)
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["exit_code"] == 0, row
|
||||
ran = execute([str(binary), "main.main.main", "{}"], case, scenario + "-run", 60)
|
||||
row["execution"] = ran
|
||||
row["binary_sha256"] = fingerprint(binary)
|
||||
value = json.loads(Path(ran["stdout"]).read_text()) if ran["exit_code"] == 0 else None
|
||||
row["correct"] = value is not None and value["code"] == 0 and value["data"] == answer
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["correct"], row
|
||||
if scenario != "first":
|
||||
# 只复制源码,避免把增量缓存带入干净构建。
|
||||
clean = case / (scenario + "-clean-project")
|
||||
shutil.copytree(case / "project/module", clean / "module")
|
||||
clean_binary = case / (scenario + "-clean")
|
||||
clean_command = [str(compiler), "build", str(clean), "--output", str(clean_binary)]
|
||||
if args.syntax == "next":
|
||||
clean_command += ["--profile", args.profile]
|
||||
row["clean_build"] = execute(clean_command, case, scenario + "-clean", 900)
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["clean_build"]["exit_code"] == 0, row
|
||||
clean_run = execute([str(clean_binary), "main.main.main", "{}"],
|
||||
case, scenario + "-clean-run", 60)
|
||||
row["clean_execution"] = clean_run
|
||||
row["clean_binary_sha256"] = fingerprint(clean_binary)
|
||||
row["clean_correct"] = clean_run["exit_code"] == 0 and json.loads(
|
||||
Path(clean_run["stdout"]).read_text()) == value
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
assert row["clean_correct"], row
|
||||
assert dict(line.split() for line in (cgroup / "memory.events").read_text().splitlines())["oom_kill"] == initial_oom
|
||||
print(count, repeat, scenario, row["seconds"], flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""真实回环 TCP:持久连接逐次写入一个变化字节、读回并核验;独立参考不引用运行库。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'runtime':
|
||||
return '''use dever_runtime::{Bytes, net, task};
|
||||
async fn measure(n: i64, scope: &task::Scope) -> i64 {
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let client = net::connect_timeout("127.0.0.1", listener.port().unwrap(), 1000).await.unwrap();
|
||||
let server = listener.accept().await.unwrap();
|
||||
let pattern = Bytes::from((0..251u8).collect::<Vec<_>>());
|
||||
let mut count = 0i64;
|
||||
for value in 0..n {
|
||||
let index = (value % 251) as usize;
|
||||
let piece = pattern.slice(index..index + 1);
|
||||
client.write(&piece).await.unwrap();
|
||||
let received = server.read(1).await.unwrap().unwrap();
|
||||
assert_eq!(received.as_ref(), &[index as u8]);
|
||||
count = count.checked_add(1).unwrap();
|
||||
}
|
||||
client.close().unwrap(); server.close().unwrap(); listener.close().unwrap();
|
||||
count
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{}", task::run(true, 4096, async |scope| Ok::<_, ()>(measure(n, scope).await)).unwrap().unwrap());
|
||||
}
|
||||
'''
|
||||
if language == 'dever':
|
||||
return '''loop pattern() (out: List<Int>)
|
||||
| each value in range(0, 251) | result |
|
||||
| out | list value |
|
||||
rule readByte(state: dever.io.ReadState) (out: Bytes)
|
||||
| state | out |
|
||||
| Read(bytes) | bytes |
|
||||
| End | fail(Invalid) |
|
||||
verified(value: Int?, expected: Int) (out: Int) {
|
||||
check value == expected else Invalid
|
||||
out = 1
|
||||
}
|
||||
flow transfer(client: dever.system.Socket, server: dever.system.Socket, bytes: Bytes, value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| piece | calc | dever.bytes.slice(bytes, value % 251, value % 251 + 1) |
|
||||
| - | flow | dever.net.write(client, piece) |
|
||||
| state | flow | dever.net.read(server, 1) |
|
||||
| received | rule | readByte(state) |
|
||||
| out | calc | verified(dever.bytes.at(received, 0), value % 251) |
|
||||
loop transfers(client: dever.system.Socket, server: dever.system.Socket, bytes: Bytes, n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum transfer(client, server, bytes, value) |
|
||||
flow measure(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| listener | flow | dever.net.listen("127.0.0.1", 0) |
|
||||
| port | flow | dever.net.port(listener) |
|
||||
| client | flow | dever.net.connectTimeout("127.0.0.1", port, 1000) |
|
||||
| server | flow | dever.net.accept(listener) |
|
||||
| bytes | calc | dever.bytes.fromInts(pattern()) |
|
||||
| out | loop | transfers(client, server, bytes, n) |
|
||||
| - | flow | dever.net.close(client) |
|
||||
| - | flow | dever.net.close(server) |
|
||||
| - | flow | dever.net.closeListener(listener) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::{Bytes, BufMut};
|
||||
use std::io::ErrorKind;
|
||||
use tokio::{net::{TcpListener, TcpStream}, io::AsyncWriteExt};
|
||||
async fn measure(n: i64) -> i64 {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let mut client = TcpStream::connect(listener.local_addr().unwrap()).await.unwrap();
|
||||
let server = listener.accept().await.unwrap().0;
|
||||
client.set_nodelay(true).unwrap(); server.set_nodelay(true).unwrap();
|
||||
let pattern = Bytes::from((0..251u8).collect::<Vec<_>>());
|
||||
let mut count = 0i64;
|
||||
for value in 0..n {
|
||||
let index = (value % 251) as usize;
|
||||
let piece = pattern.slice(index..index + 1);
|
||||
client.write_all(&piece).await.unwrap();
|
||||
server.readable().await.unwrap();
|
||||
let mut buffer = Vec::new(); buffer.try_reserve_exact(1).unwrap();
|
||||
loop {
|
||||
match server.try_read_buf(&mut (&mut buffer).limit(1)) {
|
||||
Ok(1) => break,
|
||||
Ok(_) => panic!("unexpected EOF"),
|
||||
Err(error) if error.kind() == ErrorKind::WouldBlock => server.readable().await.unwrap(),
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
}
|
||||
let received = Bytes::from(buffer);
|
||||
assert_eq!(received.as_ref(), &[index as u8]);
|
||||
count = count.checked_add(1).unwrap();
|
||||
}
|
||||
count
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
println!("{}", runtime.block_on(measure(n)));
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "io"; "net"; "os"; "strconv")
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127,0,0,1)}); if err != nil { panic(err) }; defer listener.Close()
|
||||
client, err := net.DialTCP("tcp", nil, listener.Addr().(*net.TCPAddr)); if err != nil { panic(err) }; defer client.Close()
|
||||
server, err := listener.AcceptTCP(); if err != nil { panic(err) }; defer server.Close()
|
||||
if err := client.SetNoDelay(true); err != nil { panic(err) }
|
||||
if err := server.SetNoDelay(true); err != nil { panic(err) }
|
||||
pattern := make([]byte, 251); for i := range pattern { pattern[i] = byte(i) }
|
||||
count := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
index := value % 251
|
||||
if size, err := client.Write(pattern[index:index+1]); err != nil || size != 1 { panic("write failed") }
|
||||
received := make([]byte, 1); if _, err := io.ReadFull(server, received); err != nil { panic(err) }
|
||||
if received[0] != byte(index) { panic("byte mismatch") }
|
||||
next := count + 1; if next < count { panic("count overflow") }; count = next
|
||||
}
|
||||
fmt.Println(count)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,201 @@
|
||||
//! 独立 Tokio TCP 对照:共享关闭、同向串行、期限和部分写入取消。
|
||||
//! 不链接 Dever;原有裸 Tokio 对端继续作为另一项保留。
|
||||
use bytes::{BufMut, Bytes};
|
||||
use futures_util::future::poll_fn;
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
sync::{
|
||||
Arc, RwLock,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
task::Poll,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::Semaphore,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Socket(Arc<State>);
|
||||
struct State {
|
||||
stream: RwLock<Option<TcpStream>>,
|
||||
reader: Semaphore,
|
||||
writer: Semaphore,
|
||||
closed: CancellationToken,
|
||||
timeout: AtomicU64,
|
||||
}
|
||||
fn closed() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::NotConnected, "socket is closed")
|
||||
}
|
||||
impl Socket {
|
||||
fn new(stream: TcpStream) -> io::Result<Self> {
|
||||
stream.set_nodelay(true)?;
|
||||
Ok(Self(Arc::new(State {
|
||||
stream: RwLock::new(Some(stream)),
|
||||
reader: Semaphore::new(1),
|
||||
writer: Semaphore::new(1),
|
||||
closed: CancellationToken::new(),
|
||||
timeout: AtomicU64::new(0),
|
||||
})))
|
||||
}
|
||||
fn close(&self) -> io::Result<()> {
|
||||
drop(self.0.stream.write().unwrap().take().ok_or_else(closed)?);
|
||||
self.0.reader.close();
|
||||
self.0.writer.close();
|
||||
self.0.closed.cancel();
|
||||
Ok(())
|
||||
}
|
||||
fn timeout(&self, millis: u64) -> io::Result<()> {
|
||||
if millis == 0
|
||||
|| tokio::time::Instant::now()
|
||||
.checked_add(Duration::from_millis(millis))
|
||||
.is_none()
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid socket timeout",
|
||||
));
|
||||
}
|
||||
if self.0.closed.is_cancelled() {
|
||||
return Err(closed());
|
||||
}
|
||||
self.0.timeout.store(millis, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
async fn operation<T>(&self, work: impl Future<Output = io::Result<T>>) -> io::Result<T> {
|
||||
let work = async {
|
||||
match self.0.timeout.load(Ordering::Relaxed) {
|
||||
0 => work.await,
|
||||
millis => tokio::time::timeout(Duration::from_millis(millis), work)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(io::ErrorKind::TimedOut, "socket operation timed out")
|
||||
})?,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = self.0.closed.cancelled() => Err(closed()),
|
||||
result = work => result,
|
||||
}
|
||||
}
|
||||
async fn read(&self, limit: usize) -> io::Result<Option<Bytes>> {
|
||||
if limit == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid read size",
|
||||
));
|
||||
}
|
||||
self.operation(async {
|
||||
let _permit = self.0.reader.acquire().await.map_err(|_| closed())?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(limit).map_err(io::Error::other)?;
|
||||
let count = poll_fn(|cx| {
|
||||
let state = self.0.stream.read().unwrap();
|
||||
let stream = state.as_ref().ok_or_else(closed)?;
|
||||
loop {
|
||||
std::task::ready!(stream.poll_read_ready(cx))?;
|
||||
match stream.try_read_buf(&mut (&mut bytes).limit(limit)) {
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
|
||||
result => return Poll::Ready(result),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
Ok((count != 0).then(|| Bytes::from(bytes)))
|
||||
})
|
||||
.await
|
||||
}
|
||||
async fn write(&self, bytes: &[u8]) -> io::Result<()> {
|
||||
self.operation(async {
|
||||
let _permit = self.0.writer.acquire().await.map_err(|_| closed())?;
|
||||
let mut progress = PartialWrite {
|
||||
socket: self,
|
||||
partial: false,
|
||||
};
|
||||
let mut offset = 0;
|
||||
poll_fn(|cx| {
|
||||
let state = self.0.stream.read().unwrap();
|
||||
let stream = state.as_ref().ok_or_else(closed)?;
|
||||
while offset < bytes.len() {
|
||||
std::task::ready!(stream.poll_write_ready(cx))?;
|
||||
match stream.try_write(&bytes[offset..]) {
|
||||
Ok(0) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"socket write returned zero",
|
||||
)));
|
||||
}
|
||||
Ok(count) => {
|
||||
offset += count;
|
||||
progress.partial = offset < bytes.len();
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Err(error) => return Poll::Ready(Err(error)),
|
||||
}
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
})
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
struct PartialWrite<'a> {
|
||||
socket: &'a Socket,
|
||||
partial: bool,
|
||||
}
|
||||
impl Drop for PartialWrite<'_> {
|
||||
fn drop(&mut self) {
|
||||
if self.partial {
|
||||
let _ = self.socket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pair() -> io::Result<(Socket, Socket)> {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await?;
|
||||
let client = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
TcpStream::connect(listener.local_addr()?),
|
||||
)
|
||||
.await??;
|
||||
let server = listener.accept().await?.0;
|
||||
Ok((Socket::new(client)?, Socket::new(server)?))
|
||||
}
|
||||
async fn measure(n: i64, timeout: Option<u64>) -> io::Result<i64> {
|
||||
let (client, server) = pair().await?;
|
||||
if let Some(millis) = timeout {
|
||||
client.timeout(millis)?;
|
||||
server.timeout(millis)?;
|
||||
}
|
||||
let pattern = Bytes::from((0..251u8).collect::<Vec<_>>());
|
||||
let mut count = 0i64;
|
||||
for value in 0..n {
|
||||
let index = (value % 251) as usize;
|
||||
let piece = pattern.slice(index..index + 1);
|
||||
client.write(&piece).await?;
|
||||
let received = server.read(1).await?.expect("unexpected EOF");
|
||||
assert_eq!(received.as_ref(), &[index as u8]);
|
||||
count = count.checked_add(1).expect("count overflow");
|
||||
}
|
||||
client.close()?;
|
||||
server.close()?;
|
||||
Ok(count)
|
||||
}
|
||||
fn main() {
|
||||
let n = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let timeout = std::env::args().nth(2).map(|value| value.parse().unwrap());
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
println!("{}", runtime.block_on(measure(n, timeout)).unwrap());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "net_resource_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,76 @@
|
||||
use super::*;
|
||||
|
||||
fn run(work: impl Future<Output = ()>) {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(work)
|
||||
}
|
||||
#[test]
|
||||
fn closes_all_aliases_pending_and_queued_reads_and_releases_socket() {
|
||||
run(async {
|
||||
let (client, server) = pair().await.unwrap();
|
||||
let alias = server.clone();
|
||||
let mut active = std::pin::pin!(server.read(1));
|
||||
let mut queued = std::pin::pin!(alias.read(1));
|
||||
assert!(futures_util::poll!(&mut active).is_pending());
|
||||
assert!(futures_util::poll!(&mut queued).is_pending());
|
||||
alias.close().unwrap();
|
||||
for result in [active.await, queued.await, server.read(1).await] {
|
||||
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotConnected);
|
||||
}
|
||||
assert!(alias.0.stream.read().unwrap().is_none());
|
||||
assert!(client.read(1).await.unwrap().is_none());
|
||||
assert!(server.close().is_err());
|
||||
});
|
||||
}
|
||||
#[test]
|
||||
fn cancelled_reads_release_the_direction_and_timeout_keeps_the_socket_usable() {
|
||||
run(async {
|
||||
let (client, server) = pair().await.unwrap();
|
||||
{
|
||||
let mut pending = std::pin::pin!(server.read(1));
|
||||
assert!(futures_util::poll!(&mut pending).is_pending());
|
||||
}
|
||||
assert_eq!(server.0.reader.available_permits(), 1);
|
||||
server.timeout(10).unwrap();
|
||||
assert_eq!(
|
||||
server.read(1).await.unwrap_err().kind(),
|
||||
io::ErrorKind::TimedOut
|
||||
);
|
||||
client.write(b"x").await.unwrap();
|
||||
assert_eq!(server.read(1).await.unwrap().unwrap().as_ref(), b"x");
|
||||
assert!(server.timeout(0).is_err());
|
||||
assert!(server.read(0).await.is_err());
|
||||
client.close().unwrap();
|
||||
server.close().unwrap();
|
||||
});
|
||||
}
|
||||
#[test]
|
||||
fn cancelling_a_partial_write_closes_aliases_and_wakes_the_queued_writer() {
|
||||
run(async {
|
||||
let (client, server) = pair().await.unwrap();
|
||||
let alias = client.clone();
|
||||
let data = vec![7u8; 16 * 1024 * 1024];
|
||||
let mut queued = std::pin::pin!(alias.write(b"later"));
|
||||
{
|
||||
let mut pending = std::pin::pin!(client.write(&data));
|
||||
assert!(futures_util::poll!(&mut pending).is_pending());
|
||||
assert!(futures_util::poll!(&mut queued).is_pending());
|
||||
}
|
||||
assert_eq!(
|
||||
queued.await.unwrap_err().kind(),
|
||||
io::ErrorKind::NotConnected
|
||||
);
|
||||
assert!(client.0.stream.read().unwrap().is_none());
|
||||
assert!(client.write(b"after").await.is_err());
|
||||
server.close().unwrap();
|
||||
});
|
||||
}
|
||||
#[test]
|
||||
fn successful_transfer_checks_every_dynamic_byte_and_count() {
|
||||
run(async {
|
||||
assert_eq!(measure(1024, None).await.unwrap(), 1024);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"""TCP 同资源责任对照;保留原始裸 Rust、Go 和修改前 Dever,不替换基线。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import statistics
|
||||
import tomllib
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def measure(core, output, report, binaries):
|
||||
def save():
|
||||
(output / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
os.sched_setaffinity(0, {0})
|
||||
names = list(binaries)
|
||||
save()
|
||||
for repeat in range(-1, 7):
|
||||
assert all(fingerprint(core / path) == digest for path,digest in report["source_hashes"].items())
|
||||
for offset in range(len(names)):
|
||||
name = names[(repeat + 1 + offset) % len(names)]
|
||||
command = [str(binaries[name])]
|
||||
if name in ["dever", "previous"]:
|
||||
command += ["main.main.bench", json.dumps(dict(n=report["size"]))]
|
||||
else:
|
||||
command += [str(report["size"])]
|
||||
row = execute(command, output, f"{repeat}-{name}", 60)
|
||||
row.update(name=name, repeat=repeat)
|
||||
report["samples"].append(row)
|
||||
save()
|
||||
assert row["exit_code"] == 0 and not row["timeout"], row
|
||||
answer = Path(row["stdout"]).read_text()
|
||||
assert (json.loads(answer)["data"] if name in ["dever", "previous"] else int(answer)) == report["size"], row
|
||||
row["checked"] = True
|
||||
save()
|
||||
report["medians"] = {name:dict(seconds=statistics.median(r["seconds"] for r in report["samples"] if 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["name"]==name and r["repeat"]>=0)) for name in names}
|
||||
save()
|
||||
print(json.dumps(report["medians"], indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--baseline", type=Path, required=True,
|
||||
help="original loop.py --shape net result directory")
|
||||
parser.add_argument("--previous", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
output = args.output.absolute()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
original_path = args.baseline / "results.json"
|
||||
original = json.loads(original_path.read_text())
|
||||
report = dict(rounds=7, warmups=1, size=original["size"], cpu_affinity=[0],
|
||||
contract="Persistent loopback TCP pair, TCP_NODELAY, a varying byte written/read/verified each iteration, checked count. Resource Rust owns alias-wide immediate socket close, serialized same-direction operations, cancelled-read release, optional total-operation deadlines, and partial-write cancellation that closes aliases before the queued writer proceeds. Uses independent Tokio/bytes/tokio-util, no Dever runtime.",
|
||||
limitations="Successful sequential socket workload; not full listener/DNS/AsyncStream or language error/Scope equivalence. Original bare Tokio and Go remain separate results; resource parity cannot erase the gap to the bare peer. Wall/CPU cover process startup/shutdown, not individual-operation tail latency.",
|
||||
original_baseline=dict(path=str(original_path.resolve()), sha256=fingerprint(original_path)),
|
||||
source_hashes={}, builds=[], samples=[])
|
||||
|
||||
def save():
|
||||
(output / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
def run(label, command, timeout=900):
|
||||
row = execute(list(map(str, command)), output, label, timeout)
|
||||
report["builds"].append(row)
|
||||
save()
|
||||
assert row["exit_code"] == 0 and not row["timeout"], row
|
||||
|
||||
sources = [Path(__file__), *Path(__file__).parent.glob("net_resource_*.rs"),
|
||||
*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"),
|
||||
core / "rust/Cargo.toml", core / "rust/Cargo.lock", core / "rust/src/runtime/Cargo.toml"]
|
||||
for source in sources:
|
||||
relative = source.relative_to(core)
|
||||
report["source_hashes"][str(relative)] = fingerprint(source)
|
||||
target = output / "inputs" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
reference = output / "reference"
|
||||
reference.mkdir()
|
||||
for source in Path(__file__).parent.glob("net_resource_*.rs"):
|
||||
shutil.copyfile(source, reference / source.name)
|
||||
manifest = '''[package]
|
||||
name = "net-resource-reference"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "net-resource-reference"
|
||||
path = "net_resource_reference.rs"
|
||||
[dependencies]
|
||||
bytes = "=1.12.1"
|
||||
tokio = { version = "=1.53.1", features = ["rt", "net", "io-util", "time", "macros", "sync"] }
|
||||
tokio-util = { version = "=0.7.19", features = ["rt"] }
|
||||
futures-util = { version = "=0.3.34", default-features = false, features = ["std", "async-await"] }
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = "symbols"
|
||||
'''
|
||||
(reference / "Cargo.toml").write_text(manifest)
|
||||
shutil.copyfile(core / "rust/Cargo.lock", reference / "Cargo.lock")
|
||||
cargo = ["cargo", "+1.95.0"]
|
||||
common = ["--manifest-path", reference / "Cargo.toml", "--offline", "--target-dir", reference / "target"]
|
||||
run("reference-test", [*cargo, "test", *common])
|
||||
run("reference-clippy", [*cargo, "clippy", *common, "--locked", "--all-targets", "--", "-D", "warnings"])
|
||||
run("reference-build", [*cargo, "build", *common, "--locked", "--release"])
|
||||
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)
|
||||
report["reference_lock_sha256"] = fingerprint(reference / "Cargo.lock")
|
||||
source = args.baseline / "net-dever/main.dever"
|
||||
run("dever-build", [args.compiler, "build", source, "--output", output / "dever"])
|
||||
shutil.copyfile(source, output / "workload.dever")
|
||||
report["compiler_sha256"] = fingerprint(args.compiler)
|
||||
binaries = dict(dever=output / "dever", previous=args.previous.resolve(strict=True),
|
||||
resource=reference / "target/release/net-resource-reference")
|
||||
for name in ["rust", "go"]:
|
||||
info = next(row for row in original["builds"] if row["language"] == name and row["shape"] == "net")
|
||||
binary = args.baseline / ("net-rust/target/release/collection-reference" if name == "rust" else "net-go/program")
|
||||
assert fingerprint(binary) == info["binary_sha256"], "original reference changed"
|
||||
binaries[name] = binary
|
||||
report["binaries"] = {name:dict(path=str(path),sha256=fingerprint(path)) for name,path in binaries.items()}
|
||||
measure(core, output, report, binaries)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""每个输入并发执行两个步骤;独立 Rust 使用相同 Tokio,Go 使用原生 goroutine。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''noop() () {}
|
||||
rule pause(value: Int) ()
|
||||
| value | do |
|
||||
| 0 | dever.time.sleep(1) |
|
||||
| other | noop() |
|
||||
flow item(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | rule | pause(value % 1000000) |
|
||||
| out | calc | value |
|
||||
flow pair(value: Int) (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | read | item(value) |
|
||||
| right | flow | read | item(value + 1) |
|
||||
| out | calc | - | left + right |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum pair(value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''async fn pause(value: i64) -> Result<(), &'static str> {
|
||||
if value == 0 {
|
||||
let millis = u64::try_from(1i64).map_err(|_| "sleep duration must be nonnegative")?;
|
||||
let deadline = tokio::time::Instant::now().checked_add(std::time::Duration::from_millis(millis)).ok_or("sleep deadline is out of range")?;
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn item(value: i64) -> Result<i64, &'static str> { pause(value % 1000000).await?; Ok(value) }
|
||||
async fn pair(value: i64) -> Result<i64, &'static str> {
|
||||
let left = value;
|
||||
let right = value.checked_add(1).expect("argument overflow");
|
||||
let (left, right) = tokio::try_join!(biased; item(left), item(right))?;
|
||||
Ok(left.checked_add(right).expect("pair overflow"))
|
||||
}
|
||||
async fn measure(n: i64) -> Result<i64, &'static str> {
|
||||
let mut total = 0i64;
|
||||
for value in 0..n { total = total.checked_add(pair(value).await?).expect("sum overflow"); }
|
||||
Ok(total)
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
|
||||
println!("{}", runtime.block_on(measure(n)).unwrap());
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv"; "sync"; "time")
|
||||
func add(a, b int64) int64 {
|
||||
out := a + b
|
||||
if (b > 0 && out < a) || (b < 0 && out > a) { panic("integer overflow") }
|
||||
return out
|
||||
}
|
||||
func item(value int64) int64 {
|
||||
if value % 1000000 == 0 { time.Sleep(time.Millisecond) }
|
||||
return value
|
||||
}
|
||||
func pair(value int64) int64 {
|
||||
left, right := value, add(value, 1)
|
||||
var a, b int64
|
||||
var group sync.WaitGroup
|
||||
group.Add(2)
|
||||
go func() { defer group.Done(); a = item(left) }()
|
||||
go func() { defer group.Done(); b = item(right) }()
|
||||
group.Wait()
|
||||
return add(a, b)
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ { total = add(total, pair(value)) }
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,74 @@
|
||||
"""启动选择一个具体实现;对照使用相同配置、文本查询和 checked sum。"""
|
||||
from settings_reference import config as settings_config, source as settings_source
|
||||
|
||||
|
||||
def config():
|
||||
return {'adapter': {'main.main': {'use': 'contains', 'setting': {
|
||||
'corpus': settings_config()['module']['main']['main']['corpus']}}}}
|
||||
|
||||
|
||||
def project(root, app):
|
||||
domain = root / 'module/main/main'
|
||||
(domain / 'adapter').mkdir(parents=True)
|
||||
(domain / 'app').mkdir()
|
||||
(domain / 'app/main.dever').write_text(app)
|
||||
(domain / 'api.dever').write_text('cmd bench = app.measure\n')
|
||||
(domain / 'port.dever').write_text('includes(value: Text) (out: Bool)\n')
|
||||
for name, operation in [('contains', 'contains'), ('prefix', 'startsWith')]:
|
||||
(domain / f'adapter/{name}.dever').write_text(
|
||||
'setting { corpus: Text }\n'
|
||||
f'port.includes(value: Text) (out: Bool) {{ out = text.{operation}(setting.corpus, value) }}\n')
|
||||
return root
|
||||
|
||||
|
||||
def source(language):
|
||||
original = settings_source(language)
|
||||
if language == 'dever':
|
||||
return original.replace('setting corpus: Text\n', '').replace(
|
||||
'text.contains(corpus, int.toText(value % 1000))',
|
||||
'port.includes(int.toText(value % 1000))').replace('cmd bench = app.measure\n', '')
|
||||
if language == 'rust':
|
||||
return r'''use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Root { adapter: Adapters }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Adapters { #[serde(rename="main.main")] selected: DecodeAdapter }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings { corpus: String }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag="use",content="setting",deny_unknown_fields)]
|
||||
enum DecodeAdapter { #[serde(rename="contains")] Contains(Settings), #[serde(rename="prefix")] Prefix(Settings) }
|
||||
enum Adapter { Contains(Settings), Prefix(Settings) }
|
||||
impl Adapter {
|
||||
fn includes(&self, value: &str) -> bool {
|
||||
match self { Self::Contains(s) => s.corpus.contains(value), Self::Prefix(s) => s.corpus.starts_with(value) }
|
||||
}
|
||||
}
|
||||
fn measure(adapter: &Adapter, n: i64) -> i64 {
|
||||
let mut total = 0i64;
|
||||
for value in 0..n {
|
||||
let text = (value % 1000).to_string();
|
||||
let selected = if adapter.includes(&text) { value } else { 0 };
|
||||
total = total.checked_add(selected).unwrap();
|
||||
}
|
||||
total
|
||||
}
|
||||
fn main() {
|
||||
let path = std::env::args().nth(2).unwrap();
|
||||
let input = std::fs::read_to_string(path).unwrap();
|
||||
let root: Root = serde_json::from_str(&input).unwrap();
|
||||
let adapter = match root.adapter.selected { DecodeAdapter::Contains(s) => Adapter::Contains(s), DecodeAdapter::Prefix(s) => Adapter::Prefix(s) };
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{}", measure(&adapter, n));
|
||||
}
|
||||
'''
|
||||
original = original.replace('type Domain struct { Main Settings }\n', '').replace('type Module struct { Main Domain }\n', '')
|
||||
return original.replace('type Root struct { Module Module }',
|
||||
'type Adapter struct { Use string; Setting Settings }\ntype Root struct { Adapter map[string]Adapter }').replace(
|
||||
'n, err := strconv.ParseInt',
|
||||
'adapter := root.Adapter["main.main"]\n if adapter.Use != "contains" && adapter.Use != "prefix" { panic("unknown implementation") }\n n, err := strconv.ParseInt').replace(
|
||||
'if strings.Contains(root.Module.Main.Main.Corpus, text) { selected = value }',
|
||||
'found := false\n switch adapter.Use { case "contains": found = strings.Contains(adapter.Setting.Corpus, text); case "prefix": found = strings.HasPrefix(adapter.Setting.Corpus, text) }\n if found { selected = value }')
|
||||
@@ -0,0 +1,108 @@
|
||||
"""规则覆盖证明基线:调用真实编译器,保留完整、遗漏、重叠及宽条件输入。"""
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def source(columns, shape, syntax):
|
||||
names = [f"flag{i}" for i in range(columns)]
|
||||
signature = ", ".join(f"{name}: Bool" for name in names)
|
||||
rows = list(itertools.product(["false", "true"], repeat=columns)) if shape != "wide" else [tuple("-" for _ in names)]
|
||||
if shape == "missing":
|
||||
rows.pop()
|
||||
elif shape == "overlap":
|
||||
rows.append(rows[0])
|
||||
definitions = []
|
||||
if syntax == "tables":
|
||||
definitions = [f"rule choose({signature}) (answer: Int)",
|
||||
"| " + " | ".join(names + ["answer"]) + " |"]
|
||||
definitions.extend("| " + " | ".join(list(row) + [str(i)]) + " |" for i, row in enumerate(rows))
|
||||
else:
|
||||
for i, row in enumerate(rows):
|
||||
parameters = ", ".join(f"{name}: {'Bool' if value == '-' else value}" for name, value in zip(names, row))
|
||||
definitions.extend([f"choose({parameters}) (answer: Int) {{", f" answer = {i}", "}"])
|
||||
arguments = ", ".join("false" for _ in names)
|
||||
definitions.extend(["main() (answer: Int) {", f" answer = choose({arguments})", "}"])
|
||||
return '\n'.join(definitions) + '\n', len(rows)
|
||||
|
||||
|
||||
def numeric_source(size, shape):
|
||||
if shape == "budget":
|
||||
rows = [f"| {value} | 1 |" for value in range(size)] + ["| other | 2 |"]
|
||||
return "rule choose(x: Int) (answer: Int)\n| x | answer |\n" + "\n".join(rows) + "\n", len(rows), 1
|
||||
columns = 2 if shape == "interval-grid" else 1
|
||||
names = [f"value{i}" for i in range(columns)]
|
||||
signature = ", ".join(f"{name}: Int >= 0 and < {size * 10}" for name in names)
|
||||
rows = [f"rule choose({signature}) (answer: Int)", "| " + " | ".join(names + ["answer"]) + " |"]
|
||||
for index, cells in enumerate(itertools.product(range(size), repeat=columns)):
|
||||
conditions = [f">= {value * 10} and < {(value + 1) * 10}" for value in cells]
|
||||
rows.append("| " + " | ".join(conditions + [str(index)]) + " |")
|
||||
return "\n".join(rows) + "\n", size ** columns, columns
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--syntax", required=True, choices=["clauses", "tables"])
|
||||
parser.add_argument("--numeric", action="store_true", help="measure interval partitions and the proof-budget diagnostic instead of Boolean cases")
|
||||
args = parser.parse_args()
|
||||
if args.numeric and args.syntax != "tables":
|
||||
parser.error("numeric table cases require --syntax tables")
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler),
|
||||
driver_sha256=fingerprint(Path(__file__)), syntax=args.syntax,
|
||||
repeats=3, timeout_seconds=30, samples=[])
|
||||
cases = [(size, "complete") for size in [4, 8, 10]]
|
||||
cases += [(4, "missing"), (4, "overlap")]
|
||||
cases += [(size, "wide") for size in [8, 16, 20]]
|
||||
if args.numeric:
|
||||
cases = [(size, "intervals") for size in [16, 64, 256]]
|
||||
cases += [(size, "interval-grid") for size in [4, 16, 32]]
|
||||
cases += [(1200, "budget")]
|
||||
for size, shape in cases:
|
||||
for repeat in range(3):
|
||||
directory = root / f"{shape}-{size}-{repeat}"
|
||||
directory.mkdir()
|
||||
path = directory / "main.dever"
|
||||
columns = size
|
||||
if shape in ("intervals", "interval-grid", "budget"):
|
||||
text, rows, columns = numeric_source(size, shape)
|
||||
else:
|
||||
text, rows = source(columns, shape, args.syntax)
|
||||
path.write_text(text)
|
||||
formatted = execute([str(compiler), "fmt", str(directory)], directory, "fmt", 30)
|
||||
if formatted["exit_code"] != 0:
|
||||
sample = dict(columns=columns, rows=rows, shape=shape, repeat=repeat,
|
||||
correct=False, stage="fmt", **formatted)
|
||||
else:
|
||||
result = execute([str(compiler), "check", str(path)], directory, "check", 30)
|
||||
diagnostic = Path(result["stderr"]).read_text()
|
||||
if shape == "missing":
|
||||
correct = result["exit_code"] != 0 and "C009" in diagnostic and "cover" in diagnostic
|
||||
elif shape == "overlap":
|
||||
correct = result["exit_code"] != 0 and "C009" in diagnostic and "overlap" in diagnostic
|
||||
elif shape == "budget":
|
||||
correct = result["exit_code"] != 0 and "C015" in diagnostic and "has not been proved" in diagnostic
|
||||
else:
|
||||
correct = result["exit_code"] == 0
|
||||
sample = dict(columns=columns, rows=rows, shape=shape, repeat=repeat,
|
||||
source_sha256=fingerprint(path), correct=correct,
|
||||
expected="reject" if shape in ["missing", "overlap", "budget"] else "accept", **result)
|
||||
sample["axis_size"] = size
|
||||
report["samples"].append(sample)
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps(sample), flush=True)
|
||||
if not sample["correct"]:
|
||||
break
|
||||
raise SystemExit(0 if all(s["correct"] for s in report["samples"]) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,260 @@
|
||||
"""固定规模的真实编译、执行和 inspect 基线,不清理共享缓存。"""
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
def fingerprint(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def source(count, shape, changed=False, signature=False):
|
||||
if shape in ("owned", "deep"):
|
||||
# owned 的调用深度为 100,与真实项目同量级,是 30 秒门槛的正式输入;deep 保留 count 层单链作压力用例,
|
||||
# 因为 rustc 的内联环路检查随调用链深度平方增长,深链耗时不代表函数数量的成本(见 REMAINING.md)。
|
||||
depth = count if shape == "deep" else 100
|
||||
definitions = ["type Parcel {\n title: Text\n tags: List<Text>\n number: Int\n}"]
|
||||
for index in range(count - 1):
|
||||
arguments = "value: Parcel, extra: Int" if signature and index == 0 else "value: Parcel"
|
||||
if index == 0:
|
||||
increment = "extra" if signature else str(2 if changed else 1)
|
||||
body = f"length(value.title) + length(value.tags) + value.number + {increment}"
|
||||
else:
|
||||
# 每段的首个函数改调 step0,使所有段仍依赖同一个被修改的函数。
|
||||
callee = index - 1 if index % depth else 0
|
||||
call = "value, 1" if signature and callee == 0 else "value"
|
||||
body = f"step{callee}({call}) + 1"
|
||||
definitions.append(f"step{index}({arguments}) (answer: Int) {{ answer = {body} }}")
|
||||
heads = [min(start + depth, count - 1) - 1 for start in range(0, count - 1, depth)]
|
||||
terms = " + ".join(f"step{head}(parcel{', 1' if signature and head == 0 else ''})" for head in heads)
|
||||
definitions.append('main() (answer: Int) {\n parcel = Parcel { title = "hello", tags = ["one", "two"], number = 3 }\n'
|
||||
f" answer = {terms}\n}}")
|
||||
bottom = 10 + (1 if signature else 2 if changed else 1)
|
||||
expected = sum(bottom + head % depth + (1 if head >= depth else 0) for head in heads)
|
||||
return "\n\n".join(definitions) + "\n", expected
|
||||
if shape == "flow":
|
||||
# 与 linear 相同的调用链,改用唯一绑定的顺序表,检查表本身是否增加执行层。
|
||||
definitions = []
|
||||
for index in range(count - 1):
|
||||
arguments = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
rows = []
|
||||
if index == 0:
|
||||
increment = "extra" if signature else str(2 if changed else 1)
|
||||
rows.append(f"| answer | calc | value + {increment} |")
|
||||
else:
|
||||
call = "value, 1" if signature and index == 1 else "value"
|
||||
rows.extend([f"| previous | flow | step{index - 1}({call}) |", "| answer | calc | previous + 1 |"])
|
||||
definitions.append(f"flow step{index}({arguments}) (answer: Int)\n| step | kind | do |\n" + "\n".join(rows))
|
||||
call = "1, 1" if signature and count == 2 else "1"
|
||||
definitions.append(f"flow main() (answer: Int)\n| step | kind | do |\n| answer | flow | step{count - 2}({call}) |")
|
||||
return "\n\n".join(definitions) + "\n", count + int(changed)
|
||||
if shape == "handler":
|
||||
extra = ", offset: Int" if signature else ""
|
||||
result = "transform(value) + offset" if signature else "transform(value)"
|
||||
definitions = [f"apply(value: Int, transform: handler(value: Int) (answer: Int){extra}) (answer: Int) {{ answer = {result} }}"]
|
||||
for index in range(count - 2):
|
||||
increment = 2 if changed and index == 0 else 1
|
||||
definitions.append(f"step{index}(value: Int) (answer: Int) {{ answer = value + {increment} }}")
|
||||
lines = ["main() (answer: Int) {", " answer = 0"]
|
||||
for index in range(count - 2):
|
||||
arguments = f"1, step{index}, 0" if signature else f"1, step{index}"
|
||||
lines.append(f" answer = answer + apply({arguments})")
|
||||
definitions.append("\n".join(lines + ["}"]))
|
||||
return "\n\n".join(definitions) + "\n", 2 * (count - 2) + int(changed and count > 2)
|
||||
# 包含 main 在内恰好 count 个定义;main 使用每个函数的结果。
|
||||
if shape == "tree":
|
||||
definitions = []
|
||||
for index in range(count - 1):
|
||||
argument = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
increment = "extra" if signature and index == 0 else str(2 if changed and index == 0 else 1)
|
||||
terms = ["value", increment]
|
||||
terms.extend(f"step{child}(value)" for child in [2 * index + 1, 2 * index + 2]
|
||||
if child < count - 1)
|
||||
definitions.append(f"step{index}({argument}) (answer: Int) {{\n answer = {' + '.join(terms)}\n}}\n")
|
||||
call = "1, 1" if signature else "1"
|
||||
definitions.append(f"main() (answer: Int) {{\n answer = step0({call})\n}}\n")
|
||||
return "\n".join(definitions), 2 * (count - 1) + int(changed)
|
||||
definitions = []
|
||||
expected = []
|
||||
for index in range(count - 1):
|
||||
increment = 2 if changed and index == 0 else 1
|
||||
argument = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
if index == 0:
|
||||
body = "value + extra" if signature else f"value + {increment}"
|
||||
expected.append(2 if signature else 1 + increment)
|
||||
else:
|
||||
parent = index - 1 if shape in ("chain", "linear") else (index - 1) // 2
|
||||
call = "value, 1" if signature and parent == 0 else "value"
|
||||
body = f"step{parent}({call}) + 1"
|
||||
expected.append(expected[parent] + 1)
|
||||
definitions.append(f"step{index}({argument}) (answer: Int) {{\n answer = {body}\n}}\n")
|
||||
lines = ["main() (answer: Int) {", " answer = 0"]
|
||||
indices = [count - 2] if shape == "linear" else range(count - 1)
|
||||
for index in indices:
|
||||
call = "1, 1" if signature and index == 0 else "1"
|
||||
lines.append(f" answer = answer + step{index}({call})")
|
||||
definitions.append("\n".join(lines + ["}", ""]))
|
||||
return "\n".join(definitions), expected[-1] if shape == "linear" else sum(expected)
|
||||
|
||||
|
||||
def execute(command, directory, label, timeout, *, argv0=None):
|
||||
stdout = directory / (label + ".stdout")
|
||||
stderr = directory / (label + ".stderr")
|
||||
started = time.monotonic()
|
||||
timed_out = False
|
||||
with stdout.open("xb") as out, stderr.open("xb") as err:
|
||||
arguments = command if argv0 is None else [argv0, *command[1:]]
|
||||
process = subprocess.Popen(arguments, executable=command[0], stdout=out, stderr=err,
|
||||
start_new_session=True)
|
||||
def expire(signum, frame):
|
||||
nonlocal timed_out
|
||||
timed_out = True
|
||||
# 只结束本次创建的进程组,避免超时后 Cargo 仍占用共享开发预算。
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass # 截止时间与进程退出可以同时发生。
|
||||
|
||||
previous = signal.signal(signal.SIGALRM, expire)
|
||||
signal.alarm(timeout)
|
||||
try:
|
||||
_, status, usage = os.wait4(process.pid, 0)
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
signal.signal(signal.SIGALRM, previous)
|
||||
process.returncode = os.waitstatus_to_exitcode(status)
|
||||
return dict(command=command, **({"argv0": argv0} if argv0 is not None else {}),
|
||||
exit_code=process.returncode, timeout=timed_out,
|
||||
seconds=time.monotonic() - started, peak_rss_kib=usage.ru_maxrss,
|
||||
user_cpu_seconds=usage.ru_utime, system_cpu_seconds=usage.ru_stime,
|
||||
voluntary_switches=usage.ru_nvcsw, involuntary_switches=usage.ru_nivcsw,
|
||||
stdout=str(stdout), stderr=str(stderr))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--sizes", type=int, nargs="+", default=[100, 1000, 10000])
|
||||
parser.add_argument("--shapes", nargs="+", choices=["tree", "linear", "layered", "chain", "handler", "flow", "owned", "deep"],
|
||||
default=["tree", "linear"])
|
||||
parser.add_argument("--phase", choices=["inspect", "build"], required=True)
|
||||
parser.add_argument("--syntax", choices=["old", "next"], default="old")
|
||||
parser.add_argument("--profile", choices=["dev", "release"], default="release")
|
||||
args = parser.parse_args()
|
||||
if args.syntax == "old" and args.profile != "release":
|
||||
parser.error("old syntax has no public dev build profile")
|
||||
if args.syntax == "old" and "flow" in args.shapes:
|
||||
parser.error("flow tables require next syntax; compare the old linear shape")
|
||||
if any(size < 2 for size in args.sizes):
|
||||
parser.error("sizes must include at least one function and main")
|
||||
compiler = str(args.compiler.resolve(strict=True))
|
||||
# 历史大项目曾使共享 dev OOM 重启;在子进程内失败,保留同一固定预算。
|
||||
address_limit = 6 * 1024 ** 3
|
||||
resource.setrlimit(resource.RLIMIT_AS, (address_limit, address_limit))
|
||||
os.environ["CARGO_BUILD_JOBS"] = "1"
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
(root / "scale.py").write_bytes(Path(__file__).read_bytes())
|
||||
report = dict(compiler=compiler, compiler_sha256=fingerprint(Path(compiler)),
|
||||
driver_sha256=fingerprint(root / "scale.py"), rounds=3, timeout_seconds=900,
|
||||
phase=args.phase, syntax=args.syntax, profile=args.profile, samples=[])
|
||||
cgroup = Path("/sys/fs/cgroup")
|
||||
report["environment"] = dict(cpu_affinity=sorted(os.sched_getaffinity(0)),
|
||||
cpu_max=(cgroup / "cpu.max").read_text().strip(),
|
||||
memory_max=(cgroup / "memory.max").read_text().strip(),
|
||||
process_virtual_address_limit_bytes=address_limit, cargo_build_jobs=1)
|
||||
memory_before = (cgroup / "memory.events").read_text()
|
||||
report["memory_events_before"] = memory_before
|
||||
initial_oom = dict(line.split() for line in memory_before.splitlines())["oom_kill"]
|
||||
|
||||
def record(sample):
|
||||
report["samples"].append(sample)
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(sample), flush=True)
|
||||
|
||||
for size in args.sizes:
|
||||
for shape in args.shapes:
|
||||
stop = False
|
||||
for round_number in range(3):
|
||||
case = root / f"{shape}-{size}-{round_number}"
|
||||
case.mkdir()
|
||||
path = case / "main.dever"
|
||||
scenarios = [("saved", False, False)] if args.phase == "inspect" else [
|
||||
("first", False, False), ("unchanged", False, False),
|
||||
("body", True, False), ("signature", False, True)]
|
||||
for scenario, changed, signature in scenarios:
|
||||
text, expected = source(size, shape, changed, signature)
|
||||
if scenario != "unchanged":
|
||||
path.write_text(text)
|
||||
formatted = execute([compiler, "fmt", str(case)], case, scenario + "-fmt", 900)
|
||||
if formatted["exit_code"] != 0:
|
||||
record(dict(size=size, shape=shape, round=round_number,
|
||||
scenario=scenario, stage="fmt", **formatted))
|
||||
stop = True
|
||||
break
|
||||
command = [compiler, "inspect", str(path), "--json"]
|
||||
if args.phase == "build":
|
||||
binary = case / scenario
|
||||
command = [compiler, "build", str(path), "--output", str(binary)]
|
||||
if args.syntax == "next":
|
||||
command.extend(["--profile", args.profile])
|
||||
measured = execute(command, case, scenario, 900)
|
||||
sample = dict(size=size, shape=shape, round=round_number, scenario=scenario,
|
||||
source_sha256=fingerprint(path), source_bytes=path.stat().st_size,
|
||||
expected=expected, **measured)
|
||||
if measured["exit_code"] == 0:
|
||||
if args.phase == "build":
|
||||
ran = execute([str(binary)], case, scenario + "-run", 900)
|
||||
sample["execution"] = ran
|
||||
sample["correct"] = ran["exit_code"] == 0 and Path(ran["stdout"]).read_text().strip() == str(expected)
|
||||
sample["binary_sha256"] = fingerprint(binary)
|
||||
sample["binary_bytes"] = binary.stat().st_size
|
||||
else:
|
||||
index = json.loads(Path(measured["stdout"]).read_text())
|
||||
names = {item["name"] for item in index["symbols"]}
|
||||
namespace = "main.main.app" if args.syntax == "next" else "main"
|
||||
count = size - 2 if shape == "handler" else size - 1
|
||||
wanted = {f"{namespace}.main"} | {f"{namespace}.step{i}" for i in range(count)}
|
||||
sample["correct"] = wanted.issubset(names)
|
||||
if args.syntax == "next":
|
||||
by_id = {symbol["id"]: symbol for symbol in index["symbols"]}
|
||||
versions = Counter(by_id[symbol["template"]]["name"] if "template" in symbol
|
||||
else symbol.get("source_name", symbol["name"]) for symbol in index["symbols"]
|
||||
if symbol["kind"] in {"function", "rule", "flow"})
|
||||
sample["checked_function_instances"] = sum(versions.values())
|
||||
sample["instances_per_source"] = dict(sorted(versions.items()))
|
||||
sample["correct"] &= not index["diagnostics"]
|
||||
if shape == "handler":
|
||||
sample["correct"] &= versions[f"{namespace}.apply"] == size - 2
|
||||
sample["correct"] &= sum(versions.values()) == 2 * size - 3
|
||||
sample["index_bytes"] = Path(measured["stdout"]).stat().st_size
|
||||
else:
|
||||
sample["correct"] = False
|
||||
record(sample)
|
||||
memory_after = (cgroup / "memory.events").read_text()
|
||||
if dict(line.split() for line in memory_after.splitlines())["oom_kill"] != initial_oom:
|
||||
record(dict(status="remaining workloads not executed after cgroup OOM",
|
||||
memory_events_after=memory_after))
|
||||
raise SystemExit(1)
|
||||
if not sample["correct"]:
|
||||
stop = True
|
||||
break
|
||||
if stop:
|
||||
record(dict(size=size, shape=shape, status="remaining rounds not executed after failure"))
|
||||
break
|
||||
failed = any(sample.get("correct") is False or sample.get("exit_code", 0) != 0
|
||||
for sample in report["samples"])
|
||||
raise SystemExit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,181 @@
|
||||
"""与 scale.py 同一函数图的独立 Rust/Go 对端;不链接 Dever 运行库。"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import shutil
|
||||
|
||||
from scale import execute, fingerprint
|
||||
|
||||
|
||||
def source(count, shape, language, changed=False, signature=False):
|
||||
definitions = []
|
||||
expected = []
|
||||
if shape == "owned":
|
||||
# 与正式 Dever 输入一致:每段最多 100 层,所有段都依赖 step0。
|
||||
depth = 100
|
||||
definitions.append("struct Parcel { title: String, tags: Vec<String>, number: i64 }" if language == "rust"
|
||||
else "type Parcel struct { title string; tags []string; number int64 }")
|
||||
for index in range(count - 1):
|
||||
extra = (", extra: i64" if language == "rust" else ", extra int64") if signature and index == 0 else ""
|
||||
if index == 0:
|
||||
increment = "extra" if signature else str(2 if changed else 1)
|
||||
terms = ["value.title.chars().count() as i64", "value.tags.len() as i64", "value.number", increment] if language == "rust" else ["int64(len([]rune(value.title)))", "int64(len(value.tags))", "value.number", increment]
|
||||
else:
|
||||
callee = index - 1 if index % depth else 0
|
||||
call = "value, 1" if signature and callee == 0 else "value"
|
||||
terms = [f"step{callee}({call})", "1"]
|
||||
body = sum_terms(terms, language)
|
||||
definitions.append(f"fn step{index}(value: &Parcel{extra}) -> i64 {{ {body} }}" if language == "rust"
|
||||
else f"func step{index}(value Parcel{extra}) int64 {{ return {body} }}")
|
||||
heads = [min(start + depth, count - 1) - 1 for start in range(0, count - 1, depth)]
|
||||
value = "&parcel" if language == "rust" else "parcel"
|
||||
terms = [f"step{head}({value}{', 1' if signature and head == 0 else ''})" for head in heads]
|
||||
body = sum_terms(terms, language)
|
||||
definitions.append(
|
||||
'fn answer() -> i64 {\nlet parcel = Parcel { title: "hello".into(), tags: vec!["one".into(), "two".into()], number: 3 };\n' + body + '\n}'
|
||||
if language == "rust" else
|
||||
'func answer() int64 {\nparcel := Parcel{title: "hello", tags: []string{"one", "two"}, number: 3}\nreturn ' + body + '\n}')
|
||||
bottom = 11 + int(changed and not signature)
|
||||
result = sum(bottom + head % depth + int(head >= depth) for head in heads)
|
||||
return entry(definitions, language), result
|
||||
if shape == "handler":
|
||||
extra = (", offset: i64" if language == "rust" else ", offset int64") if signature else ""
|
||||
result = sum_terms(["transform(value)", "offset"], language) if signature else "transform(value)"
|
||||
definitions.append(f"fn apply<F: Fn(i64) -> i64>(value: i64, transform: F{extra}) -> i64 {{ {result} }}" if language == "rust" else f"func apply(value int64, transform func(int64) int64{extra}) int64 {{ return {result} }}")
|
||||
for index in range(count - 2):
|
||||
increment = str(2 if changed and index == 0 else 1)
|
||||
definitions.append(function(f"step{index}", ["value"], [sum_terms(["value", increment], language)], language))
|
||||
terms = [f"apply(1, step{index}" + (", 0)" if signature else ")") for index in range(count - 2)]
|
||||
definitions.append(function("answer", [], ["0", *terms], language))
|
||||
result = 2 * (count - 2) + int(changed and count > 2)
|
||||
return entry(definitions, language), result
|
||||
for index in range(count - 1):
|
||||
inputs = ["value"] + (["extra"] if signature and index == 0 else [])
|
||||
increment = "extra" if signature and index == 0 else str(2 if changed and index == 0 else 1)
|
||||
terms = ["value", increment]
|
||||
if shape == "tree":
|
||||
terms.extend(f"step{child}(value)" for child in [2 * index + 1, 2 * index + 2] if child < count - 1)
|
||||
elif index > 0:
|
||||
parent = index - 1 if shape in ("chain", "linear") else (index - 1) // 2
|
||||
arguments = "value, 1" if signature and parent == 0 else "value"
|
||||
terms = [f"step{parent}({arguments})", "1"]
|
||||
if shape != "tree":
|
||||
expected.append((expected[parent] + 1) if index else (2 + int(changed)))
|
||||
definitions.append(function(f"step{index}", inputs, [sum_terms(terms, language)], language))
|
||||
indices = [0] if shape == "tree" else [count - 2] if shape == "linear" else range(count - 1)
|
||||
terms = [f"step{index}({'1, 1' if signature and index == 0 else '1'})" for index in indices]
|
||||
definitions.append(function("answer", [], terms, language))
|
||||
result = 2 * (count - 1) + int(changed) if shape == "tree" else expected[-1] if shape == "linear" else sum(expected)
|
||||
return entry(definitions, language), result
|
||||
|
||||
|
||||
def entry(definitions, language):
|
||||
if language == "rust":
|
||||
definitions.append('fn main() { println!("{}", answer()); }')
|
||||
else:
|
||||
definitions.insert(0, 'package main\nimport "fmt"\n\n// Dever Int 溢出终止当前调用;Go 的默认回绕不满足这个合同。\nfunc add(a, b int64) int64 {\n result := a + b\n if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }\n return result\n}')
|
||||
definitions.append('func main() { fmt.Println(answer()) }')
|
||||
return '\n\n'.join(definitions) + '\n'
|
||||
|
||||
|
||||
def sum_terms(terms, language):
|
||||
if language == "rust":
|
||||
return " + ".join(terms)
|
||||
value = terms[0]
|
||||
for term in terms[1:]:
|
||||
value = f"add({value}, {term})"
|
||||
return value
|
||||
|
||||
|
||||
def function(name, inputs, terms, language):
|
||||
if language == "rust":
|
||||
parameters = ", ".join(f"{value}: i64" for value in inputs)
|
||||
body = terms[0] if len(terms) == 1 else 'let mut answer = 0i64;\n' + '\n'.join(f'answer += {term};' for term in terms) + '\nanswer'
|
||||
return f"fn {name}({parameters}) -> i64 {{\n{body}\n}}"
|
||||
parameters = ", ".join(f"{value} int64" for value in inputs)
|
||||
body = "return " + terms[0] if len(terms) == 1 else 'answer := int64(0)\n' + '\n'.join(f'answer = add(answer, {term})' for term in terms) + '\nreturn answer'
|
||||
return f"func {name}({parameters}) int64 {{\n{body}\n}}"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--language', choices=['rust', 'go'], required=True)
|
||||
parser.add_argument('--profile', choices=['dev', 'release'], default='release')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--sizes', nargs='+', type=int, default=[100, 1000, 10000])
|
||||
parser.add_argument('--shapes', nargs='+', choices=['tree', 'linear', 'layered', 'chain', 'handler', 'owned'], default=['tree', 'linear'])
|
||||
args = parser.parse_args()
|
||||
if args.language == 'go' and args.profile != 'release':
|
||||
parser.error('Go uses its normal optimized build; no equivalent Cargo dev profile')
|
||||
if any(size < 2 for size in args.sizes):
|
||||
parser.error('sizes must include at least one function and answer')
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
(root / "scale_reference.py").write_bytes(Path(__file__).read_bytes())
|
||||
(root / "scale.py").write_bytes(Path(__file__).with_name("scale.py").read_bytes())
|
||||
resource.setrlimit(resource.RLIMIT_AS, (6 * 1024 ** 3, 6 * 1024 ** 3))
|
||||
# 使用已复现深调用图需要的 rustc 官方线程栈配置,沿用新旧对照的资源总上限。
|
||||
os.environ['RUST_MIN_STACK'] = '16777216'
|
||||
os.environ['GOMAXPROCS'] = '1'
|
||||
version = execute(['rustc', '+1.95.0', '--version', '--verbose'] if args.language == 'rust' else ['go', 'version'], root, 'toolchain', 30)
|
||||
if version['exit_code']:
|
||||
raise SystemExit('reference toolchain is unavailable: ' + version['stderr'])
|
||||
cgroup = Path('/sys/fs/cgroup')
|
||||
report = dict(language=args.language, profile=args.profile, driver_sha256=fingerprint(root / "scale_reference.py"), rounds=3, timeout_seconds=900,
|
||||
toolchain=Path(version['stdout']).read_text(), semantics='signed 64-bit checked addition; same graph and results; standalone native compiler',
|
||||
environment=dict(cpu_max=(cgroup/'cpu.max').read_text().strip(), memory_max=(cgroup/'memory.max').read_text().strip(),
|
||||
cpu_affinity=sorted(os.sched_getaffinity(0)), virtual_address_limit_bytes=6 * 1024 ** 3,
|
||||
build_jobs=1, go_max_procs=1, application_cache='separate case identity; dependencies remain shared'), samples=[])
|
||||
initial = dict(line.split() for line in (cgroup/'memory.events').read_text().splitlines())['oom_kill']
|
||||
for size in args.sizes:
|
||||
for shape in args.shapes:
|
||||
stop = False
|
||||
for repeat in range(3):
|
||||
case = root/f'{shape}-{size}-{repeat}'
|
||||
case.mkdir()
|
||||
path = case/('main.rs' if args.language == 'rust' else 'main.go')
|
||||
if args.language == 'rust':
|
||||
path.write_text(source(size, shape, args.language)[0])
|
||||
(case/'Cargo.toml').write_text('[package]\nname = "scale-reference"\nversion = "0.0.1"\nedition = "2024"\n[workspace]\n[[bin]]\nname = "reference"\npath = "main.rs"\n[profile.dev]\ndebug = 0\nincremental = true\noverflow-checks = true\n[profile.release]\nlto = "fat"\ncodegen-units = 1\noverflow-checks = true\nstrip = "symbols"\n')
|
||||
prepared = execute(['cargo', '+1.95.0', 'generate-lockfile', '--manifest-path', str(case/'Cargo.toml'), '--offline'], case, 'lock', 30)
|
||||
if prepared['exit_code']: raise SystemExit('reference lock preparation failed: ' + prepared['stderr'])
|
||||
else:
|
||||
# 每轮是新的应用身份,避免不同目录中的 main.go 共享 command-line-arguments 缓存。
|
||||
# 标准库仍复用已有缓存;同一轮的无改动/改体/改签名继续使用本轮身份。
|
||||
(case/'go.mod').write_text(f'module scale-reference/{root.name}/{case.name}\n\ngo 1.25.0\n')
|
||||
for scenario, changed, signature in [('first', False, False), ('unchanged', False, False), ('body', True, False), ('signature', False, True)]:
|
||||
text, expected = source(size, shape, args.language, changed, signature)
|
||||
if scenario != 'unchanged':
|
||||
path.write_text(text)
|
||||
binary = case/scenario
|
||||
command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case/'Cargo.toml'), '--target-dir', str(case/'target'), '--profile', args.profile, '--locked', '--offline', '-j', '1'] if args.language == 'rust' else ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-x', '-o', str(binary), '.']
|
||||
sample = dict(size=size, shape=shape, repeat=repeat, scenario=scenario,
|
||||
source_sha256=fingerprint(path), source_bytes=path.stat().st_size, source_lines=len(text.splitlines()), expected=expected,
|
||||
**execute(command, case, scenario, 900))
|
||||
sample['correct'] = False
|
||||
if sample['exit_code'] == 0:
|
||||
if args.language == 'rust':
|
||||
directory = 'release' if args.profile == 'release' else 'debug'
|
||||
shutil.copyfile(case/'target'/directory/'reference', binary)
|
||||
binary.chmod(0o755)
|
||||
ran = execute([str(binary)], case, scenario+'-run', 900)
|
||||
sample.update(execution=ran, correct=ran['exit_code']==0 and Path(ran['stdout']).read_text().strip()==str(expected),
|
||||
binary_sha256=fingerprint(binary), binary_bytes=binary.stat().st_size)
|
||||
report['samples'].append(sample)
|
||||
(root/'results.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps(sample), flush=True)
|
||||
if dict(line.split() for line in (cgroup/'memory.events').read_text().splitlines())['oom_kill'] != initial:
|
||||
raise SystemExit('remaining work not executed after cgroup OOM')
|
||||
if not sample['correct']:
|
||||
stop = True
|
||||
break
|
||||
if stop:
|
||||
break
|
||||
raise SystemExit(0 if all(sample['correct'] for sample in report['samples']) else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""启动读取同一配置,热路径只借用文本并查询动态数字;对端不共享 Dever 运行库。"""
|
||||
|
||||
|
||||
def config():
|
||||
return {'module': {'main': {'main': {'corpus': '雪0123456789' * 64}}}}
|
||||
|
||||
|
||||
def expected(n):
|
||||
corpus = config()['module']['main']['main']['corpus']
|
||||
total = 0
|
||||
for residue in range(min(n, 1000)):
|
||||
if str(residue) in corpus:
|
||||
count = (n - 1 - residue) // 1000 + 1
|
||||
total += residue * count + 1000 * count * (count - 1) // 2
|
||||
return total
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting corpus: Text
|
||||
rule selected(found: Bool, value: Int) (out: Int)
|
||||
| found | value | out |
|
||||
| true | - | value |
|
||||
| false | - | 0 |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum selected(text.contains(corpus, int.toText(value % 1000)), value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Root { module: Module }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Module { main: Domain }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Domain { main: Settings }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings { corpus: String }
|
||||
fn measure(settings: &Settings, n: i64) -> i64 {
|
||||
let mut total = 0i64;
|
||||
for value in 0..n {
|
||||
let text = (value % 1000).to_string();
|
||||
let selected = if settings.corpus.contains(&text) { value } else { 0 };
|
||||
total = total.checked_add(selected).unwrap();
|
||||
}
|
||||
total
|
||||
}
|
||||
fn main() {
|
||||
let path = std::env::args().nth(2).unwrap();
|
||||
let input = std::fs::read_to_string(path).unwrap();
|
||||
let root: Root = serde_json::from_str(&input).unwrap();
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
println!("{}", measure(&root.module.main.main, n));
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("encoding/json"; "fmt"; "os"; "strconv"; "strings")
|
||||
type Settings struct { Corpus string }
|
||||
type Domain struct { Main Settings }
|
||||
type Module struct { Main Domain }
|
||||
type Root struct { Module Module }
|
||||
func main() {
|
||||
input, err := os.ReadFile(os.Args[2]); if err != nil { panic(err) }
|
||||
var root Root
|
||||
decoder := json.NewDecoder(strings.NewReader(string(input)))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&root); err != nil { panic(err) }
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
text := strconv.FormatInt(value % 1000, 10)
|
||||
selected := int64(0)
|
||||
if strings.Contains(root.Module.Main.Main.Corpus, text) { selected = value }
|
||||
next := total + selected
|
||||
if next < total { panic("integer overflow") }; total = next
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,88 @@
|
||||
"""按固定清单统计手写维护量;非空行不冒充去注释后的代码行。"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
def category(name):
|
||||
path = Path(name)
|
||||
if path.name == "link.md":
|
||||
return "generated-documentation"
|
||||
if path.suffix == ".md":
|
||||
return "documentation"
|
||||
if path.suffix in {".json", ".yaml", ".toml", ".lock", ".mod"} or path.name.startswith("."):
|
||||
return "configuration"
|
||||
if name.startswith("test/"):
|
||||
return "tests-and-benchmark-references"
|
||||
if name.startswith("rust/src/runtime/"):
|
||||
return "runtime"
|
||||
if name.startswith("rust/src/"):
|
||||
return "compiler-cli-process"
|
||||
if name.startswith("examples/next/"):
|
||||
return "new-syntax-design-examples"
|
||||
if name.startswith(("examples/", "skills/")):
|
||||
return "examples-and-skills"
|
||||
if name.startswith("lib/"):
|
||||
return "standard-library"
|
||||
if name.startswith("sdk/"):
|
||||
return "worker-sdk"
|
||||
if name.startswith("editor/"):
|
||||
return "editor"
|
||||
if name.startswith("build/"):
|
||||
return "build-and-release"
|
||||
return "other"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
root = args.root.resolve(strict=True)
|
||||
if args.manifest:
|
||||
names = json.loads(args.manifest.read_text())["files"]
|
||||
else:
|
||||
listed = subprocess.check_output(["git", "-C", str(root), "ls-files",
|
||||
"-z", "--cached", "--others", "--exclude-standard"])
|
||||
names = set(listed.decode().split(chr(0))) - {""}
|
||||
files = []
|
||||
groups = {}
|
||||
for name in sorted(names):
|
||||
path = root / name
|
||||
if not path.exists():
|
||||
continue # Git 中已删除的文件没有当前维护行数。
|
||||
data = path.read_bytes()
|
||||
row = dict(path=name, category=category(name), bytes=len(data),
|
||||
sha256=hashlib.sha256(data).hexdigest())
|
||||
try:
|
||||
lines = data.decode("utf-8").splitlines()
|
||||
except UnicodeDecodeError:
|
||||
row.update(physical_lines=None, nonblank_lines=None)
|
||||
else:
|
||||
row.update(physical_lines=len(lines), nonblank_lines=sum(bool(line.strip()) for line in lines))
|
||||
files.append(row)
|
||||
group = groups.setdefault(row["category"], dict(files=0, binary_files=0,
|
||||
physical_lines=0, nonblank_lines=0, longest=None))
|
||||
group["files"] += 1
|
||||
if row["physical_lines"] is None:
|
||||
group["binary_files"] += 1
|
||||
else:
|
||||
group["physical_lines"] += row["physical_lines"]
|
||||
group["nonblank_lines"] += row["nonblank_lines"]
|
||||
if group["longest"] is None or row["physical_lines"] > group["longest"]["lines"]:
|
||||
group["longest"] = dict(path=name, lines=row["physical_lines"])
|
||||
result = dict(root=str(root), method="All manifest/Git-listed files; UTF-8 splitlines; nonblank includes comments. No extension whitelist. Ignored dependencies/build outputs excluded.",
|
||||
counter_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
groups=groups, files=files)
|
||||
with args.output.open("x") as output:
|
||||
json.dump(result, output, ensure_ascii=False, indent=2)
|
||||
output.write(chr(10))
|
||||
print(json.dumps(groups, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Unicode 文本处理和整数往返;独立 Rust/Go 对端不共享 Dever runtime。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''rule required(value: Int?) (out: Int)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
roundtrip(value: Int) (out: Int) {
|
||||
decorated = " " + int.toText(value) + "雪 "
|
||||
trimmed = text.trim(decorated)
|
||||
joined = text.join(text.split(trimmed, ""), "")
|
||||
out = required(int.parse(text.replace(joined, "雪", "")))
|
||||
}
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum roundtrip(value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''fn roundtrip(value: i64) -> i64 {
|
||||
let mut decorated = String::from(" ");
|
||||
decorated.push_str(&value.to_string());
|
||||
decorated.push_str("雪 ");
|
||||
let trimmed = decorated.trim().to_owned();
|
||||
let pieces: Vec<String> = trimmed.split("").filter(|piece| !piece.is_empty()).map(str::to_owned).collect();
|
||||
let joined = pieces.join("");
|
||||
joined.replace("雪", "").parse().expect("valid integer")
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut total = 0i64;
|
||||
for value in 0..n { total = total.checked_add(roundtrip(value)).expect("sum overflow"); }
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv"; "strings")
|
||||
func roundtrip(value int64) int64 {
|
||||
decorated := " " + strconv.FormatInt(value, 10) + "雪 "
|
||||
trimmed := strings.TrimSpace(decorated)
|
||||
joined := strings.Join(strings.Split(trimmed, ""), "")
|
||||
result, err := strconv.ParseInt(strings.ReplaceAll(joined, "雪", ""), 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
return result
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
next := roundtrip(value)
|
||||
sum := total + next
|
||||
if (next > 0 && sum < total) || (next < 0 && sum > total) { panic("sum overflow") }
|
||||
total = sum
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,36 @@
|
||||
"""逐行写真实 stdout;对端均逐项格式化、持锁写入并传播系统错误。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | do dever.io.println(int.toText(value)) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use std::io::{self, Write};
|
||||
fn line(text: &str) -> io::Result<()> { writeln!(io::stdout().lock(), "{text}") }
|
||||
fn main() -> io::Result<()> {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut count = 0i64;
|
||||
for value in 0..n {
|
||||
line(&value.to_string())?;
|
||||
count = count.checked_add(1).unwrap();
|
||||
}
|
||||
println!("{count}");
|
||||
Ok(())
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
count := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
if _, err := fmt.Fprintln(os.Stdout, strconv.FormatInt(value, 10)); err != nil { panic(err) }
|
||||
count++
|
||||
}
|
||||
fmt.Println(count)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,83 @@
|
||||
"""共享单次异步流的真实消费,包含来源构造、关闭及别名结束检查。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''loop numbers(n: Int) (out: List<Int>)
|
||||
| each value in range(0, n) | result |
|
||||
| out | list value |
|
||||
loop sum(values: AsyncStream<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
loop count(values: AsyncStream<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | count |
|
||||
flow total(n: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| values | calc | stream(numbers(n)) |
|
||||
| out | loop | sum(values) |
|
||||
| remaining | loop | count(values) |
|
||||
| - | check | remaining == 0 else Invalid |
|
||||
cmd total = total
|
||||
'''
|
||||
if language == 'runtime':
|
||||
return '''fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let out = dever_runtime::task::execute(true, async {
|
||||
let values = (0..n).collect::<Vec<_>>();
|
||||
let values = dever_runtime::stream::AsyncStream::values(values);
|
||||
let out = {
|
||||
let _consume = values.close_on_drop();
|
||||
let mut sum = 0i64;
|
||||
while let Some(value) = values.next().await.unwrap() { sum = sum.checked_add(value).unwrap(); }
|
||||
sum
|
||||
};
|
||||
assert_eq!(values.next().await.unwrap(), None);
|
||||
out
|
||||
}).unwrap();
|
||||
println!("{out}");
|
||||
}
|
||||
'''
|
||||
return '''use futures_util::{stream, Stream, StreamExt};
|
||||
use std::{pin::Pin, sync::Arc};
|
||||
use tokio::sync::{Mutex, Semaphore};
|
||||
type Source = Pin<Box<dyn Stream<Item = Result<i64, ()>> + Send>>;
|
||||
struct Shared { source: Mutex<Option<Source>>, closed: Semaphore }
|
||||
struct Consume<'a>(&'a Shared);
|
||||
impl Drop for Consume<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.closed.close();
|
||||
if let Ok(mut source) = self.0.source.try_lock() { source.take(); }
|
||||
}
|
||||
}
|
||||
async fn next(shared: &Shared) -> Option<i64> {
|
||||
let mut source = shared.source.lock().await;
|
||||
let value = match source.as_mut() {
|
||||
None => return None,
|
||||
Some(source) => tokio::select! {
|
||||
biased;
|
||||
_ = shared.closed.acquire() => None,
|
||||
value = source.next() => value,
|
||||
},
|
||||
};
|
||||
if matches!(value, None | Some(Err(_))) { source.take(); }
|
||||
value.transpose().unwrap()
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
|
||||
let out = runtime.block_on(async {
|
||||
let values = (0..n).collect::<Vec<_>>();
|
||||
let shared = Arc::new(Shared { source: Mutex::new(Some(Box::pin(stream::iter(values.into_iter().map(Ok))))), closed: Semaphore::new(0) });
|
||||
let out = {
|
||||
let _consume = Consume(&shared);
|
||||
let mut sum = 0i64;
|
||||
while let Some(value) = next(&shared).await { sum = sum.checked_add(value).unwrap(); }
|
||||
sum
|
||||
};
|
||||
assert_eq!(next(&shared).await, None);
|
||||
out
|
||||
});
|
||||
println!("{out}");
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,290 @@
|
||||
"""真实创建并领取叶子任务;独立 Rust 直接使用 Tokio,不依赖 Dever 运行库。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import statistics
|
||||
|
||||
from scale import execute, fingerprint
|
||||
import task_combinations
|
||||
import channel_reference
|
||||
import stream_reference
|
||||
|
||||
|
||||
def source(language, shape='wait'):
|
||||
if shape == 'stream':
|
||||
return stream_reference.source(language)
|
||||
if shape == 'channel':
|
||||
return channel_reference.source(language)
|
||||
if shape in {'timeout', 'race', 'group', 'parallel', 'blocking', 'blocking_run'}:
|
||||
return task_combinations.source(language, shape)
|
||||
if language == 'dever':
|
||||
return """identity(value: Int) (out: Int) { out = value }
|
||||
flow receive(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(identity(value)) |
|
||||
| out | calc | wait(task) |
|
||||
loop total(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum receive(value) |
|
||||
cmd total = total
|
||||
"""
|
||||
if shape != 'wait':
|
||||
return cleanup_source(language, shape)
|
||||
if language == 'runtime':
|
||||
return '''fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let result = dever_runtime::task::run(true, 4096, async |scope| {
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let task = scope.spawn_leaf(async move { value }).unwrap();
|
||||
sum = sum.checked_add(task.wait().await.unwrap()).expect("sum overflow");
|
||||
}
|
||||
Ok::<_, ()>(sum)
|
||||
}).unwrap().unwrap();
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use std::sync::Arc;
|
||||
use tokio::{sync::Semaphore, runtime::Builder};
|
||||
use tokio_util::task::{TaskTracker, AbortOnDropHandle};
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let runtime = Builder::new_current_thread().enable_time().build().unwrap();
|
||||
let result = runtime.block_on(async {
|
||||
let capacity = Arc::new(Semaphore::new(4096));
|
||||
let tracker = TaskTracker::new();
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let tracking = tracker.token();
|
||||
let task = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
drop(permit);
|
||||
(value, tracking)
|
||||
}));
|
||||
let (value, _tracking) = task.await.unwrap();
|
||||
sum = sum.checked_add(value).expect("sum overflow");
|
||||
}
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
sum
|
||||
});
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("fmt"; "os"; "strconv")
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
sum := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
completed := make(chan int64, 1)
|
||||
go func(input int64) { completed <- input }(value)
|
||||
next := sum + <-completed
|
||||
if next < sum { panic("sum overflow") }; sum = next
|
||||
}
|
||||
fmt.Println(sum)
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def cleanup_source(language, shape):
|
||||
prefix = '''use std::{future::pending, sync::{Arc, atomic::{AtomicI64, Ordering}}};
|
||||
struct Released(Arc<AtomicI64>, i64);
|
||||
impl Drop for Released {
|
||||
fn drop(&mut self) { self.0.fetch_add(self.1, Ordering::SeqCst); }
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let released = Arc::new(AtomicI64::new(0));
|
||||
'''
|
||||
if language == 'runtime':
|
||||
begin = ''' dever_runtime::task::run(true, 64, async |scope| {
|
||||
for value in 0..n {
|
||||
let held = Released(released.clone(), value);
|
||||
let task = scope.spawn_leaf(async move {
|
||||
let _held = held;
|
||||
pending::<i64>().await
|
||||
}).unwrap();
|
||||
'''
|
||||
action = ' assert_eq!(task.stop().await, Ok(None));' if shape == 'stop' else ' drop(task);\n tokio::task::yield_now().await;'
|
||||
end = '''
|
||||
}
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
'''
|
||||
else:
|
||||
begin = ''' use tokio::{sync::Semaphore, runtime::Builder};
|
||||
use tokio_util::task::{TaskTracker, AbortOnDropHandle};
|
||||
let runtime = Builder::new_current_thread().enable_time().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let capacity = Arc::new(Semaphore::new(64));
|
||||
let tracker = TaskTracker::new();
|
||||
for value in 0..n {
|
||||
let held = Released(released.clone(), value);
|
||||
let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let tracking = tracker.token();
|
||||
let task = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let _held = held;
|
||||
let value = pending::<i64>().await;
|
||||
drop(permit);
|
||||
(value, tracking)
|
||||
}));
|
||||
'''
|
||||
action = ' task.abort();\n assert!(task.await.unwrap_err().is_cancelled());' if shape == 'stop' else ' drop(task);\n tokio::task::yield_now().await;'
|
||||
end = '''
|
||||
}
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
});
|
||||
'''
|
||||
return prefix + begin + action + end + ' println!("{}", released.load(Ordering::SeqCst));\n}\n'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--core-source', type=Path, required=True)
|
||||
parser.add_argument('--size', type=int, default=1000000)
|
||||
parser.add_argument('--shape', choices=['wait', 'stop', 'drop', 'timeout', 'race', 'group', 'parallel', 'blocking', 'blocking_run', 'channel', 'stream'], default='wait')
|
||||
parser.add_argument('--previous-source', type=Path)
|
||||
parser.add_argument('--dever-binary', type=Path, help='Include real compiled Dever task operations against independent references')
|
||||
args = parser.parse_args()
|
||||
if not 1 <= args.size <= 1000000000:
|
||||
parser.error('size must be within 1..1000000000')
|
||||
if args.dever_binary and args.shape in {'stop', 'drop'}:
|
||||
parser.error('Dever comparisons support wait/timeout/race/group/parallel')
|
||||
compiler = args.dever_binary.resolve(strict=True) if args.dever_binary else None
|
||||
core = args.core_source.resolve(strict=True)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
os.environ.update(CARGO_BUILD_JOBS='1', GOMAXPROCS='1', GOTOOLCHAIN='local')
|
||||
for name in ['task.py', 'scale.py', 'task_combinations.py', 'channel_reference.py', 'stream_reference.py']:
|
||||
(root / name).write_bytes(Path(__file__).with_name(name).read_bytes())
|
||||
inputs = [core / 'rust/Cargo.lock'] + sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.suffix in {'.rs', '.toml'})
|
||||
if compiler:
|
||||
inputs += sorted((core / 'rust/src/compiler').rglob('*.rs'))
|
||||
inputs += sorted((core / 'lib').rglob('*.dv'))
|
||||
hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs}
|
||||
for path in inputs:
|
||||
saved = root / 'inputs' / path.relative_to(core)
|
||||
saved.parent.mkdir(parents=True, exist_ok=True)
|
||||
saved.write_bytes(path.read_bytes())
|
||||
previous = args.previous_source.resolve(strict=True) if args.previous_source else None
|
||||
previous_hashes = {str(path.relative_to(previous)): fingerprint(path) for path in sorted((previous / 'rust/src/runtime').rglob('*')) if path.suffix in {'.rs', '.toml'}} if previous else {}
|
||||
report = dict(size=args.size, shape=args.shape, rounds=7, cpu_affinity=sorted(os.sched_getaffinity(0)), inputs=hashes, previous_source=str(previous) if previous else None, previous_inputs=previous_hashes, versions={}, builds=[], samples=[],
|
||||
semantics='Spawn one leaf task, await its result, checked i64 checksum; one task at a time. Runtime and independent Rust use the same Tokio current-thread runtime, task tracking and capacity permits. Rust uses AbortOnDropHandle. Go uses native goroutines/channels with GOMAXPROCS=1. This measures successful spawn/join, not equivalence of failure journals, descendant cleanup or language frontend performance.',
|
||||
scope='Whole-process time. wait4 RSS may include Python fork memory; not application-only RSS. Cargo dependencies share a within-run build cache; build times are not cold-build comparisons.',
|
||||
environment={name: (Path('/sys/fs/cgroup')/name).read_text().strip() for name in ['cpu.max', 'memory.max']})
|
||||
if args.shape != 'wait':
|
||||
report['semantics'] = 'Cancel a pending leaf before its first poll using stop/await or drop/yield. A destructor accumulates every owned input and is checked after root cleanup. Independent Rust uses the same Tokio, capacity and task tracker, but has no unclaimed-fault journal. Go is omitted because goroutine cancellation is not equivalent.'
|
||||
if args.shape in {'timeout', 'race', 'group'}:
|
||||
report['semantics'] = 'Successful task composition: timeout with a 60s deadline and immediate result; race of two equal results with biased parameter order and loser cancellation/join; group of two zero-output members at limit=1, checked nonnegative input and full drain. Checksums are checked i64 sums. Independent Rust uses Tokio, AbortOnDropHandle, Semaphore, TaskTracker and FuturesUnordered; no Dever runtime. Fault journals and descendant faults are tested separately, not compared by these successful-path timings. Go omitted because cancellation contracts differ.'
|
||||
if args.shape == 'parallel':
|
||||
report['semantics'] = 'Two concurrent CPU calls per group, each summing 4096 checked i64 additions modulo 97. Eight worker slots, Tokio spawn_blocking, owned values, task tracking and cancellation handles; independent Rust does not use Dever runtime. Successful-path timings do not compare fault journals; queued cancellation and running-work cleanup are tested separately. Go omitted because cancellation contracts differ.'
|
||||
blocking = args.shape in {'blocking', 'blocking_run'}
|
||||
if blocking:
|
||||
report['semantics'] = 'Real Argon2id v19 verification at default m=19456,t=2,p=1 with the same public benchmark password and PHC input. Owned password/hash per call, eight worker slots, direct blocking or spawned blocking task then wait; checked checksum of successful verifications. Independent Rust uses Argon2 and Tokio directly, not Dever runtime. Success timing does not establish fault-journal equivalence; cancellation and late errors are tested separately.'
|
||||
if compiler:
|
||||
report['compiler'] = dict(binary=str(compiler), sha256=fingerprint(compiler))
|
||||
report['semantics'] += ' Dever uses real task flow steps, sequential loop sum and the generated CMD input/output boundary.'
|
||||
if args.shape == 'channel':
|
||||
report['semantics'] = 'One producer task sends n integers to a shared bounded channel at capacity 64; one consumer verifies every receive and accumulates a checked i64 checksum. Explicit close, full drain and producer join. Independent Rust uses async-channel 2.5.0 and Tokio directly, with task capacity and tracking, no Dever runtime. Success timing does not establish fault-journal equivalence; cancellation, aliases and close are tested separately.'
|
||||
if args.shape == 'stream':
|
||||
report['semantics'] = 'Construct n integers, move the Vec into one shared boxed async stream, consume once with checked i64 checksum, close it and verify a second traversal is empty. Independent Rust directly uses futures-util and Tokio mutex/semaphore, with close notification and a consumption guard; it does not depend on Dever runtime. Successful drain timings do not compare runtime-fault diagnostics or the closed-then-cancelled-pull drop path, which are separately tested.'
|
||||
def save():
|
||||
(root / 'results.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
for language, command in [('rust', ['rustc', '+1.95.0', '--version', '--verbose']), ('go', ['go', 'version'])]:
|
||||
result = execute(command, root, language + '-version', 30)
|
||||
assert result['exit_code'] == 0, result
|
||||
report['versions'][language] = Path(result['stdout']).read_text()
|
||||
programs = {}
|
||||
arguments = {}
|
||||
languages = ['runtime', 'rust'] + (['go'] if args.shape == 'wait' else []) + (['previous'] if previous else []) + (['dever'] if compiler else [])
|
||||
for language in languages:
|
||||
case = root / language
|
||||
case.mkdir()
|
||||
path = case / ('main.go' if language == 'go' else 'app.dever' if language == 'dever' else 'main.rs')
|
||||
path.write_text(source('runtime' if language == 'previous' else language, args.shape))
|
||||
arguments[language] = [str(args.size)]
|
||||
if language == 'dever':
|
||||
formatted = dict(language='dever-format', **execute([str(compiler), 'fmt', str(path)], case, 'format', 30))
|
||||
report['builds'].append(formatted)
|
||||
save()
|
||||
assert formatted['exit_code'] == 0, formatted
|
||||
binary = case / 'program'
|
||||
command = [str(compiler), 'build', str(path), '--profile', 'release', '--output', str(binary)]
|
||||
arguments[language] = ['main.main.total', json.dumps(dict(n=args.size))]
|
||||
elif language == 'go':
|
||||
(case / 'go.mod').write_text(f'module tasks/{root.name}\n\ngo 1.25.0\n')
|
||||
binary = case / 'program'
|
||||
command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-o', str(binary), '.']
|
||||
else:
|
||||
dependency = 'tokio = { version = "=1.53.1", features = ["rt", "sync", "time", "macros"] }'
|
||||
dependency += '\nfutures-util = { version = "=0.3.34", default-features = false, features = ["std"] }'
|
||||
if language in ['runtime', 'previous']:
|
||||
dependency += f'\ndever-runtime = {{ path = {json.dumps(str((previous if language == "previous" else core) / "rust/src/runtime"))} }}'
|
||||
else:
|
||||
dependency += '\ntokio-util = { version = "=0.7.19", features = ["rt"] }'
|
||||
if blocking:
|
||||
dependency += '\nargon2 = { version = "=0.5.3", features = ["zeroize"] }\nzeroize = "=1.9.0"'
|
||||
if args.shape == 'channel':
|
||||
dependency += '\nasync-channel = "=2.5.0"'
|
||||
(case / 'Cargo.toml').write_text('[package]\nname = "task-reference"\nversion = "0.0.1"\nedition = "2024"\n[[bin]]\nname = "task-reference"\npath = "main.rs"\n[dependencies]\n' + dependency + '\n[profile.release]\nlto = "fat"\ncodegen-units = 1\noverflow-checks = true\nstrip = "symbols"\n')
|
||||
command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case / 'Cargo.toml'), '--offline', '--release', '--target-dir', str(root / 'cargo-build')]
|
||||
binary = case / 'program'
|
||||
result = dict(language=language, source_sha256=fingerprint(path), **execute(command, case, 'build', 900))
|
||||
report['builds'].append(result)
|
||||
save()
|
||||
assert result['exit_code'] == 0, result
|
||||
if language not in ['go', 'dever']:
|
||||
shutil.copy2(root / 'cargo-build/release/task-reference', binary)
|
||||
result['binary'] = str(binary)
|
||||
result['binary_sha256'] = fingerprint(binary)
|
||||
programs[language] = binary
|
||||
languages = list(programs)
|
||||
if blocking:
|
||||
fixture = execute([str(programs['rust']), '--fixture'], root, 'fixture', 60)
|
||||
report['fixture'] = fixture
|
||||
save()
|
||||
assert fixture['exit_code'] == 0, fixture
|
||||
encoded = Path(fixture['stdout']).read_text().strip()
|
||||
password = 'public-benchmark-password'
|
||||
for language in languages:
|
||||
if language == 'dever':
|
||||
arguments[language] = ['main.main.total', json.dumps(dict(n=args.size, password=password, hash=encoded))]
|
||||
else:
|
||||
arguments[language] += [password, encoded]
|
||||
# 模 97 的完整周期与尾段独立计算校验和,不复制被测循环。
|
||||
def residue_sum(end):
|
||||
periods, rest = divmod(end, 97)
|
||||
return periods * 96 * 97 // 2 + rest * (rest - 1) // 2
|
||||
expected = args.size * (args.size - 1) // 2
|
||||
if args.shape == 'parallel':
|
||||
period = [residue_sum(value + 4096) - residue_sum(value)
|
||||
+ residue_sum(value + 4097) - residue_sum(value + 1) for value in range(97)]
|
||||
periods, rest = divmod(args.size, 97)
|
||||
expected = periods * sum(period) + sum(period[:rest])
|
||||
report['expected'] = expected
|
||||
for repeat in range(-1, 7):
|
||||
assert hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime changed during measurement'
|
||||
assert all(fingerprint(previous / name) == digest for name, digest in previous_hashes.items()), 'previous runtime changed during measurement'
|
||||
for offset in range(len(languages)):
|
||||
language = languages[(repeat + 1 + offset) % len(languages)]
|
||||
binary = programs[language]
|
||||
result = dict(language=language, repeat=repeat, **execute([str(binary)] + arguments[language], binary.parent, f'run-{repeat}', 60))
|
||||
output = Path(result['stdout']).read_text()
|
||||
value = json.loads(output)['data'] if language == 'dever' and result['exit_code'] == 0 else output
|
||||
result['correct'] = result['exit_code'] == 0 and int(value) == expected
|
||||
report['samples'].append(result)
|
||||
save()
|
||||
assert result['correct'], result
|
||||
report['medians'] = {language: statistics.median(row['seconds'] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0) for language in languages}
|
||||
save()
|
||||
print(json.dumps(report['medians']))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,319 @@
|
||||
"""任务组合的真实 Dever 与独立 Tokio 参考;由 task.py 固定轮次并保存原始结果。"""
|
||||
|
||||
|
||||
def parallel_source(language):
|
||||
if language == 'dever':
|
||||
return '''loop calculate(value: Int) (out: Int)
|
||||
| each item in range(0, 4096) | result |
|
||||
| out | sum (value + item) % 97 |
|
||||
flow receive(value: Int) (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | compute | parallel(calculate(value)) |
|
||||
| right | calc | compute | parallel(calculate(value + 1)) |
|
||||
| out | calc | - | left + right |
|
||||
loop total(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum receive(value) |
|
||||
cmd total = total
|
||||
'''
|
||||
kernel = '''fn calculate(value: i64) -> i64 {
|
||||
let mut sum = 0i64;
|
||||
for item in 0..4096i64 {
|
||||
sum = sum.checked_add(value.checked_add(item).unwrap() % 97).unwrap();
|
||||
}
|
||||
sum
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
'''
|
||||
if language == 'runtime':
|
||||
return kernel + ''' let result = dever_runtime::task::run(true, 4096, async |scope| {
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let next = value.checked_add(1).unwrap();
|
||||
let (left, right) = dever_runtime::task::join!(
|
||||
scope.parallel(move || calculate(value)),
|
||||
scope.parallel(move || calculate(next))
|
||||
);
|
||||
sum = sum.checked_add(left.unwrap().checked_add(right.unwrap()).unwrap()).unwrap();
|
||||
}
|
||||
Ok::<_, ()>(sum)
|
||||
}).unwrap().unwrap();
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
return '''use std::sync::Arc;
|
||||
use tokio::{sync::Semaphore, runtime::Builder};
|
||||
use tokio_util::task::{TaskTracker, AbortOnDropHandle};
|
||||
''' + kernel + ''' let result = Builder::new_current_thread().max_blocking_threads(8).enable_time().build().unwrap().block_on(async {
|
||||
let workers = Arc::new(Semaphore::new(8));
|
||||
let tracker = TaskTracker::new();
|
||||
let calculate_async = async |value: i64| {
|
||||
let worker = workers.clone().acquire_owned().await.unwrap();
|
||||
let tracking = tracker.token();
|
||||
let task = AbortOnDropHandle::new(tokio::task::spawn_blocking(move || {
|
||||
let result = calculate(value);
|
||||
drop(worker);
|
||||
(result, tracking)
|
||||
}));
|
||||
task.await.unwrap().0
|
||||
};
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let next = value.checked_add(1).unwrap();
|
||||
let (left, right) = tokio::join!(calculate_async(value), calculate_async(next));
|
||||
sum = sum.checked_add(left.checked_add(right).unwrap()).unwrap();
|
||||
}
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
sum
|
||||
});
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def blocking_source(language, spawned):
|
||||
if language == 'dever':
|
||||
steps = '''| task | calc | run(dever.crypto.passwordVerify(password, hash)) |
|
||||
| valid | calc | wait(task) |''' if spawned else '| valid | calc | blocking(dever.crypto.passwordVerify(password, hash)) |'
|
||||
return '''flow receive(value: Int, password: Secret, hash: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
''' + steps + '''
|
||||
| - | check | valid else Invalid |
|
||||
| out | calc | value |
|
||||
loop total(n: Int, password: Secret, hash: Text) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum receive(value, password, hash) |
|
||||
cmd total = total
|
||||
'''
|
||||
prefix = '''use argon2::{Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString};
|
||||
use zeroize::Zeroizing;
|
||||
fn main() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let first = args.next().unwrap();
|
||||
if first == "--fixture" {
|
||||
let salt = SaltString::encode_b64(&[7u8; 16]).unwrap();
|
||||
println!("{}", Argon2::default().hash_password(b"public-benchmark-password", &salt).unwrap());
|
||||
return;
|
||||
}
|
||||
let n: i64 = first.parse().unwrap();
|
||||
let password = Zeroizing::new(args.next().unwrap().into_bytes());
|
||||
let encoded = args.next().unwrap();
|
||||
'''
|
||||
if language == 'runtime':
|
||||
operation = 'spawn_blocking' if spawned else 'parallel'
|
||||
invocation = f'''let valid = scope.{operation}(move || dever_runtime::crypto::password_verify(&secret, &hash))'''
|
||||
invocation += '.unwrap().await.unwrap().unwrap();' if spawned else '.await.unwrap().unwrap();'
|
||||
return prefix + ''' let result = dever_runtime::task::run(true, 4096, async |scope| {
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let secret = dever_runtime::value::secret::Secret::from_input(password.to_vec());
|
||||
let hash = encoded.clone();
|
||||
''' + invocation + '''
|
||||
assert!(valid);
|
||||
sum = sum.checked_add(value).unwrap();
|
||||
}
|
||||
Ok::<_, ()>(sum)
|
||||
}).unwrap().unwrap();
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
verify = '''use std::sync::Arc;
|
||||
use tokio::{runtime::Builder, sync::Semaphore};
|
||||
use tokio_util::{task::{TaskTracker, AbortOnDropHandle}, sync::CancellationToken};
|
||||
fn verify(password: &[u8], encoded: &str) -> bool {
|
||||
assert!(encoded.len() <= 256);
|
||||
let hash = PasswordHash::new(encoded).unwrap();
|
||||
assert_eq!(hash.algorithm.as_str(), "argon2id");
|
||||
assert_eq!(hash.version, Some(19));
|
||||
assert!(hash.salt.is_some() && hash.hash.is_some());
|
||||
let limits = Params::default();
|
||||
assert!((Params::MIN_M_COST..=limits.m_cost()).contains(&hash.params.get_decimal("m").unwrap()));
|
||||
assert!((Params::MIN_T_COST..=limits.t_cost()).contains(&hash.params.get_decimal("t").unwrap()));
|
||||
assert!((Params::MIN_P_COST..=limits.p_cost()).contains(&hash.params.get_decimal("p").unwrap()));
|
||||
let params = Params::try_from(&hash).unwrap();
|
||||
assert!(params.output_len().unwrap_or(Params::DEFAULT_OUTPUT_LEN) <= Params::DEFAULT_OUTPUT_LEN);
|
||||
assert!(params.keyid().is_empty() && params.data().is_empty());
|
||||
Argon2::default().verify_password(password, &hash).is_ok()
|
||||
}
|
||||
'''
|
||||
call = '''let worker = workers.clone().acquire_owned().await.unwrap();
|
||||
let task = AbortOnDropHandle::new(tokio::task::spawn_blocking(move || {
|
||||
let result = verify(&secret, &hash);
|
||||
drop(worker);
|
||||
(result, tracking)
|
||||
}));
|
||||
let valid = task.await.unwrap().0;'''
|
||||
if spawned:
|
||||
call = '''let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let workers = workers.clone();
|
||||
let cancel = cancelled.child_token();
|
||||
let task = tokio::spawn(async move {
|
||||
let worker = tokio::select! { biased;
|
||||
() = cancel.cancelled() => return (false, tracking),
|
||||
worker = workers.acquire_owned() => worker.unwrap(),
|
||||
};
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
if cancel.is_cancelled() { return (false, tracking); }
|
||||
let result = verify(&secret, &hash);
|
||||
drop(worker);
|
||||
(result, tracking)
|
||||
}).await.unwrap();
|
||||
drop(permit);
|
||||
result
|
||||
});
|
||||
let valid = task.await.unwrap().0;'''
|
||||
return verify + prefix + ''' let result = Builder::new_current_thread().max_blocking_threads(8).enable_time().build().unwrap().block_on(async {
|
||||
let workers = Arc::new(Semaphore::new(8));
|
||||
let capacity = Arc::new(Semaphore::new(4096));
|
||||
let cancelled = CancellationToken::new();
|
||||
let tracker = TaskTracker::new();
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
let secret = password.clone();
|
||||
let hash = encoded.clone();
|
||||
let tracking = tracker.token();
|
||||
''' + call + '''
|
||||
assert!(valid);
|
||||
sum = sum.checked_add(value).unwrap();
|
||||
}
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
sum
|
||||
});
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def source(language, shape):
|
||||
if shape in {'blocking', 'blocking_run'}:
|
||||
return blocking_source(language, shape == 'blocking_run')
|
||||
if shape == 'parallel':
|
||||
return parallel_source(language)
|
||||
if language == 'dever':
|
||||
expression = {
|
||||
'timeout': 'timeout(run(identity(value)), 60000, fallback)',
|
||||
'race': 'race(run(identity(value)), run(identity(value)))',
|
||||
}
|
||||
body = f'| out | calc | {expression[shape]} |' if shape != 'group' else '''| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, member(value)) |
|
||||
| - | calc | run(tasks, member(value)) |
|
||||
| - | calc | wait(tasks) |
|
||||
| out | calc | value |'''
|
||||
return '''identity(value: Int) (out: Int) { out = value }
|
||||
fallback() (out: Int) { out = -1 }
|
||||
member(value: Int) () { check value >= 0 else Invalid }
|
||||
flow receive(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
''' + body + '''
|
||||
loop total(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum receive(value) |
|
||||
cmd total = total
|
||||
'''
|
||||
if language == 'runtime':
|
||||
body = {
|
||||
'timeout': '''let task = scope.spawn_leaf(async move { value }).unwrap();
|
||||
let received = match task.timeout(60000).await.unwrap() {
|
||||
dever_runtime::task::Timed::Ready(value) => value,
|
||||
dever_runtime::task::Timed::Expired(_) => -1,
|
||||
};''',
|
||||
'race': '''let mut first = scope.spawn_leaf(async move { value }).unwrap();
|
||||
let mut second = scope.spawn_leaf(async move { value }).unwrap();
|
||||
let (winner, result) = dever_runtime::task::select! { biased;
|
||||
result = &mut first => (0, result),
|
||||
result = &mut second => (1, result),
|
||||
};
|
||||
let mut cleanup = dever_runtime::task::Selection::new(scope);
|
||||
if winner == 0 { second.cancel(); cleanup.join(second).await; } else { first.cancel(); cleanup.join(first).await; }
|
||||
cleanup.finish(result.is_ok());
|
||||
let received = result.unwrap();''',
|
||||
'group': '''let mut group = dever_runtime::task::Group::new(scope, 1).unwrap();
|
||||
for _ in 0..2 {
|
||||
group.run(|| scope.spawn_leaf(async move {
|
||||
if value < 0 { Err(()) } else { Ok(()) }
|
||||
})).await.unwrap().unwrap();
|
||||
}
|
||||
group.wait().await.unwrap().unwrap();
|
||||
let received = value;''',
|
||||
}[shape]
|
||||
return '''fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let result = dever_runtime::task::run(true, 4096, async |scope| {
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
''' + body + '''
|
||||
sum = sum.checked_add(received).expect("sum overflow");
|
||||
}
|
||||
Ok::<_, ()>(sum)
|
||||
}).unwrap().unwrap();
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
body = {
|
||||
'timeout': '''let mut task = launch(value);
|
||||
let deadline = tokio::time::Instant::now().checked_add(std::time::Duration::from_millis(60000)).unwrap();
|
||||
let received = tokio::select! { biased;
|
||||
result = &mut task => result.unwrap().0,
|
||||
() = tokio::time::sleep_until(deadline) => {
|
||||
task.abort();
|
||||
match task.await { Ok(_) => (), Err(error) if error.is_cancelled() => (), Err(error) => std::panic::resume_unwind(error.into_panic()) }
|
||||
-1
|
||||
},
|
||||
};''',
|
||||
'race': '''let mut first = launch(value);
|
||||
let mut second = launch(value);
|
||||
let (winner, result) = tokio::select! { biased;
|
||||
result = &mut first => (0, result),
|
||||
result = &mut second => (1, result),
|
||||
};
|
||||
let loser = if winner == 0 { second } else { first };
|
||||
loser.abort();
|
||||
match loser.await { Ok(_) => (), Err(error) if error.is_cancelled() => (), Err(error) => std::panic::resume_unwind(error.into_panic()) }
|
||||
let received = result.unwrap().0;''',
|
||||
'group': '''let mut tasks = futures_util::stream::FuturesUnordered::new();
|
||||
for _ in 0..2 {
|
||||
while let Some(Some(result)) = tasks.next().now_or_never() { check_member(result); }
|
||||
if tasks.len() == 1 { check_member(tasks.next().await.unwrap()); }
|
||||
let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let tracking = tracker.token();
|
||||
tasks.push(AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let result = if value < 0 { Err(()) } else { Ok(()) };
|
||||
drop(permit);
|
||||
(result, tracking)
|
||||
})));
|
||||
}
|
||||
while let Some(result) = tasks.next().await { check_member(result); }
|
||||
let received = value;''',
|
||||
}[shape]
|
||||
return '''use std::sync::Arc;
|
||||
use tokio::{sync::Semaphore, runtime::Builder};
|
||||
use tokio_util::task::{TaskTracker, AbortOnDropHandle, task_tracker::TaskTrackerToken};
|
||||
use futures_util::{FutureExt, StreamExt};
|
||||
fn check_member(result: Result<(Result<(), ()>, TaskTrackerToken), tokio::task::JoinError>) {
|
||||
result.unwrap().0.unwrap();
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let result = Builder::new_current_thread().enable_time().build().unwrap().block_on(async {
|
||||
let capacity = Arc::new(Semaphore::new(4096));
|
||||
let tracker = TaskTracker::new();
|
||||
let launch = |value: i64| {
|
||||
let permit = capacity.clone().try_acquire_owned().unwrap();
|
||||
let tracking = tracker.token();
|
||||
AbortOnDropHandle::new(tokio::spawn(async move { drop(permit); (value, tracking) }))
|
||||
};
|
||||
let mut sum = 0i64;
|
||||
for value in 0..n {
|
||||
''' + body + '''
|
||||
sum = sum.checked_add(received).expect("sum overflow");
|
||||
}
|
||||
tracker.close();
|
||||
tracker.wait().await;
|
||||
sum
|
||||
});
|
||||
println!("{result}");
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,68 @@
|
||||
"""反复解析同一 CA 并构造客户端配置;握手行为另由真实连接测试验证。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''setting ca_pem: Text
|
||||
configured(ca: Bytes) (out: Int) {
|
||||
config = dever.tls.client(ca)
|
||||
out = 1
|
||||
}
|
||||
loop configure(ca: Bytes, n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum configured(ca) |
|
||||
measure(n: Int) (out: Int) { out = configure(dever.bytes.fromText(ca_pem), n) }
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use rustls::{ClientConfig, RootCertStore, pki_types::{CertificateDer, pem::PemObject}};
|
||||
use std::sync::Arc;
|
||||
use serde::Deserialize;
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Root { module: Module }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Module { main: Domain }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Domain { main: Settings }
|
||||
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Settings { ca_pem: String }
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let data = std::fs::read(std::env::args().nth(2).unwrap()).unwrap();
|
||||
let input: Root = serde_json::from_slice(&data).unwrap();
|
||||
let ca = input.module.main.main.ca_pem.as_bytes();
|
||||
let mut total = 0i64;
|
||||
for _ in 0..n {
|
||||
let mut roots = RootCertStore::empty();
|
||||
for certificate in CertificateDer::pem_slice_iter(ca) {
|
||||
roots.add(certificate.unwrap()).unwrap();
|
||||
}
|
||||
assert!(!roots.is_empty());
|
||||
let config = ClientConfig::builder()
|
||||
.with_root_certificates(roots).with_no_client_auth();
|
||||
let _config = Arc::new(config);
|
||||
total = total.checked_add(1).unwrap();
|
||||
}
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("crypto/tls"; "crypto/x509"; "encoding/json"; "fmt"; "os"; "strconv"; "bytes")
|
||||
type Settings struct { CaPem string `json:"ca_pem"` }
|
||||
type Domain struct { Main Settings }
|
||||
type Module struct { Main Domain }
|
||||
type Root struct { Module Module }
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
data, err := os.ReadFile(os.Args[2]); if err != nil { panic(err) }
|
||||
var input Root
|
||||
decoder := json.NewDecoder(bytes.NewReader(data)); decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil { panic(err) }
|
||||
ca := []byte(input.Module.Main.Main.CaPem)
|
||||
total := int64(0)
|
||||
for i := int64(0); i < n; i++ {
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) { panic("invalid CA") }
|
||||
config := &tls.Config{RootCAs: roots, ClientSessionCache: tls.NewLRUClientSessionCache(256)}
|
||||
if config.RootCAs == nil { panic("missing roots") }
|
||||
next := total + 1; if next < total { panic("count overflow") }; total = next
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,76 @@
|
||||
"""真实系统随机源生成密钥,两次 HMAC 比较后校验所有输入;不输出 Secret。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''flow roundtrip(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| key | flow | dever.crypto.token(32) |
|
||||
| message | calc | dever.bytes.fromText(int.toText(value)) |
|
||||
| first | calc | dever.crypto.hmacSha256(key, message) |
|
||||
| second | calc | dever.crypto.hmacSha256(key, message) |
|
||||
| - | check | dever.crypto.constantTimeEq(first, second) else Invalid |
|
||||
| out | calc | value |
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum roundtrip(value) |
|
||||
cmd bench = measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use bytes::Bytes;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use subtle::ConstantTimeEq;
|
||||
use zeroize::Zeroizing;
|
||||
fn token(length: i64) -> Result<Zeroizing<Vec<u8>>, String> {
|
||||
if !(16..=1024).contains(&length) { return Err("token length must be between 16 and 1024 bytes".into()); }
|
||||
let mut key = Zeroizing::new(vec![0; length as usize]);
|
||||
getrandom::getrandom(&mut key).map_err(|e| format!("secure random source unavailable: {e}"))?;
|
||||
Ok(key)
|
||||
}
|
||||
fn sign(key: &[u8], message: &[u8]) -> Bytes {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(key).unwrap();
|
||||
mac.update(message);
|
||||
Bytes::copy_from_slice(&mac.finalize().into_bytes())
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut out = 0i64;
|
||||
for value in 0..n {
|
||||
let key = token(32).unwrap();
|
||||
let message = Bytes::from(value.to_string());
|
||||
let first = sign(&key, &message);
|
||||
let second = sign(&key, &message);
|
||||
assert!(bool::from(first.ct_eq(&second)));
|
||||
out = out.checked_add(value).unwrap();
|
||||
}
|
||||
println!("{out}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("crypto/rand"; "crypto/hmac"; "crypto/sha256"; "fmt"; "os"; "strconv")
|
||||
func token(length int) []byte {
|
||||
if length < 16 || length > 1024 { panic("invalid token length") }
|
||||
key := make([]byte, length)
|
||||
if _, err := rand.Read(key); err != nil { panic(err) }
|
||||
return key
|
||||
}
|
||||
func sign(key, message []byte) []byte {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write(message)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
||||
out := int64(0)
|
||||
for value := int64(0); value < n; value++ {
|
||||
key := token(32)
|
||||
message := []byte(strconv.FormatInt(value, 10))
|
||||
first, second := sign(key, message), sign(key, message)
|
||||
if !hmac.Equal(first, second) { panic("HMAC mismatch") }
|
||||
clear(key)
|
||||
next := out + value; if next < out { panic("overflow") }; out = next
|
||||
}
|
||||
fmt.Println(out)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,87 @@
|
||||
"""UUID 解析、规范输出与内容校验;Rust 使用同版本 uuid,Go 复用 encoding/hex。"""
|
||||
|
||||
|
||||
def source(language):
|
||||
if language == 'dever':
|
||||
return '''rule requiredUuid(value: Uuid?) (out: Uuid)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
rule requiredText(value: Text?) (out: Text)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
rule requiredInt(value: Int?) (out: Int)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
roundtrip(value: Int) (out: Int) {
|
||||
source = "550e8400-e29b-41d4-a716-" + int.toText(value + 100000000000)
|
||||
parsed = requiredUuid(uuid.parse(source))
|
||||
last = requiredText(text.at(uuid.toText(parsed), 35))
|
||||
out = requiredInt(int.parse(last))
|
||||
}
|
||||
loop measure(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum roundtrip(value) |
|
||||
cmd bench = app.measure
|
||||
'''
|
||||
if language == 'rust':
|
||||
return '''use uuid::Uuid;
|
||||
fn parse(value: &str) -> Option<Uuid> {
|
||||
if value.len() != 36 { return None; }
|
||||
Uuid::try_parse(value).ok()
|
||||
}
|
||||
fn roundtrip(value: i64) -> i64 {
|
||||
let mut source = String::from("550e8400-e29b-41d4-a716-");
|
||||
source.push_str(&value.checked_add(100000000000).unwrap().to_string());
|
||||
let parsed = parse(&source).unwrap();
|
||||
let last = parsed.hyphenated().to_string().chars().nth(35).unwrap().to_string();
|
||||
last.parse().unwrap()
|
||||
}
|
||||
fn main() {
|
||||
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
||||
let mut total = 0i64;
|
||||
for value in 0..n { total = total.checked_add(roundtrip(value)).expect("sum overflow"); }
|
||||
println!("{total}");
|
||||
}
|
||||
'''
|
||||
return '''package main
|
||||
import ("encoding/hex"; "fmt"; "os"; "strconv")
|
||||
func parse(value string) [16]byte {
|
||||
if len(value) != 36 || value[8] != '-' || value[13] != '-' || value[18] != '-' || value[23] != '-' { panic("UUID format") }
|
||||
var raw [32]byte
|
||||
copy(raw[:8], value[:8]); copy(raw[8:12], value[9:13]); copy(raw[12:16], value[14:18])
|
||||
copy(raw[16:20], value[19:23]); copy(raw[20:], value[24:])
|
||||
var uuid [16]byte
|
||||
if _, err := hex.Decode(uuid[:], raw[:]); err != nil { panic(err) }
|
||||
return uuid
|
||||
}
|
||||
func toText(value [16]byte) string {
|
||||
var text [36]byte
|
||||
hex.Encode(text[:8], value[:4]); hex.Encode(text[9:13], value[4:6]); hex.Encode(text[14:18], value[6:8])
|
||||
hex.Encode(text[19:23], value[8:10]); hex.Encode(text[24:], value[10:])
|
||||
text[8], text[13], text[18], text[23] = '-', '-', '-', '-'
|
||||
return string(text[:])
|
||||
}
|
||||
func add(left, right int64) int64 {
|
||||
sum := left + right
|
||||
if (right > 0 && sum < left) || (right < 0 && sum > left) { panic("sum overflow") }
|
||||
return sum
|
||||
}
|
||||
func roundtrip(value int64) int64 {
|
||||
source := "550e8400-e29b-41d4-a716-" + strconv.FormatInt(add(value, 100000000000), 10)
|
||||
text := toText(parse(source))
|
||||
last := string([]rune(text)[35])
|
||||
result, err := strconv.ParseInt(last, 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
return result
|
||||
}
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil { panic(err) }
|
||||
total := int64(0)
|
||||
for value := int64(0); value < n; value++ { total = add(total, roundtrip(value)) }
|
||||
fmt.Println(total)
|
||||
}
|
||||
'''
|
||||
@@ -0,0 +1,188 @@
|
||||
"""真实外部 Worker 四方进程对照;固定后端,核对全部文本和干净退出。"""
|
||||
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("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--old-compiler", type=Path, required=True)
|
||||
parser.add_argument("--baseline-identity", type=Path, required=True)
|
||||
parser.add_argument("--worker", type=Path, required=True,
|
||||
help="precompiled test/rust/build/port/worker_fixture.rs.txt")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
core = Path(__file__).resolve().parents[2]
|
||||
fixture = Path(__file__).parent / "fixtures/worker"
|
||||
root = args.output.absolute()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
baseline = json.loads(args.baseline_identity.read_text())
|
||||
assert fingerprint(args.old_compiler) == baseline["original_compiler"]["sha256"]
|
||||
report = dict(rounds=7, warmups=1, cpu_affinity=[0],
|
||||
contract="One CMD decodes a required List<Text>, starts one real Worker, validates hello/ready and health, calls unit once, calls echo sequentially for every item, returns every complete text and waits for shutdown. One shared backend executable serves all four programs. New/old published programs execute after removing their source Worker image. Wall/CPU include process startup, protocol, result encoding and shutdown.",
|
||||
limitations="Bounded successful external-exec workload and CMD input rejection; not full Worker cancellation, restart limits, process descendants, schema-range failures or auth/tenant equivalence. Independent peers use a disk executable; Dever embeds its executable and owns Scope resources. Rust/Go do not link Dever runtime. Go uses blocking standard pipes; Rust uses Tokio framing/deadlines. Tail summaries describe a whole CMD, not individual calls. wait4 RSS can include inherited launcher memory.",
|
||||
baseline_identity=baseline, commands=[], functional=[], samples=[])
|
||||
|
||||
def save():
|
||||
(root / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
def run(label, command):
|
||||
row = execute(list(map(str, command)), root, label, 1800)
|
||||
report["commands"].append(row)
|
||||
save()
|
||||
assert row["exit_code"] == 0, row
|
||||
return row
|
||||
|
||||
worker = root / "worker-image"
|
||||
shutil.copyfile(args.worker, worker)
|
||||
worker.chmod(0o755)
|
||||
report["worker"] = dict(path=str(worker), sha256=fingerprint(worker),
|
||||
source_sha256=fingerprint(core / "test/rust/build/port/worker_fixture.rs.txt"))
|
||||
report["compilers"] = {}
|
||||
binaries = {}
|
||||
for name, compiler in [("new", args.compiler), ("old", args.old_compiler)]:
|
||||
compiler = compiler.resolve(strict=True)
|
||||
report["compilers"][name] = dict(path=str(compiler), sha256=fingerprint(compiler))
|
||||
project = root / name
|
||||
domain = project / "module/benchmark/echo"
|
||||
domain.joinpath("bin").mkdir(parents=True)
|
||||
shutil.copyfile(worker, domain / "bin/worker")
|
||||
domain.joinpath("bin/worker").chmod(0o755)
|
||||
target = domain / ("app/main.dever" if name == "new" else "app.dever")
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
shutil.copyfile(fixture / ("app.dever" if name == "new" else "old.dever.txt"), target)
|
||||
failure = " fails dever.api.Error" if name == "old" else ""
|
||||
domain.joinpath("port.dever").write_text(
|
||||
f"echo(value: Text) (out: Text){failure}\nunit() (){failure}\n")
|
||||
domain.joinpath("adapter.dever").write_text('external exec "bin/worker" {}\n')
|
||||
domain.joinpath("api.dever").write_text("cmd bench = app.batch\n")
|
||||
project.joinpath("config").mkdir()
|
||||
project.joinpath("config/setting.json").write_text("{}\n")
|
||||
run(name + "-fmt", [compiler, "fmt", project])
|
||||
binaries[name] = root / (name + "-app")
|
||||
run(name + "-build", [compiler, "build", project, "--output", binaries[name]])
|
||||
domain.joinpath("bin/worker").unlink()
|
||||
|
||||
rust = root / "rust"
|
||||
rust.mkdir()
|
||||
shutil.copyfile(fixture / "peer.rs.txt", rust / "main.rs")
|
||||
shutil.copyfile(core / "rust/Cargo.lock", rust / "Cargo.lock")
|
||||
rust.joinpath("Cargo.toml").write_text('''[package]
|
||||
name = "worker-peer"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[[bin]]
|
||||
name = "worker-peer"
|
||||
path = "main.rs"
|
||||
[dependencies]
|
||||
bytes = "=1.12.1"
|
||||
futures-util = { version = "=0.3.34", features = ["sink"] }
|
||||
tokio = { version = "=1.53.1", features = ["rt", "time", "process", "io-util"] }
|
||||
tokio-util = { version = "=0.7.19", features = ["codec"] }
|
||||
serde = { version = "=1.0.228", features = ["derive"] }
|
||||
serde_json = "=1.0.145"
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
overflow-checks = true
|
||||
strip = true
|
||||
''')
|
||||
run("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
|
||||
"--manifest-path", rust / "Cargo.toml", "--target-dir", rust / "target"])
|
||||
locked = {(p["name"], p["version"]) for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]}
|
||||
assert all((p["name"], p["version"]) in locked for p in
|
||||
tomllib.loads((rust / "Cargo.lock").read_text())["package"] if "source" in p)
|
||||
binaries["rust"] = rust / "target/release/worker-peer"
|
||||
go = root / "go"
|
||||
go.mkdir()
|
||||
go.joinpath("go.mod").write_text("module worker-peer\n\ngo 1.25.0\n")
|
||||
shutil.copyfile(fixture / "peer.go.txt", go / "main.go")
|
||||
run("go-fmt", ["gofmt", "-w", go / "main.go"])
|
||||
binaries["go"] = root / "go-app"
|
||||
run("go-build", ["go", "-C", go, "build", "-buildvcs=false", "-trimpath",
|
||||
"-ldflags=-s -w", "-o", binaries["go"], "."])
|
||||
report["binaries"] = {name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size)
|
||||
for name, path in binaries.items()}
|
||||
sources = [Path(__file__), *fixture.iterdir(), core / "test/rust/build/port/worker_fixture.rs.txt",
|
||||
core / "rust/Cargo.toml", core / "rust/Cargo.lock", core / "rust/src/runtime/Cargo.toml",
|
||||
*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"),
|
||||
rust / "Cargo.toml", rust / "Cargo.lock", rust / "main.rs", go / "go.mod", go / "main.go"]
|
||||
sources += [p for name in ("new", "old") for p in root.joinpath(name, "module").rglob("*.dever")]
|
||||
report["sources"] = {str(p): fingerprint(p) for p in sources}
|
||||
report["source_lines"] = {str(p): len(p.read_text().splitlines()) for p in sources}
|
||||
snapshots = root / "sources"
|
||||
snapshots.mkdir()
|
||||
for index, path in enumerate(sources):
|
||||
shutil.copyfile(path, snapshots / f"{index}-{path.name}")
|
||||
for name, binary in binaries.items():
|
||||
shutil.copyfile(binary, root / (name + "-binary"))
|
||||
save()
|
||||
|
||||
def command(name, data):
|
||||
if name in ("new", "old"):
|
||||
return [str(binaries[name]), "benchmark.echo.bench", data]
|
||||
return [str(binaries[name]), str(worker), data]
|
||||
|
||||
def checked(name, row, values):
|
||||
assert row["exit_code"] == 0 and not row["timeout"], row
|
||||
answer = json.loads(Path(row["stdout"]).read_text())
|
||||
if name in ("new", "old"):
|
||||
assert answer["code"] == 0, answer
|
||||
answer = answer["data"]
|
||||
assert answer == values, (name, "returned content differs")
|
||||
row["checked"] = True
|
||||
|
||||
invalid = ['{}', '{"values":null}', '{"values":[null]}', '{"values":[1]}',
|
||||
'{"values":[],"extra":1}', '{"values":[],"values":[]}',
|
||||
'{"values":[],"\\u0076alues":[]}']
|
||||
for name in binaries:
|
||||
for index, data in enumerate(invalid):
|
||||
row = execute(command(name, data), root, f"{name}-invalid-{index}", 30)
|
||||
report["functional"].append(dict(implementation=name, case=index, **row))
|
||||
save()
|
||||
assert row["exit_code"] != 0 and not row["timeout"], row
|
||||
assert Path(row["stderr"]).read_text().strip(), row
|
||||
report["functional"][-1]["checked"] = True
|
||||
cases = dict(empty=[], single=["雪🙂\u0000quote\"\\"],
|
||||
small=[f"{i}:" + "雪🙂" * 9 for i in range(512)],
|
||||
medium=[f"{i}:" + "雪🙂" * 146 for i in range(32)],
|
||||
large=["雪🙂" * 9362])
|
||||
os.sched_setaffinity(0, {0})
|
||||
os.environ["GOMAXPROCS"] = "1"
|
||||
names = list(binaries)
|
||||
for repeat in range(-1, 7):
|
||||
assert all(fingerprint(Path(p)) == digest for p, digest in report["sources"].items())
|
||||
assert all(fingerprint(path) == report["binaries"][name]["sha256"] for name, path in binaries.items())
|
||||
assert fingerprint(worker) == report["worker"]["sha256"]
|
||||
for case, values in cases.items():
|
||||
data = json.dumps(dict(values=values), ensure_ascii=False)
|
||||
order = names[repeat % len(names):] + names[:repeat % len(names)]
|
||||
if repeat % 2:
|
||||
order = list(reversed(order))
|
||||
for name in order:
|
||||
row = execute(command(name, data), root, f"{repeat}-{case}-{name}", 30)
|
||||
report["samples"].append(dict(implementation=name, case=case, repeat=repeat, **row))
|
||||
save()
|
||||
checked(name, row, values)
|
||||
report["samples"][-1]["checked"] = True
|
||||
save()
|
||||
report["summary"] = {}
|
||||
for case in cases:
|
||||
report["summary"][case] = {}
|
||||
for name in names:
|
||||
rows = [r for r in report["samples"] if r["case"] == case and r["implementation"] == name and r["repeat"] >= 0]
|
||||
report["summary"][case][name] = dict(seconds=statistics.median(r["seconds"] for r in rows),
|
||||
cpu_seconds=statistics.median(r["user_cpu_seconds"] + r["system_cpu_seconds"] for r in rows))
|
||||
save()
|
||||
print(json.dumps(dict(functional=len(report["functional"]), measured=len(report["samples"]), summary=report["summary"])))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user