Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

@@ -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(())
}