Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/python3
|
||||
"""协议故障与半帧 fixture;不代替 SDK 验收。"""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import struct
|
||||
import sys
|
||||
|
||||
def read():
|
||||
size = struct.unpack('>I', sys.stdin.buffer.read(4))[0]
|
||||
return json.loads(sys.stdin.buffer.read(size))
|
||||
|
||||
def write(value):
|
||||
body = json.dumps(value).encode()
|
||||
sys.stdout.buffer.write(struct.pack('>I', len(body)) + body)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
hello = read()
|
||||
root = pathlib.Path(hello.pop('setting')['directory'])
|
||||
hello['kind'] = 'ready'
|
||||
write(hello)
|
||||
remaining = None
|
||||
while True:
|
||||
frame = read()
|
||||
kind = frame['kind']
|
||||
if kind == 'health':
|
||||
write(frame)
|
||||
elif kind == 'shutdown':
|
||||
(root / 'shutdown').touch()
|
||||
write(frame)
|
||||
break
|
||||
elif kind == 'cancel':
|
||||
(root / 'cancelled').touch()
|
||||
if remaining is not None:
|
||||
sys.stdout.buffer.write(remaining)
|
||||
sys.stdout.buffer.flush()
|
||||
remaining = None
|
||||
else:
|
||||
write(dict(kind='error', id=frame['id'], error='dever.cancelled', payload=None))
|
||||
elif kind == 'call':
|
||||
operation = frame['operation']
|
||||
if operation in ('hang', 'partial'):
|
||||
(root / 'started').touch()
|
||||
if operation == 'partial':
|
||||
body = json.dumps(dict(kind='result', id=frame['id'], payload={})).encode()
|
||||
sys.stdout.buffer.write(struct.pack('>I', len(body)) + body[:5])
|
||||
sys.stdout.buffer.flush()
|
||||
remaining = body[5:]
|
||||
elif operation == 'invalid':
|
||||
write(dict(kind='result', id=frame['id'] + 1, payload={}))
|
||||
else:
|
||||
write(dict(kind='result', id=frame['id'], payload=dict(value=frame['payload']['value'], pid=os.getpid())))
|
||||
@@ -0,0 +1,203 @@
|
||||
use dever_runtime::{
|
||||
task,
|
||||
wire::json::Json,
|
||||
worker::{self, Contract, Reply},
|
||||
};
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, sync::Arc};
|
||||
mod performance;
|
||||
static CONTRACT: Contract = Contract {
|
||||
port: "demo.test",
|
||||
schema: "runtime-worker-test",
|
||||
adapter: "default",
|
||||
capabilities: &[],
|
||||
operations: &["echo", "hang", "partial", "invalid"],
|
||||
};
|
||||
struct Fixture {
|
||||
directory: tempfile::TempDir,
|
||||
path: Arc<dever_runtime::process::Executable>,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("worker");
|
||||
fs::write(&path, include_str!("fixture.py")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
Self {
|
||||
directory,
|
||||
path: Arc::new(path.as_path().into()),
|
||||
}
|
||||
}
|
||||
fn setting(&self) -> Result<Json, String> {
|
||||
Json::encode(&serde_json::json!({"directory":self.directory.path()}))
|
||||
}
|
||||
}
|
||||
async fn finish(response: worker::Response) -> Result<serde_json::Value, String> {
|
||||
let decoded = match &response.reply {
|
||||
Reply::Result(payload) => serde_json::from_str(payload).map_err(|e| e.to_string()),
|
||||
_ => Err("unexpected error".into()),
|
||||
};
|
||||
response.finish(decoded).await
|
||||
}
|
||||
async fn call(
|
||||
scope: &task::Scope,
|
||||
fixture: &Fixture,
|
||||
operation: &'static str,
|
||||
payload: serde_json::Value,
|
||||
) -> io::Result<worker::Response> {
|
||||
worker::call(
|
||||
scope,
|
||||
&fixture.path,
|
||||
&CONTRACT,
|
||||
|| fixture.setting(),
|
||||
operation,
|
||||
Json::encode(&payload).unwrap(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn marked(path: &std::path::Path) {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while !path.exists() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(2)).await
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_cancel_drains_partial_frames_and_reuses_session() {
|
||||
for operation in ["hang", "partial"] {
|
||||
let fixture = Fixture::new();
|
||||
let marker = fixture.directory.path().join("started");
|
||||
let result = task::run(true, 16, async |scope| {
|
||||
let before = finish(
|
||||
call(scope, &fixture, "echo", serde_json::json!({"value":1}))
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let path = fixture.path.clone();
|
||||
let setting = fixture.setting().unwrap();
|
||||
let pending = scope
|
||||
.spawn(move |child| async move {
|
||||
worker::call(
|
||||
&child,
|
||||
&path,
|
||||
&CONTRACT,
|
||||
|| Ok(setting),
|
||||
operation,
|
||||
Json::encode(&serde_json::json!({})).unwrap(),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.unwrap();
|
||||
marked(&marker).await;
|
||||
pending.stop().await.unwrap();
|
||||
assert!(fixture.directory.path().join("cancelled").exists());
|
||||
let after = finish(
|
||||
call(scope, &fixture, "echo", serde_json::json!({"value":2}))
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(before["pid"], after["pid"]);
|
||||
assert_eq!(after["value"], 2);
|
||||
Ok::<_, String>(after["pid"].as_u64().unwrap())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!std::path::Path::new(&format!("/proc/{result}")).exists());
|
||||
assert!(fixture.directory.path().join("shutdown").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_protocol_or_output_rejection_reaps_before_return() {
|
||||
for invalid in [true, false] {
|
||||
let fixture = Fixture::new();
|
||||
task::run(true, 16, async |scope| {
|
||||
let value = finish(
|
||||
call(scope, &fixture, "echo", serde_json::json!({"value":1}))
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let pid = value["pid"].as_u64().unwrap();
|
||||
if invalid {
|
||||
assert!(
|
||||
call(scope, &fixture, "invalid", serde_json::json!({}))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
call(scope, &fixture, "echo", serde_json::json!({"value":2}))
|
||||
.await
|
||||
.unwrap()
|
||||
.finish::<()>(Err("bad typed output".into()))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(!std::path::Path::new(&format!("/proc/{pid}")).exists());
|
||||
let restarted = finish(
|
||||
call(scope, &fixture, "echo", serde_json::json!({"value":3}))
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(restarted["pid"].as_u64().unwrap(), pid);
|
||||
assert_eq!(restarted["value"], 3);
|
||||
Ok::<_, String>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_failure_invalidates_queued_calls_and_limits_restarts() {
|
||||
let fixture = Fixture::new();
|
||||
task::run(true, 16, async |scope| {
|
||||
let response = call(scope, &fixture, "echo", serde_json::json!({"value":1}))
|
||||
.await
|
||||
.unwrap();
|
||||
// 已持有响应直到类型验证,后续调用必定还在等待同一会话许可。
|
||||
let queued = call(scope, &fixture, "echo", serde_json::json!({"value":2}));
|
||||
tokio::pin!(queued);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut queued => panic!("queued call crossed validation boundary"),
|
||||
_ = tokio::task::yield_now() => {},
|
||||
}
|
||||
assert!(
|
||||
response
|
||||
.finish::<()>(Err("bad typed output".into()))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(queued.await.err().unwrap().to_string().contains("queued"));
|
||||
for _ in 0..2 {
|
||||
assert!(
|
||||
call(scope, &fixture, "invalid", serde_json::json!({}))
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("out of order")
|
||||
);
|
||||
}
|
||||
let error = call(scope, &fixture, "echo", serde_json::json!({"value":3}))
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.to_string().contains("restart budget"), "{error}");
|
||||
Ok::<_, String>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! 固定轮次的真实 Worker 回包对照;启动和输入准备在计时外,原始样本全部输出。
|
||||
use super::*;
|
||||
use std::{path::PathBuf, time::Instant};
|
||||
|
||||
static BENCH: Contract = Contract {
|
||||
port: "demo.bench",
|
||||
schema: "worker-reply-bench",
|
||||
adapter: "default",
|
||||
capabilities: &[],
|
||||
operations: &["echo"],
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Echo {
|
||||
out: String,
|
||||
}
|
||||
|
||||
async fn echo(
|
||||
scope: &task::Scope,
|
||||
executable: &Arc<dever_runtime::process::Executable>,
|
||||
input: Json,
|
||||
) -> String {
|
||||
let response = worker::call(
|
||||
scope,
|
||||
executable,
|
||||
&BENCH,
|
||||
|| Ok(Json::null()),
|
||||
"echo",
|
||||
input,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let decoded = match &response.reply {
|
||||
Reply::Result(payload) => {
|
||||
serde_json::from_slice::<Echo>(payload.as_ref()).map_err(|e| e.to_string())
|
||||
}
|
||||
_ => Err("expected echo result".into()),
|
||||
};
|
||||
response.finish(decoded).await.unwrap().out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "explicit release performance probe; requires precompiled worker fixture"]
|
||||
fn worker_reply_cost() {
|
||||
let fixture = PathBuf::from(
|
||||
std::env::var_os("DEVER_WORKER_BENCH_FIXTURE")
|
||||
.expect("precompiled Worker fixture is required"),
|
||||
);
|
||||
let executable = Arc::new(fixture.as_path().into());
|
||||
task::run(true, 32, async |scope| {
|
||||
println!("case,sample,iterations,elapsed_ns,checksum");
|
||||
for (size, iterations) in [(64, 512), (65_536, 64), (1_048_576, 8)] {
|
||||
let text = "雪🙂".repeat(size / 7);
|
||||
let input = Json::encode(&serde_json::json!({"value": text})).unwrap();
|
||||
assert_eq!(echo(scope, &executable, input.clone()).await, text);
|
||||
// 一次预热和七次测量;响应内容核对在计时后进行,保留所有响应到本轮结束。
|
||||
for sample in -1..7 {
|
||||
let inputs = vec![input.clone(); iterations];
|
||||
let mut results = Vec::with_capacity(iterations);
|
||||
let started = Instant::now();
|
||||
for input in inputs {
|
||||
results.push(echo(scope, &executable, input).await);
|
||||
}
|
||||
let elapsed = started.elapsed().as_nanos();
|
||||
assert!(results.iter().all(|value| *value == text));
|
||||
println!(
|
||||
"worker_reply_{size},{sample},{iterations},{elapsed},{}",
|
||||
text.len() * iterations
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok::<_, String>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user