Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,53 @@
|
||||
"""C ABI 同步回调:编译器 manifest、生命周期、业务错误和非法缓冲区。"""
|
||||
import json
|
||||
import pathlib
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
manifest = json.loads(pathlib.Path(sys.argv[1]).read_text())
|
||||
binary = sys.argv[2]
|
||||
hello = {name: manifest[name] for name in ("port", "schema", "adapter", "operations", "capabilities")}
|
||||
hello.update(kind="hello", version="dever-component-1", setting={"marker": "unused"})
|
||||
|
||||
|
||||
def frame(value):
|
||||
body = json.dumps(value, ensure_ascii=False).encode()
|
||||
return struct.pack(">I", len(body)) + body
|
||||
|
||||
|
||||
def run(messages, suffix=b""):
|
||||
result = subprocess.run([binary], input=b"".join(map(frame, messages)) + suffix, capture_output=True, timeout=3)
|
||||
body = result.stdout
|
||||
replies = []
|
||||
while body:
|
||||
size = struct.unpack(">I", body[:4])[0]
|
||||
assert size <= len(body) - 4
|
||||
replies.append(json.loads(body[4:4+size]))
|
||||
body = body[4+size:]
|
||||
return result, replies
|
||||
|
||||
|
||||
call = dict(kind="call", id=1, operation="echo", payload=dict(value=2**63-1, label="中文", items=[]))
|
||||
result, replies = run([hello, dict(kind="health", id=0), call, dict(kind="cancel", id=1), dict(kind="call", id=2, operation="fail", payload={}), dict(kind="shutdown")])
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert replies[2]["payload"] == dict(out=2**63-1, name="中文")
|
||||
assert replies[3]["error"] == "demo.service.port.Error.Rejected"
|
||||
assert replies[3]["payload"]["message"] == "business rejection"
|
||||
assert replies[4] == dict(kind="shutdown")
|
||||
assert result.stderr == b"closed\n"
|
||||
|
||||
for changed in [dict(schema="wrong"), dict(operations=["other"])]:
|
||||
result, replies = run([hello | changed])
|
||||
assert result.returncode != 0 and not replies
|
||||
assert b"closed" not in result.stderr
|
||||
|
||||
for changed in [dict(id=2), dict(operation="missing"), dict(operation="invalid"), dict(id=-1)]:
|
||||
result, replies = run([hello, call | changed])
|
||||
assert result.returncode != 0 and len(replies) == 1
|
||||
assert b"closed" in result.stderr
|
||||
|
||||
body = b'{"kind":"health","id":0,"id":0}'
|
||||
result, replies = run([hello], struct.pack(">I", len(body)) + body)
|
||||
assert result.returncode != 0 and len(replies) == 1
|
||||
print("C ABI: 8 protocol cases passed")
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "dever_ffi.h"
|
||||
#include <yyjson.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
static const char contract[] =
|
||||
#include "manifest.h"
|
||||
;
|
||||
|
||||
static int open_worker(void *context, dever_ffi_slice setting) {
|
||||
(void)context; (void)setting;
|
||||
return DEVER_FFI_OK;
|
||||
}
|
||||
static int invoke(void *context, dever_ffi_slice operation, dever_ffi_slice payload, dever_ffi_output *output) {
|
||||
(void)context;
|
||||
if (operation.size == 7 && memcmp(operation.data,"invalid",7) == 0) {
|
||||
output->size = output->capacity + 1;
|
||||
return DEVER_FFI_OK;
|
||||
}
|
||||
if (operation.size == 4 && memcmp(operation.data,"fail",4) == 0) {
|
||||
const char *error = "{\"error\":\"demo.service.port.Error.Rejected\",\"payload\":{\"message\":\"business rejection\"}}";
|
||||
output->size = strlen(error); memcpy(output->data,error,output->size);
|
||||
return DEVER_FFI_ERROR;
|
||||
}
|
||||
yyjson_doc *input = yyjson_read(payload.data,payload.size,0);
|
||||
if (input == NULL) return DEVER_FFI_FAULT;
|
||||
yyjson_val *root = yyjson_doc_get_root(input);
|
||||
yyjson_mut_doc *result = yyjson_mut_doc_new(NULL);
|
||||
yyjson_mut_val *record = yyjson_mut_obj(result);
|
||||
yyjson_mut_doc_set_root(result,record);
|
||||
yyjson_mut_obj_add_val(result,record,"out",yyjson_val_mut_copy(result,yyjson_obj_get(root,"value")));
|
||||
yyjson_mut_obj_add_val(result,record,"name",yyjson_val_mut_copy(result,yyjson_obj_get(root,"label")));
|
||||
size_t size; char *text = yyjson_mut_write(result,0,&size);
|
||||
int okay = text != NULL && size <= output->capacity;
|
||||
if (okay) { memcpy(output->data,text,size); output->size = size; }
|
||||
free(text); yyjson_mut_doc_free(result); yyjson_doc_free(input);
|
||||
return okay ? DEVER_FFI_OK : DEVER_FFI_FAULT;
|
||||
}
|
||||
static void close_worker(void *context) { (void)context; fputs("closed\n",stderr); }
|
||||
int main(void) {
|
||||
dever_ffi_handler handler = {DEVER_FFI_ABI_V1,NULL,open_worker,invoke,close_worker};
|
||||
dever_ffi_slice manifest = {contract,sizeof(contract)-1};
|
||||
return dever_ffi_serve(&handler,manifest);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""使用编译器导出的 manifest,驱动真实 SDK 子进程。"""
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import pathlib
|
||||
import select
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
MANIFEST = pathlib.Path(sys.argv[1])
|
||||
SDK = pathlib.Path(sys.argv[2])
|
||||
LANGUAGE = sys.argv[3]
|
||||
CONTRACT = json.loads(MANIFEST.read_text())
|
||||
sys.argv[1:] = []
|
||||
|
||||
|
||||
class WorkerProtocol(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.marker = pathlib.Path(self.directory.name) / "started"
|
||||
entry = pathlib.Path(__file__).with_name("python_worker.py" if LANGUAGE == "python" else "javascript_worker.mjs")
|
||||
command = [sys.executable, "-I", "-B", str(entry)] if LANGUAGE == "python" else ["node", str(entry)]
|
||||
if LANGUAGE == "go":
|
||||
command = [str(SDK)]
|
||||
self.process = subprocess.Popen(
|
||||
command + [str(MANIFEST), str(SDK)],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
)
|
||||
self.addCleanup(self.close)
|
||||
hello = {name: CONTRACT[name] for name in ("port", "schema", "adapter", "operations", "capabilities")}
|
||||
hello.update(kind="hello", version="dever-component-1", setting={"marker": str(self.marker)})
|
||||
self.send(hello)
|
||||
hello.pop("setting")
|
||||
hello["kind"] = "ready"
|
||||
self.assertEqual(self.receive(), hello)
|
||||
self.send({"kind": "health", "id": 0})
|
||||
self.assertEqual(self.receive(), {"kind": "health", "id": 0})
|
||||
|
||||
def close(self):
|
||||
if self.process.poll() is None:
|
||||
self.process.kill()
|
||||
self.process.communicate(timeout=3)
|
||||
|
||||
def send(self, value):
|
||||
body = json.dumps(value, ensure_ascii=False).encode()
|
||||
self.process.stdin.write(struct.pack(">I", len(body)) + body)
|
||||
self.process.stdin.flush()
|
||||
|
||||
def receive(self):
|
||||
self.assertTrue(select.select([self.process.stdout], [], [], 3)[0], "Worker did not reply")
|
||||
prefix = self.process.stdout.read(4)
|
||||
self.assertEqual(len(prefix), 4, "Worker closed protocol output")
|
||||
return json.loads(self.process.stdout.read(struct.unpack(">I", prefix)[0]), parse_float=Decimal)
|
||||
|
||||
def call(self, identity, operation, payload):
|
||||
self.send(dict(kind="call", id=identity, operation=operation, payload=payload))
|
||||
return self.receive()
|
||||
|
||||
def test_typed_values_business_error_and_reuse(self):
|
||||
for identity, value in enumerate([-(2**63), 2**63 - 1], 1):
|
||||
reply = self.call(identity, "echo", dict(value=value, label="中文", items=[value]))
|
||||
self.assertEqual(reply, dict(kind="result", id=identity, payload=dict(out=value, name="中文")))
|
||||
reply = self.call(3, "fail", {})
|
||||
self.assertEqual(reply, dict(kind="error", id=3, error="demo.service.port.Error.Rejected", payload=dict(message="business rejection")))
|
||||
reply = self.call(4, "echo", dict(value=42, label=None, items=[]))
|
||||
self.assertEqual(reply["payload"], dict(out=42, name=None))
|
||||
self.send(dict(kind="shutdown"))
|
||||
self.assertEqual(self.receive(), dict(kind="shutdown"))
|
||||
self.assertEqual(self.process.wait(timeout=3), 0)
|
||||
|
||||
def test_cancel_drains_handler_and_allows_next_call(self):
|
||||
self.send(dict(kind="call", id=1, operation="hang", payload={}))
|
||||
deadline = time.monotonic() + 3
|
||||
while not self.marker.exists() and time.monotonic() < deadline:
|
||||
time.sleep(0.002)
|
||||
self.assertTrue(self.marker.exists())
|
||||
self.send(dict(kind="cancel", id=1))
|
||||
self.assertEqual(self.receive(), dict(kind="error", id=1, error="dever.cancelled", payload=None))
|
||||
self.assertTrue(self.marker.with_suffix(".stopped").exists())
|
||||
self.assertEqual(self.call(2, "echo", dict(value=42, label=None, items=[]))["payload"]["out"], 42)
|
||||
|
||||
def test_json_numbers_remain_exact_and_float_fields_are_numeric(self):
|
||||
body = b'{"kind":"call","id":1,"operation":"raw","payload":{"value":{"tiny":1e-9999,"precise":0.1234567890123456789012345678901234,"large":1e9999,"integer":123456789012345678901234567890123456789}}}'
|
||||
self.process.stdin.write(struct.pack(">I", len(body)) + body)
|
||||
self.process.stdin.flush()
|
||||
expected = json.loads(body, parse_float=Decimal)["payload"]["value"]
|
||||
self.assertEqual(self.receive()["payload"]["out"], expected)
|
||||
self.assertEqual(self.call(2, "floating", dict(value=1.25))["payload"]["out"], Decimal("1.5"))
|
||||
|
||||
def rejected(self, operation, payload, message):
|
||||
self.send(dict(kind="call", id=1, operation=operation, payload=payload))
|
||||
self.assertNotEqual(self.process.wait(timeout=3), 0)
|
||||
self.assertIn(message, self.process.stderr.read().decode())
|
||||
self.assertEqual(self.process.stdout.read(), b"")
|
||||
|
||||
def test_missing_nullable_field_is_rejected(self):
|
||||
self.rejected("echo", dict(value=42, items=[]), "record fields")
|
||||
|
||||
def test_enum_values_roundtrip_in_nullable_fields_and_lists(self):
|
||||
reply = self.call(1, "tool", dict(value="Multiply", maybe="Add", items=["Add", "Multiply"]))
|
||||
self.assertEqual(reply["payload"], {"out": "Multiply"})
|
||||
reply = self.call(2, "tool", dict(value="Add", maybe=None, items=[]))
|
||||
self.assertEqual(reply["payload"], {"out": "Add"})
|
||||
|
||||
def test_unknown_enum_is_rejected_at_boundary(self):
|
||||
self.rejected("tool", dict(value="Divide", maybe=None, items=[]), "unknown enum value")
|
||||
|
||||
def test_integer_type_is_not_guessed(self):
|
||||
self.rejected("echo", dict(value=True, label=None, items=[]), "signed 64-bit")
|
||||
|
||||
def test_output_range_is_rejected(self):
|
||||
self.rejected("invalid", {}, "declared range")
|
||||
|
||||
def test_duplicate_protocol_keys_are_rejected(self):
|
||||
body = b'{"kind":"health","id":0,"id":0}'
|
||||
self.process.stdin.write(struct.pack(">I",len(body)) + body)
|
||||
self.process.stdin.flush()
|
||||
self.assertNotEqual(self.process.wait(timeout=3), 0)
|
||||
self.assertIn("duplicate JSON field", self.process.stderr.read().decode())
|
||||
|
||||
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"os"
|
||||
component "dever/component"
|
||||
)
|
||||
|
||||
//go:embed manifest.json
|
||||
var manifest []byte
|
||||
|
||||
func echo(ctx context.Context, value, setting any) (any, error) {
|
||||
input := value.(map[string]any)
|
||||
return map[string]any{"out":input["value"],"name":input["label"]}, nil
|
||||
}
|
||||
func fail(ctx context.Context, value, setting any) (any, error) {
|
||||
return nil, component.BusinessError{Identity:"demo.service.port.Error.Rejected", Payload:map[string]any{"message":"business rejection"}}
|
||||
}
|
||||
func invalid(ctx context.Context, value, setting any) (any, error) {
|
||||
return map[string]any{"out":int64(200)}, nil
|
||||
}
|
||||
func hang(ctx context.Context, value, setting any) (any, error) {
|
||||
marker := setting.(map[string]any)["marker"].(string)
|
||||
if err := os.WriteFile(marker, nil, 0600); err != nil { return nil, err }
|
||||
<-ctx.Done()
|
||||
return nil, os.WriteFile(marker+".stopped",nil,0600)
|
||||
}
|
||||
func raw(ctx context.Context, value, setting any) (any, error) {
|
||||
return map[string]any{"out":value.(map[string]any)["value"]}, nil
|
||||
}
|
||||
func floating(ctx context.Context, value, setting any) (any, error) {
|
||||
return map[string]any{"out":value.(map[string]any)["value"].(float64)+0.25}, nil
|
||||
}
|
||||
func tool(ctx context.Context, value, setting any) (any, error) {
|
||||
return map[string]any{"out":value.(map[string]any)["value"]}, nil
|
||||
}
|
||||
func main() {
|
||||
worker, err := component.New(manifest,map[string]component.Handler{"echo":echo,"fail":fail,"invalid":invalid,"hang":hang,"raw":raw,"floating":floating,"tool":tool})
|
||||
if err == nil { err = worker.Serve(os.Stdin,os.Stdout) }
|
||||
if err != nil { fmt.Fprintln(os.Stderr,err); os.Exit(1) }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import fs from 'node:fs';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
const { Worker, BusinessError, main } = await import(pathToFileURL(process.argv[3] + '/dever_component.mjs'));
|
||||
|
||||
async function echo(value) { return { out: value.value, name: value.label }; }
|
||||
async function fail() { throw new BusinessError('demo.service.port.Error.Rejected', { message: 'business rejection' }); }
|
||||
async function invalid() { return { out: 200 }; }
|
||||
async function hang(value, setting, signal) {
|
||||
fs.writeFileSync(setting.marker, '');
|
||||
try {
|
||||
await new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));
|
||||
} finally { fs.writeFileSync(setting.marker + '.stopped', ''); }
|
||||
}
|
||||
|
||||
async function raw(value) { return { out: value.value }; }
|
||||
async function floating(value) { return { out: value.value + 0.25 }; }
|
||||
async function tool(value) { return { out: value.value }; }
|
||||
const manifest = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
await main(new Worker(manifest, { echo, fail, hang, invalid, raw, floating, tool }));
|
||||
@@ -0,0 +1,43 @@
|
||||
"""只含业务处理函数;协议和类型验证由 SDK 承担。"""
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, sys.argv[2])
|
||||
from dever_component import BusinessError, Worker, main
|
||||
|
||||
|
||||
async def echo(value, setting):
|
||||
return dict(out=value["value"], name=value["label"])
|
||||
|
||||
|
||||
async def fail(value, setting):
|
||||
raise BusinessError("demo.service.port.Error.Rejected", dict(message="business rejection"))
|
||||
|
||||
|
||||
async def hang(value, setting):
|
||||
marker = pathlib.Path(setting["marker"])
|
||||
marker.touch()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
marker.with_suffix(".stopped").touch()
|
||||
|
||||
|
||||
async def invalid(value, setting):
|
||||
return dict(out=200)
|
||||
|
||||
|
||||
async def raw(value, setting):
|
||||
return dict(out=value["value"])
|
||||
|
||||
async def floating(value, setting):
|
||||
return dict(out=value["value"] + 0.25)
|
||||
|
||||
async def tool(value, setting):
|
||||
return dict(out=value["value"])
|
||||
|
||||
|
||||
manifest = json.loads(pathlib.Path(sys.argv[1]).read_text())
|
||||
main(Worker(manifest, dict(echo=echo, fail=fail, hang=hang, invalid=invalid, raw=raw, floating=floating, tool=tool)))
|
||||
Reference in new issue
Block a user