Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,55 @@
|
||||
# 外部 Worker SDK
|
||||
|
||||
业务多文件与资源通过 external 块的 file 声明逐个选择,路径相对入口文件目录。Go 使用 go:embed;JavaScript/Python 按模块目录读取资源。未声明的业务文件不随程序交付。
|
||||
|
||||
SDK 绑定编译器 inspect --json 输出的 worker_contracts 条目。业务只提供对应 Port 操作的处理函数,不维护协议帧、签名副本或 schema 摘要。external exec 运行已编译的 ELF;external pip/npm/go 经 dever lib install 准备固定官方工具和原生锁,构建时生成入口并嵌入运行资源,详见 [语言说明](../LANGUAGE.md#gojavascript-与-python)。
|
||||
|
||||
| SDK | 处理函数 | 接入 |
|
||||
| --- | --- | --- |
|
||||
| Python | async def add(payload, setting) | main(Worker(manifest, handlers)) |
|
||||
| JavaScript | async function add(payload, setting, signal) | await main(new Worker(manifest, handlers)) |
|
||||
| Go | func Add(context.Context, any, any) (any, error) | New(manifestBytes, handlers),再 Serve(stdin, stdout) |
|
||||
| C/C++ | dever_ffi_handler 的 open/invoke/close | dever_ffi_serve(&handler, manifestBytes) |
|
||||
|
||||
例如 Python 只写:
|
||||
|
||||
~~~python
|
||||
async def add(payload, setting):
|
||||
return {"out": payload["value"] + setting["offset"]}
|
||||
~~~
|
||||
|
||||
结果保留 Port 的输出字段名,包括单输出。Python、JavaScript 和 Go 通过 manifest 在 SDK 边界检查类型,必需字段不能省略,可空字段写 null;Int 保留完整有符号 64 位精度。无载荷普通枚举使用声明名称,SDK 拒绝未知值,支持记录、列表与可空字段中的枚举。业务失败使用 BusinessError(identity, payload),必须是 Port 声明的名义错误。C/C++ 回调输出 JSON,最终具体 Port 类型由 Dever 生成解码器检查。
|
||||
|
||||
处理函数须响应各自的取消机制。Python 接收任务取消,JavaScript 接收 AbortSignal,Go 接收 context.Context;一秒内未退出则 SDK 失败,父进程继续按两秒清理期限回收进程组。C/C++ 同步回调不支持协作取消,超期由父进程终止。stdout 专用于协议,日志使用 stderr。Worker 只隔离进程故障,不是运行不可信代码的沙箱。
|
||||
|
||||
## 依赖与开发验证
|
||||
|
||||
Python 需要 3.11 以上,依赖由 pyproject.toml 声明、uv.lock 锁定;simplejson 保留 Json 数字的精度。JavaScript 需要支持 JSON.rawJSON 的 Node 22 以上;使用 jsonc-parser 的访问接口解析 JSON,decimal.js 比较精确范围,package-lock.json 固定依赖。Go 需要 1.25 以上,直接使用标准库,无第三方运行依赖。
|
||||
|
||||
C SDK 使用 [yyjson 0.12.0](https://github.com/ibireme/yyjson/releases/tag/0.12.0),来源与 SHA-256 固定在 c/dependency.json。把 yyjson.c、c/wire.c 和 c/dever_ffi.c 一起编译,并把 yyjson.h 与 dever_ffi.h 加入头文件搜索路径;不需要 CMake。第三方源码不复制进 SDK。
|
||||
|
||||
所有命令在项目开发容器执行。先准备 Python SDK 依赖,并在 sdk/javascript 执行 npm ci --ignore-scripts。DEVER_SDK_PYTHON 指向安装了 Python SDK 依赖的解释器。执行:
|
||||
|
||||
~~~sh
|
||||
cargo +1.95.0 test --locked --offline --test build port::worker -- --test-threads=1
|
||||
~~~
|
||||
|
||||
提供已经按 dependency.json 校验的 yyjson 源码目录后,单独执行 C/C++ 验证:
|
||||
|
||||
~~~sh
|
||||
YYJSON_ROOT=/path/to/yyjson-0.12.0 cargo +1.95.0 test --locked --offline --test build port::worker::c_and_cpp -- --ignored --test-threads=1
|
||||
~~~
|
||||
|
||||
测试使用编译器的真实合同,执行真实 SDK 子进程;它们不代替解释器、动态库、GPU 环境、跨架构和离线发行验收。原生生态专项使用固定官方工具、真实第三方包、删除入口源码后的产物执行及临时资源清理:
|
||||
|
||||
~~~sh
|
||||
DEVER_HOME=/absolute/cache cargo +1.95.0 test --locked --offline --test build port::native -- --ignored --test-threads=1
|
||||
~~~
|
||||
|
||||
该专项内部的显式 lib install 可以联网;Cargo 自身保持离线。首次执行会准备官方工具和包,后续恢复原生锁。跨架构和真实 GPU 运算须在对应环境验证。
|
||||
|
||||
## C ABI
|
||||
|
||||
ABI 为 DEVER_FFI_ABI_V1。manifest、operation、setting 和 payload 都是调用期间借用的字节,不保证 NUL 结尾,回调不能保留它们的地址。open 成功后 close 调用一次;invoke 串行执行。
|
||||
|
||||
输出缓冲由 SDK 分配。回调只写 capacity 以内的数据并设置 size,不能替换或释放指针。DEVER_FFI_OK 返回输出记录的 JSON;DEVER_FFI_ERROR 返回含 error 和 payload 的对象;DEVER_FFI_FAULT 使会话失败。C++ 异常不得跨 C ABI。
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "yyjson",
|
||||
"version": "0.12.0",
|
||||
"url": "https://github.com/ibireme/yyjson/archive/refs/tags/0.12.0.tar.gz",
|
||||
"sha256": "b16246f617b2a136c78d73e5e2647c6f1de1313e46678062985bdcf1f40bb75d",
|
||||
"license": "MIT"
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/* 同步 C ABI;取消由 Dever 进程监管设定宽限,SDK 不新增线程调度。 */
|
||||
#include "wire.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int text(yyjson_val *value, const char *expected) {
|
||||
return yyjson_is_str(value) && yyjson_get_len(value) == strlen(expected) && memcmp(yyjson_get_str(value), expected, strlen(expected)) == 0;
|
||||
}
|
||||
static int identifier(yyjson_val *message, uint64_t *id) {
|
||||
yyjson_val *value = yyjson_obj_get(message, "id");
|
||||
if (!yyjson_is_uint(value) || yyjson_get_uint(value) > INT64_MAX) return 0;
|
||||
*id = yyjson_get_uint(value);
|
||||
return 1;
|
||||
}
|
||||
static int declared(yyjson_val *operations, yyjson_val *operation) {
|
||||
size_t i, length; yyjson_val *item;
|
||||
yyjson_arr_foreach(operations, i, length, item) if (yyjson_equals(item, operation)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int handshake(const dever_ffi_handler *handler, yyjson_val *contract, int *opened) {
|
||||
yyjson_doc *doc = dever_receive();
|
||||
if (doc == NULL) return 0;
|
||||
yyjson_val *hello = yyjson_doc_get_root(doc);
|
||||
int okay = yyjson_obj_size(hello) == 8 && text(yyjson_obj_get(hello, "kind"), "hello") && text(yyjson_obj_get(hello, "version"), "dever-component-1");
|
||||
const char *identity[] = {"port", "schema", "adapter", "operations", "capabilities"};
|
||||
for (size_t i = 0; okay && i < 5; ++i) okay = yyjson_equals(yyjson_obj_get(hello, identity[i]), yyjson_obj_get(contract, identity[i]));
|
||||
yyjson_val *setting = yyjson_obj_get(hello, "setting");
|
||||
if (okay) okay = setting != NULL;
|
||||
if (okay && handler->open != NULL) {
|
||||
size_t size; char *data = yyjson_val_write(setting, 0, &size);
|
||||
okay = data != NULL && handler->open(handler->context, (dever_ffi_slice){data, size}) == DEVER_FFI_OK;
|
||||
free(data);
|
||||
}
|
||||
if (okay) {
|
||||
*opened = 1;
|
||||
yyjson_mut_doc *ready = yyjson_doc_mut_copy(doc, NULL);
|
||||
if (ready == NULL) okay = 0;
|
||||
else {
|
||||
yyjson_mut_val *root = yyjson_mut_doc_get_root(ready);
|
||||
yyjson_mut_obj_remove_key(root, "setting");
|
||||
yyjson_mut_obj_remove_key(root, "kind");
|
||||
okay = yyjson_mut_obj_add_str(ready, root, "kind", "ready") && dever_send(ready);
|
||||
yyjson_mut_doc_free(ready);
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(doc);
|
||||
return okay;
|
||||
}
|
||||
|
||||
static int invoke(const dever_ffi_handler *handler, yyjson_val *contract, yyjson_val *message, uint64_t id, char *buffer) {
|
||||
yyjson_val *operation = yyjson_obj_get(message, "operation");
|
||||
yyjson_val *payload = yyjson_obj_get(message, "payload");
|
||||
if (payload == NULL || !yyjson_is_str(operation) || !declared(yyjson_obj_get(contract, "operations"), operation)) return 0;
|
||||
size_t size; char *data = yyjson_val_write(payload, 0, &size);
|
||||
if (data == NULL) return 0;
|
||||
dever_ffi_output returned = {buffer, DEVER_MAX_BYTES - 256, 0};
|
||||
int status = handler->invoke(handler->context, (dever_ffi_slice){yyjson_get_str(operation), yyjson_get_len(operation)}, (dever_ffi_slice){data, size}, &returned);
|
||||
free(data);
|
||||
if (returned.data != buffer || returned.capacity != DEVER_MAX_BYTES - 256 || returned.size > returned.capacity || (status != DEVER_FFI_OK && status != DEVER_FFI_ERROR)) return 0;
|
||||
yyjson_doc *result = dever_parse(buffer, (size_t)returned.size, status == DEVER_FFI_OK ? 3 : 2, status == DEVER_FFI_OK ? 1 : 0);
|
||||
if (result == NULL) return 0;
|
||||
yyjson_val *value = yyjson_doc_get_root(result);
|
||||
yyjson_val *error = NULL;
|
||||
int okay = 1;
|
||||
if (status == DEVER_FFI_ERROR) {
|
||||
error = yyjson_obj_get(value, "error");
|
||||
payload = yyjson_obj_get(value, "payload");
|
||||
okay = yyjson_obj_size(value) == 2 && yyjson_is_str(error) && payload != NULL && yyjson_obj_getn(yyjson_obj_get(contract, "errors"), yyjson_get_str(error), yyjson_get_len(error)) != NULL;
|
||||
} else payload = value;
|
||||
yyjson_mut_doc *reply = yyjson_mut_doc_new(NULL);
|
||||
if (reply == NULL) okay = 0;
|
||||
if (okay) {
|
||||
yyjson_mut_val *root = yyjson_mut_obj(reply);
|
||||
yyjson_mut_doc_set_root(reply, root);
|
||||
okay = root != NULL && yyjson_mut_obj_add_str(reply,root,"kind",error ? "error" : "result") && yyjson_mut_obj_add_uint(reply,root,"id",id) && yyjson_mut_obj_add_val(reply,root,"payload",yyjson_val_mut_copy(reply,payload));
|
||||
if (okay && error) okay = yyjson_mut_obj_add_val(reply,root,"error",yyjson_val_mut_copy(reply,error));
|
||||
// callback 解析已经包含外层帧头预算,此处直接编码,不重扫载荷。
|
||||
if (okay) okay = dever_send(reply);
|
||||
}
|
||||
yyjson_mut_doc_free(reply); yyjson_doc_free(result);
|
||||
return okay;
|
||||
}
|
||||
|
||||
int dever_ffi_serve(const dever_ffi_handler *handler, dever_ffi_slice manifest) {
|
||||
if (handler == NULL || handler->abi != DEVER_FFI_ABI_V1 || handler->invoke == NULL) return 1;
|
||||
yyjson_doc *contract = dever_parse(manifest.data, (size_t)manifest.size, 0, 0);
|
||||
if (contract == NULL) return 1;
|
||||
int opened = 0;
|
||||
int okay = handshake(handler, yyjson_doc_get_root(contract), &opened);
|
||||
char *buffer = okay ? malloc(DEVER_MAX_BYTES - 256) : NULL;
|
||||
okay = okay && buffer != NULL;
|
||||
uint64_t next = 1;
|
||||
int cancelled = 0, stopped = 0;
|
||||
while (okay && !stopped) {
|
||||
yyjson_doc *doc = dever_receive();
|
||||
if (doc == NULL) { okay = 0; break; }
|
||||
yyjson_val *message = yyjson_doc_get_root(doc), *kind = yyjson_obj_get(message,"kind");
|
||||
uint64_t id;
|
||||
if (text(kind,"shutdown")) {
|
||||
okay = yyjson_obj_size(message) == 1 && dever_send_value(message);
|
||||
stopped = 1;
|
||||
} else if (text(kind,"health")) {
|
||||
okay = yyjson_obj_size(message) == 2 && identifier(message,&id) && id == 0 && dever_send_value(message);
|
||||
} else if (text(kind,"cancel")) {
|
||||
okay = yyjson_obj_size(message) == 2 && identifier(message,&id) && id > 0 && id == next-1 && !cancelled;
|
||||
cancelled = 1;
|
||||
} else if (text(kind,"call")) {
|
||||
okay = yyjson_obj_size(message) == 4 && identifier(message,&id) && id == next && invoke(handler,yyjson_doc_get_root(contract),message,id,buffer);
|
||||
++next; cancelled = 0;
|
||||
} else okay = 0;
|
||||
yyjson_doc_free(doc);
|
||||
}
|
||||
if (opened && handler->close != NULL) handler->close(handler->context);
|
||||
free(buffer); yyjson_doc_free(contract);
|
||||
if (!okay) fputs("native FFI Worker protocol or callback failed\n",stderr);
|
||||
return okay && stopped ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef DEVER_FFI_H
|
||||
#define DEVER_FFI_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define DEVER_FFI_ABI_V1 1
|
||||
#define DEVER_FFI_OK 0
|
||||
#define DEVER_FFI_ERROR 1
|
||||
#define DEVER_FFI_FAULT 2
|
||||
|
||||
typedef struct {
|
||||
const char *data;
|
||||
uint64_t size;
|
||||
} dever_ffi_slice;
|
||||
|
||||
typedef struct {
|
||||
char *data;
|
||||
uint64_t capacity;
|
||||
uint64_t size;
|
||||
} dever_ffi_output;
|
||||
|
||||
typedef struct {
|
||||
uint32_t abi;
|
||||
void *context;
|
||||
int (*open)(void *context, dever_ffi_slice setting);
|
||||
int (*invoke)(void *context, dever_ffi_slice operation, dever_ffi_slice payload, dever_ffi_output *output);
|
||||
void (*close)(void *context);
|
||||
} dever_ffi_handler;
|
||||
|
||||
/* contract 是编译器导出的 manifest,调用期间借用;不读取工作目录或环境。 */
|
||||
int dever_ffi_serve(const dever_ffi_handler *handler, dever_ffi_slice contract);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
/* yyjson 完成 JSON 解析与编码;本层只执行 Dever 帧与结构预算。 */
|
||||
#include "wire.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int key_order(const void *left, const void *right) {
|
||||
yyjson_val *a = *(yyjson_val *const *)left, *b = *(yyjson_val *const *)right;
|
||||
size_t an = yyjson_get_len(a), bn = yyjson_get_len(b);
|
||||
int compare = memcmp(yyjson_get_str(a), yyjson_get_str(b), an < bn ? an : bn);
|
||||
return compare != 0 ? compare : (an > bn) - (an < bn);
|
||||
}
|
||||
|
||||
static int bounded(yyjson_val *value, unsigned depth, size_t *remaining) {
|
||||
if (depth > 64 || *remaining == 0) return 0;
|
||||
--*remaining;
|
||||
if (yyjson_is_ctn(value) && depth == 64) return 0;
|
||||
if (yyjson_is_arr(value)) {
|
||||
size_t i, length; yyjson_val *item;
|
||||
yyjson_arr_foreach(value, i, length, item) if (!bounded(item, depth + 1, remaining)) return 0;
|
||||
} else if (yyjson_is_obj(value)) {
|
||||
size_t length = yyjson_obj_size(value);
|
||||
if (length > *remaining) return 0;
|
||||
yyjson_val **keys = length ? malloc(length * sizeof(*keys)) : NULL;
|
||||
if (length && keys == NULL) return 0;
|
||||
size_t i, count; yyjson_val *key, *item;
|
||||
int okay = 1;
|
||||
yyjson_obj_foreach(value, i, count, key, item) {
|
||||
keys[i] = key;
|
||||
if (!bounded(item, depth + 1, remaining)) { okay = 0; break; }
|
||||
}
|
||||
if (okay && length > 1) {
|
||||
qsort(keys, length, sizeof(*keys), key_order);
|
||||
for (i = 1; i < length; ++i) if (key_order(&keys[i-1], &keys[i]) == 0) { okay = 0; break; }
|
||||
}
|
||||
free(keys);
|
||||
return okay;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
yyjson_doc *dever_parse(const char *data, size_t size, size_t extra_values, unsigned depth) {
|
||||
if (size == 0 || size > DEVER_MAX_BYTES) return NULL;
|
||||
yyjson_doc *doc = yyjson_read(data, size, YYJSON_READ_BIGNUM_AS_RAW);
|
||||
if (doc == NULL) return NULL;
|
||||
size_t remaining = 65536 - extra_values;
|
||||
if (!bounded(yyjson_doc_get_root(doc), depth, &remaining)) { yyjson_doc_free(doc); return NULL; }
|
||||
return doc;
|
||||
}
|
||||
|
||||
yyjson_doc *dever_receive(void) {
|
||||
unsigned char header[4];
|
||||
if (fread(header, 1, 4, stdin) != 4) return NULL;
|
||||
size_t size = ((uint32_t)header[0] << 24) | ((uint32_t)header[1] << 16) | ((uint32_t)header[2] << 8) | header[3];
|
||||
if (size == 0 || size > DEVER_MAX_BYTES) return NULL;
|
||||
char *data = malloc(size);
|
||||
if (data == NULL) return NULL;
|
||||
yyjson_doc *doc = fread(data, 1, size, stdin) == size ? dever_parse(data, size, 0, 0) : NULL;
|
||||
free(data);
|
||||
return doc;
|
||||
}
|
||||
|
||||
static int send_bytes(char *data, size_t size) {
|
||||
if (data == NULL || size == 0 || size > DEVER_MAX_BYTES) { free(data); return 0; }
|
||||
unsigned char header[4] = {size >> 24, size >> 16, size >> 8, size};
|
||||
int okay = fwrite(header, 1, 4, stdout) == 4 && fwrite(data, 1, size, stdout) == size && fflush(stdout) == 0;
|
||||
free(data);
|
||||
return okay;
|
||||
}
|
||||
int dever_send(yyjson_mut_doc *doc) {
|
||||
size_t size; char *data = yyjson_mut_write(doc, 0, &size);
|
||||
return send_bytes(data, size);
|
||||
}
|
||||
int dever_send_value(yyjson_val *value) {
|
||||
size_t size; char *data = yyjson_val_write(value, 0, &size);
|
||||
return send_bytes(data, size);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#ifndef DEVER_WIRE_H
|
||||
#define DEVER_WIRE_H
|
||||
#include <yyjson.h>
|
||||
#include "dever_ffi.h"
|
||||
#define DEVER_MAX_BYTES (16U * 1024U * 1024U)
|
||||
yyjson_doc *dever_parse(const char *data, size_t size, size_t extra_values, unsigned depth);
|
||||
yyjson_doc *dever_receive(void);
|
||||
int dever_send(yyjson_mut_doc *doc);
|
||||
int dever_send_value(yyjson_val *value);
|
||||
#endif
|
||||
@@ -0,0 +1,252 @@
|
||||
// Package component 直接绑定编译器 manifest 与处理函数,不要求业务编写协议。
|
||||
package component
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const Version = "dever-component-1"
|
||||
|
||||
type BusinessError struct {
|
||||
Identity string
|
||||
Payload any
|
||||
}
|
||||
|
||||
func (e BusinessError) Error() string { return e.Identity }
|
||||
|
||||
type Handler func(context.Context, any, any) (any, error)
|
||||
type Worker struct {
|
||||
manifest Manifest
|
||||
handlers map[string]Handler
|
||||
}
|
||||
|
||||
func New(manifest []byte, handlers map[string]Handler) (*Worker, error) {
|
||||
var contract Manifest
|
||||
if err := json.Unmarshal(manifest, &contract); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(handlers) != len(contract.Operations) {
|
||||
return nil, errors.New("handlers must cover the checked Port exactly")
|
||||
}
|
||||
for _, operation := range contract.Operations {
|
||||
if handlers[operation] == nil {
|
||||
return nil, errors.New("missing Worker handler")
|
||||
}
|
||||
}
|
||||
return &Worker{contract, handlers}, nil
|
||||
}
|
||||
|
||||
type frame struct {
|
||||
value map[string]any
|
||||
err error
|
||||
}
|
||||
type result struct {
|
||||
value any
|
||||
err error
|
||||
}
|
||||
type invocation struct {
|
||||
id int64
|
||||
operation string
|
||||
cancel context.CancelFunc
|
||||
done chan result
|
||||
}
|
||||
|
||||
func (call *invocation) stop() error {
|
||||
call.cancel()
|
||||
timer := time.NewTimer(time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-call.done:
|
||||
return nil
|
||||
case <-timer.C:
|
||||
return errors.New("handler did not stop after cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
// Serve 使用由 Go 轮询器管理的独立管道句柄;关闭它可解除真实读取阻塞。
|
||||
func (w *Worker) Serve(input *os.File, output io.Writer) (failure error) {
|
||||
pipe, err := os.OpenFile(fmt.Sprintf("/proc/self/fd/%d", input.Fd()), os.O_RDONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messages := make(chan frame)
|
||||
stopped := make(chan struct{})
|
||||
readerDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(readerDone)
|
||||
for {
|
||||
value, err := readFrame(pipe)
|
||||
select {
|
||||
case messages <- frame{value, err}:
|
||||
case <-stopped:
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stopped)
|
||||
failure = errors.Join(failure, pipe.Close())
|
||||
<-readerDone
|
||||
}()
|
||||
hello := <-messages
|
||||
if hello.err != nil {
|
||||
return hello.err
|
||||
}
|
||||
setting, err := w.handshake(hello.value, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var active *invocation
|
||||
defer func() {
|
||||
if active != nil {
|
||||
failure = errors.Join(failure, active.stop())
|
||||
}
|
||||
}()
|
||||
next := int64(1)
|
||||
cancelled := false
|
||||
for {
|
||||
var completed <-chan result
|
||||
if active != nil {
|
||||
completed = active.done
|
||||
}
|
||||
select {
|
||||
case reply := <-completed:
|
||||
call := active
|
||||
active = nil
|
||||
call.cancel()
|
||||
cancelled = false
|
||||
message := map[string]any{"kind": "result", "id": call.id}
|
||||
schema := w.manifest.Outputs[call.operation]
|
||||
value := reply.value
|
||||
if reply.err != nil {
|
||||
var business BusinessError
|
||||
if !errors.As(reply.err, &business) {
|
||||
return reply.err
|
||||
}
|
||||
declared, ok := w.manifest.Errors[business.Identity]
|
||||
if !ok {
|
||||
return errors.New("undeclared business error")
|
||||
}
|
||||
schema, value = declared, business.Payload
|
||||
message["kind"], message["error"] = "error", business.Identity
|
||||
}
|
||||
message["payload"], err = decodeTyped(value, schema)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFrame(output, message); err != nil {
|
||||
return err
|
||||
}
|
||||
case received := <-messages:
|
||||
if received.err != nil {
|
||||
return received.err
|
||||
}
|
||||
message := received.value
|
||||
switch message["kind"] {
|
||||
case "health":
|
||||
if !exact(message, "kind", "id") || requestID(message["id"]) != 0 {
|
||||
return errors.New("invalid health")
|
||||
}
|
||||
if err := writeFrame(output, message); err != nil {
|
||||
return err
|
||||
}
|
||||
case "call":
|
||||
if !exact(message, "kind", "id", "operation", "payload") {
|
||||
return errors.New("invalid call")
|
||||
}
|
||||
id := requestID(message["id"])
|
||||
operation, ok := message["operation"].(string)
|
||||
if !ok || id != next || active != nil || w.handlers[operation] == nil {
|
||||
return errors.New("invalid call")
|
||||
}
|
||||
payload, err := decodeTyped(message["payload"], w.manifest.Inputs[operation])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next++
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan result, 1)
|
||||
active = &invocation{id, operation, cancel, done}
|
||||
go func() { value, err := w.handlers[operation](ctx, payload, setting); done <- result{value, err} }()
|
||||
case "cancel":
|
||||
if !exact(message, "kind", "id") {
|
||||
return errors.New("invalid cancel")
|
||||
}
|
||||
id := requestID(message["id"])
|
||||
if id <= 0 {
|
||||
return errors.New("invalid cancel")
|
||||
}
|
||||
if active != nil && active.id == id {
|
||||
call := active
|
||||
active = nil
|
||||
if err := call.stop(); err != nil {
|
||||
return err
|
||||
}
|
||||
cancelled = true
|
||||
if err := writeFrame(output, map[string]any{"kind": "error", "id": id, "error": "dever.cancelled", "payload": nil}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if id != next-1 || cancelled {
|
||||
return errors.New("unknown cancel id")
|
||||
}
|
||||
case "shutdown":
|
||||
if !exact(message, "kind") {
|
||||
return errors.New("invalid shutdown")
|
||||
}
|
||||
if active != nil {
|
||||
call := active
|
||||
active = nil
|
||||
if err := call.stop(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return writeFrame(output, map[string]any{"kind": "shutdown"})
|
||||
default:
|
||||
return errors.New("unknown protocol message")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) handshake(hello map[string]any, output io.Writer) (any, error) {
|
||||
contract := w.manifest
|
||||
if !exact(hello, "kind", "version", "port", "schema", "adapter", "capabilities", "operations", "setting") || hello["kind"] != "hello" || hello["version"] != Version || hello["port"] != contract.Port || hello["schema"] != contract.Schema || hello["adapter"] != contract.Adapter || !sameNames(hello["capabilities"], contract.Capabilities) || !sameNames(hello["operations"], contract.Operations) {
|
||||
return nil, errors.New("handshake differs from the checked Port")
|
||||
}
|
||||
setting := hello["setting"]
|
||||
if contract.Setting != nil {
|
||||
var err error
|
||||
setting, err = decodeTyped(setting, *contract.Setting)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if setting != nil {
|
||||
return nil, errors.New("unexpected setting")
|
||||
}
|
||||
delete(hello, "setting")
|
||||
hello["kind"] = "ready"
|
||||
return setting, writeFrame(output, hello)
|
||||
}
|
||||
|
||||
func sameNames(raw any, expected []string) bool {
|
||||
values, ok := raw.([]any)
|
||||
if !ok || len(values) != len(expected) {
|
||||
return false
|
||||
}
|
||||
for i, value := range values {
|
||||
if value != expected[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module dever/component
|
||||
|
||||
go 1.25.0
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// 字段合同来自编译器;边界转换后直接交付具体 Go 值,不复制整份记录。
|
||||
package component
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"regexp"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
decimalPattern = regexp.MustCompile(`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)
|
||||
uuidPattern = regexp.MustCompile(`(?i)^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$`)
|
||||
timePattern = regexp.MustCompile(`^[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{3})?$`)
|
||||
datetimePattern = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,3})?(?:Z|[+-][0-9]{2}:[0-9]{2})$`)
|
||||
)
|
||||
|
||||
type TypeSchema struct {
|
||||
Type string `json:"type"`
|
||||
Minimum string `json:"minimum,omitempty"`
|
||||
Maximum string `json:"maximum,omitempty"`
|
||||
Value *TypeSchema `json:"value,omitempty"`
|
||||
Fields map[string]TypeSchema `json:"fields,omitempty"`
|
||||
Values []string `json:"values,omitempty"`
|
||||
}
|
||||
|
||||
type Manifest struct {
|
||||
Port string `json:"port"`
|
||||
Schema string `json:"schema"`
|
||||
Adapter string `json:"adapter"`
|
||||
Operations []string `json:"operations"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Setting *TypeSchema `json:"setting"`
|
||||
Inputs map[string]TypeSchema `json:"inputs"`
|
||||
Outputs map[string]TypeSchema `json:"outputs"`
|
||||
Errors map[string]TypeSchema `json:"errors"`
|
||||
}
|
||||
|
||||
func decodeTyped(value any, schema TypeSchema) (any, error) {
|
||||
result, err := decodeValue(value, schema)
|
||||
if err != nil || result == nil || schema.Minimum == "" {
|
||||
return result, err
|
||||
}
|
||||
number, valid := new(big.Rat).SetString(fmt.Sprint(result))
|
||||
if !valid {
|
||||
return nil, errors.New("invalid numeric range value")
|
||||
}
|
||||
minimum, _ := new(big.Rat).SetString(schema.Minimum)
|
||||
maximum, _ := new(big.Rat).SetString(schema.Maximum)
|
||||
if number.Cmp(minimum) < 0 || number.Cmp(maximum) > 0 {
|
||||
return nil, errors.New("value is outside its declared range")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func decodeValue(value any, schema TypeSchema) (any, error) {
|
||||
switch schema.Type {
|
||||
case "enum":
|
||||
name, ok := value.(string)
|
||||
if !ok || !slices.Contains(schema.Values, name) {
|
||||
return nil, errors.New("unknown enum value")
|
||||
}
|
||||
return name, nil
|
||||
case "nullable":
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return decodeTyped(value, *schema.Value)
|
||||
case "list":
|
||||
values, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, errors.New("expected list")
|
||||
}
|
||||
result := values
|
||||
for index, item := range values {
|
||||
decoded, err := decodeTyped(item, *schema.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[index] = decoded
|
||||
}
|
||||
return result, nil
|
||||
case "record":
|
||||
object, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("expected record")
|
||||
}
|
||||
for name := range object {
|
||||
if _, ok := schema.Fields[name]; !ok {
|
||||
return nil, errors.New("unknown record fields")
|
||||
}
|
||||
}
|
||||
result := object
|
||||
for name, field := range schema.Fields {
|
||||
entry, exists := object[name]
|
||||
if !exists {
|
||||
return nil, errors.New("missing record fields")
|
||||
}
|
||||
decoded, err := decodeTyped(entry, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[name] = decoded
|
||||
}
|
||||
return result, nil
|
||||
case "int64", "duration", "model_id":
|
||||
switch number := value.(type) {
|
||||
case json.Number:
|
||||
if parsed, err := number.Int64(); err == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
case int64:
|
||||
return number, nil
|
||||
case int:
|
||||
return int64(number), nil
|
||||
}
|
||||
return nil, errors.New("expected signed 64-bit integer")
|
||||
case "float64":
|
||||
switch number := value.(type) {
|
||||
case json.Number:
|
||||
parsed, err := number.Float64()
|
||||
if err == nil && !math.IsInf(parsed, 0) && !math.IsNaN(parsed) {
|
||||
return parsed, nil
|
||||
}
|
||||
case float64:
|
||||
if !math.IsInf(number, 0) && !math.IsNaN(number) {
|
||||
return number, nil
|
||||
}
|
||||
}
|
||||
case "bool":
|
||||
if boolean, ok := value.(bool); ok {
|
||||
return boolean, nil
|
||||
}
|
||||
case "json":
|
||||
return value, nil
|
||||
case "text", "id", "secret", "decimal", "uuid", "datetime", "date", "time":
|
||||
if text, ok := value.(string); ok {
|
||||
switch schema.Type {
|
||||
case "decimal":
|
||||
if !decimalPattern.MatchString(text) {
|
||||
return nil, errors.New("invalid decimal")
|
||||
}
|
||||
case "uuid":
|
||||
if !uuidPattern.MatchString(text) {
|
||||
return nil, errors.New("invalid UUID")
|
||||
}
|
||||
case "date":
|
||||
if _, err := time.Parse("2006-01-02", text); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "time":
|
||||
if !timePattern.MatchString(text) {
|
||||
return nil, errors.New("invalid Time")
|
||||
}
|
||||
layout := "15:04:05"
|
||||
if len(text) == 12 {
|
||||
layout = "15:04:05.000"
|
||||
}
|
||||
if _, err := time.Parse(layout, text); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "datetime":
|
||||
if !datetimePattern.MatchString(text) {
|
||||
return nil, errors.New("invalid DateTime")
|
||||
}
|
||||
parsed, err := time.Parse(time.RFC3339Nano, text)
|
||||
if err != nil || parsed.Nanosecond()%1_000_000 != 0 {
|
||||
return nil, errors.New("invalid DateTime")
|
||||
}
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid typed Worker value")
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
// 协议帧与 JSON 语法复用标准库;遍历只增加重复键、深度和值数限制。
|
||||
package component
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
maxBytes = 16 * 1024 * 1024
|
||||
maxDepth = 64
|
||||
maxElements = 65536
|
||||
)
|
||||
|
||||
func exact(message map[string]any, names ...string) bool {
|
||||
if len(message) != len(names) {
|
||||
return false
|
||||
}
|
||||
for _, name := range names {
|
||||
if _, ok := message[name]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func requestID(value any) int64 {
|
||||
number, ok := value.(json.Number)
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
id, err := number.Int64()
|
||||
if err != nil || id < 0 {
|
||||
return -1
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func readFrame(input io.Reader) (map[string]any, error) {
|
||||
var header [4]byte
|
||||
if _, err := io.ReadFull(input, header[:]); err != nil {
|
||||
return nil, errors.New("incomplete component frame")
|
||||
}
|
||||
size := binary.BigEndian.Uint32(header[:])
|
||||
if size == 0 || size > maxBytes {
|
||||
return nil, errors.New("component frame exceeds byte limit")
|
||||
}
|
||||
body := make([]byte, size)
|
||||
if _, err := io.ReadFull(input, body); err != nil {
|
||||
return nil, errors.New("incomplete component frame")
|
||||
}
|
||||
return parseJSON(body)
|
||||
}
|
||||
|
||||
func writeFrame(output io.Writer, message map[string]any) error {
|
||||
body, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid handler response: %w", err)
|
||||
}
|
||||
if len(body) == 0 || len(body) > maxBytes {
|
||||
return errors.New("component frame exceeds byte limit")
|
||||
}
|
||||
if _, err := parseJSON(body); err != nil {
|
||||
return err
|
||||
}
|
||||
var header [4]byte
|
||||
binary.BigEndian.PutUint32(header[:], uint32(len(body)))
|
||||
if err := writeAll(output, header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeAll(output, body)
|
||||
}
|
||||
|
||||
func writeAll(output io.Writer, data []byte) error {
|
||||
_, err := io.Copy(output, bytes.NewReader(data))
|
||||
return err
|
||||
}
|
||||
|
||||
func parseJSON(body []byte) (map[string]any, error) {
|
||||
if !utf8.Valid(body) {
|
||||
return nil, errors.New("component frame is not UTF-8")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.UseNumber()
|
||||
remaining := maxElements
|
||||
value, err := parseValue(decoder, 0, &remaining)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := decoder.Token(); err != io.EOF {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
object, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("component message must be an object")
|
||||
}
|
||||
return object, nil
|
||||
}
|
||||
|
||||
func parseValue(decoder *json.Decoder, depth int, remaining *int) (any, error) {
|
||||
if depth > maxDepth || *remaining <= 0 {
|
||||
return nil, errors.New("wire JSON exceeds limit")
|
||||
}
|
||||
*remaining--
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
delim, ok := token.(json.Delim)
|
||||
if !ok {
|
||||
return token, nil
|
||||
}
|
||||
if depth == maxDepth {
|
||||
return nil, errors.New("wire JSON exceeds depth limit")
|
||||
}
|
||||
switch delim {
|
||||
case '{':
|
||||
object := make(map[string]any)
|
||||
for decoder.More() {
|
||||
key, err := decoder.Token()
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
name, ok := key.(string)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
if _, exists := object[name]; exists {
|
||||
return nil, errors.New("duplicate JSON field")
|
||||
}
|
||||
value, err := parseValue(decoder, depth+1, remaining)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
object[name] = value
|
||||
}
|
||||
if end, err := decoder.Token(); err != nil || end != json.Delim('}') {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
return object, nil
|
||||
case '[':
|
||||
array := make([]any, 0)
|
||||
for decoder.More() {
|
||||
value, err := parseValue(decoder, depth+1, remaining)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
array = append(array, value)
|
||||
}
|
||||
if end, err := decoder.Token(); err != nil || end != json.Delim(']') {
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
return array, nil
|
||||
default:
|
||||
return nil, errors.New("invalid component JSON")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Channel, ProtocolError, exact } from './wire.mjs';
|
||||
import { typed } from './types.mjs';
|
||||
|
||||
export class BusinessError extends Error {
|
||||
constructor(identity, payload) {
|
||||
super(identity);
|
||||
this.identity = identity;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
async function stop(active) {
|
||||
active.controller.abort();
|
||||
let timer;
|
||||
try {
|
||||
await Promise.race([
|
||||
active.done,
|
||||
new Promise((_, reject) => { timer = setTimeout(() => reject(new ProtocolError('handler did not stop after cancellation')), 1000); }),
|
||||
]);
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
|
||||
export class Worker {
|
||||
constructor(manifest, handlers) {
|
||||
exact(handlers, manifest.operations);
|
||||
if (Object.values(handlers).some(handler => typeof handler !== 'function')) throw new TypeError('expected Worker handlers');
|
||||
this.manifest = manifest;
|
||||
this.handlers = handlers;
|
||||
}
|
||||
|
||||
async serve() {
|
||||
const channel = new Channel();
|
||||
try { await this.#serve(channel); }
|
||||
finally { channel.close(); }
|
||||
}
|
||||
|
||||
async #serve(channel) {
|
||||
const manifest = this.manifest;
|
||||
const hello = await channel.receive();
|
||||
exact(hello, ['kind', 'version', 'port', 'schema', 'adapter', 'operations', 'capabilities', 'setting']);
|
||||
const identity = Object.fromEntries(['port', 'schema', 'adapter', 'operations', 'capabilities'].map(name => [name, manifest[name]]));
|
||||
if (hello.kind !== 'hello' || hello.version !== 'dever-component-1' || Object.entries(identity).some(([name, value]) => JSON.stringify(hello[name]) !== JSON.stringify(value))) throw new ProtocolError('handshake differs from the checked Port');
|
||||
const setting = hello.setting;
|
||||
if (manifest.setting !== null) typed(setting, manifest.setting);
|
||||
else if (setting !== null) throw new ProtocolError('unexpected setting');
|
||||
await channel.send({ ...identity, kind: 'ready', version: 'dever-component-1' });
|
||||
// 只保留一个管道读取和一个当前 handler,不另建消息队列或调度器。
|
||||
const read = () => channel.receive().then(frame => ({ frame }), fault => ({ fault }));
|
||||
let pending = read();
|
||||
let active = null;
|
||||
let next = 1;
|
||||
let cancelled = false;
|
||||
try {
|
||||
for (;;) {
|
||||
const event = await (active ? Promise.race([pending, active.done]) : pending);
|
||||
if (event.fault) throw event.fault;
|
||||
if (Object.hasOwn(event, 'done')) {
|
||||
const { id, operation } = active;
|
||||
active = null;
|
||||
cancelled = false;
|
||||
if (Object.hasOwn(event, 'error')) {
|
||||
const error = event.error;
|
||||
if (!(error instanceof BusinessError)) throw error;
|
||||
if (!Object.hasOwn(manifest.errors, error.identity)) throw new ProtocolError('undeclared business error');
|
||||
typed(error.payload, manifest.errors[error.identity]);
|
||||
await channel.send({ kind: 'error', id, error: error.identity, payload: error.payload });
|
||||
} else {
|
||||
typed(event.done, manifest.outputs[operation]);
|
||||
await channel.send({ kind: 'result', id, payload: event.done });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const message = event.frame;
|
||||
switch (message.kind) {
|
||||
case 'health':
|
||||
exact(message, ['kind', 'id']);
|
||||
if (message.id !== 0) throw new ProtocolError('invalid health id');
|
||||
await channel.send(message);
|
||||
break;
|
||||
case 'call': {
|
||||
exact(message, ['kind', 'id', 'operation', 'payload']);
|
||||
if (message.id !== next || active || !Object.hasOwn(this.handlers, message.operation)) throw new ProtocolError('invalid call');
|
||||
next++;
|
||||
const operation = message.operation;
|
||||
typed(message.payload, manifest.inputs[operation]);
|
||||
const controller = new AbortController();
|
||||
const done = Promise.resolve().then(() => this.handlers[operation](message.payload, setting, controller.signal)).then(done => ({ done }), error => ({ done: null, error }));
|
||||
active = { id: message.id, operation, controller, done };
|
||||
break;
|
||||
}
|
||||
case 'cancel':
|
||||
exact(message, ['kind', 'id']);
|
||||
if (active && active.id === message.id) {
|
||||
const previous = active;
|
||||
active = null;
|
||||
await stop(previous);
|
||||
cancelled = true;
|
||||
await channel.send({ kind: 'error', id: message.id, error: 'dever.cancelled', payload: null });
|
||||
} else if (!Number.isSafeInteger(message.id) || message.id === 0 || message.id !== next - 1 || cancelled) throw new ProtocolError('unknown cancel id');
|
||||
break;
|
||||
case 'shutdown':
|
||||
exact(message, ['kind']);
|
||||
if (active) { const previous = active; active = null; await stop(previous); }
|
||||
await channel.send({ kind: 'shutdown' });
|
||||
return;
|
||||
default: throw new ProtocolError('unknown protocol message');
|
||||
}
|
||||
pending = read();
|
||||
}
|
||||
} finally { if (active) await stop(active); }
|
||||
}
|
||||
}
|
||||
|
||||
export async function main(worker) {
|
||||
try { await worker.serve(); }
|
||||
catch (error) { console.error(error); process.exitCode = 1; }
|
||||
}
|
||||
Generated
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"dependencies": {
|
||||
"decimal.js": "10.6.0",
|
||||
"jsonc-parser": "3.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.6.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsonc-parser": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz",
|
||||
"integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": "./dever_component.mjs",
|
||||
"dependencies": {"jsonc-parser": "3.3.1", "decimal.js": "10.6.0"}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import Decimal from 'decimal.js';
|
||||
import { ProtocolError, exact } from './wire.mjs';
|
||||
|
||||
export function typed(value, schema) {
|
||||
const result = decode(value, schema);
|
||||
if (value !== null && Object.hasOwn(schema, 'minimum')) {
|
||||
const number = new Decimal(value.toString());
|
||||
if (number.lt(schema.minimum) || number.gt(schema.maximum)) throw new ProtocolError('value is outside its declared range');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function decode(value, schema) {
|
||||
switch (schema.type) {
|
||||
case 'enum':
|
||||
if (!schema.values.includes(value)) throw new ProtocolError('unknown enum value');
|
||||
return value;
|
||||
case 'nullable': return value === null ? null : typed(value, schema.value);
|
||||
case 'list':
|
||||
if (!Array.isArray(value)) throw new ProtocolError('expected list');
|
||||
for (let i = 0; i < value.length; i++) value[i] = typed(value[i], schema.value);
|
||||
return value;
|
||||
case 'record': {
|
||||
exact(value, Object.keys(schema.fields));
|
||||
for (const [name, field] of Object.entries(schema.fields)) value[name] = typed(value[name], field);
|
||||
return value;
|
||||
}
|
||||
case 'int64': case 'duration': case 'model_id': {
|
||||
if ((typeof value !== 'bigint' && !Number.isSafeInteger(value)) || BigInt(value) < -(1n << 63n) || BigInt(value) >= (1n << 63n)) throw new ProtocolError('expected signed 64-bit integer');
|
||||
return value;
|
||||
}
|
||||
case 'float64':
|
||||
if (JSON.isRawJSON(value)) value = Number(value.rawJSON);
|
||||
if ((typeof value !== 'number' && typeof value !== 'bigint') || !Number.isFinite(Number(value))) throw new ProtocolError('expected finite float');
|
||||
return Number(value);
|
||||
case 'bool':
|
||||
if (typeof value !== 'boolean') throw new ProtocolError('expected boolean');
|
||||
return value;
|
||||
case 'json': return value;
|
||||
case 'text': case 'id': case 'secret': case 'decimal': case 'uuid': case 'datetime': case 'date': case 'time':
|
||||
if (typeof value !== 'string') throw new ProtocolError('expected text');
|
||||
if (schema.type === 'decimal' && !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value)) throw new ProtocolError('invalid decimal');
|
||||
if (schema.type === 'uuid' && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw new ProtocolError('invalid UUID');
|
||||
if (schema.type === 'date' && (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`)))) throw new ProtocolError('invalid Date');
|
||||
if (schema.type === 'time' && !/^\d{2}:\d{2}:\d{2}(?:\.\d{3})?$/.test(value)) throw new ProtocolError('invalid Time');
|
||||
if (schema.type === 'datetime' && (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(value) || Number.isNaN(Date.parse(value)))) throw new ProtocolError('invalid DateTime');
|
||||
return value;
|
||||
default: throw new ProtocolError('unknown worker type');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// JSON 词法、语法与字符串解析交给 jsonc-parser;这里只建立值与执行协议预算。
|
||||
import { visit } from 'jsonc-parser';
|
||||
import { once } from 'node:events';
|
||||
|
||||
export const MAX_BYTES = 16 * 1024 * 1024;
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true });
|
||||
export class ProtocolError extends Error {}
|
||||
|
||||
export function parse(text) {
|
||||
let root;
|
||||
let count = 0;
|
||||
const parents = [];
|
||||
function value(item) {
|
||||
if (++count > 65536 || parents.length > 64) throw new ProtocolError('wire JSON exceeds limit');
|
||||
const parent = parents.at(-1);
|
||||
if (!parent) root = item;
|
||||
else if (Array.isArray(parent.value)) parent.value.push(item);
|
||||
else Object.defineProperty(parent.value, parent.key, { value: item, enumerable: true, writable: true });
|
||||
}
|
||||
function container(item) {
|
||||
if (parents.length === 64) throw new ProtocolError('wire JSON exceeds depth limit');
|
||||
value(item);
|
||||
parents.push({ value: item });
|
||||
}
|
||||
visit(text, {
|
||||
onObjectBegin: () => container({}),
|
||||
onArrayBegin: () => container([]),
|
||||
onObjectEnd: () => parents.pop(),
|
||||
onArrayEnd: () => parents.pop(),
|
||||
onObjectProperty(key) {
|
||||
const parent = parents.at(-1);
|
||||
if (Object.hasOwn(parent.value, key)) throw new ProtocolError('duplicate JSON field');
|
||||
parent.key = key;
|
||||
},
|
||||
onLiteralValue(item, offset, length) {
|
||||
if (typeof item === 'number') {
|
||||
const source = text.slice(offset, offset + length);
|
||||
if (!/[.eE]/.test(source) && !Number.isSafeInteger(item)) item = BigInt(source);
|
||||
else if (/[.eE]/.test(source)) item = JSON.rawJSON(source);
|
||||
}
|
||||
value(item);
|
||||
},
|
||||
onError: code => { throw new ProtocolError('invalid JSON: ' + code); },
|
||||
}, { disallowComments: true, allowTrailingComma: false, allowEmptyContent: false });
|
||||
if (!root || typeof root !== 'object' || Array.isArray(root)) throw new ProtocolError('expected protocol object');
|
||||
return root;
|
||||
}
|
||||
|
||||
export function exact(value, names) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== names.length || names.some(name => !Object.hasOwn(value, name))) {
|
||||
throw new ProtocolError('missing or extra record fields');
|
||||
}
|
||||
}
|
||||
|
||||
export class Channel {
|
||||
#input = process.stdin[Symbol.asyncIterator]();
|
||||
#chunk = Buffer.alloc(0);
|
||||
#offset = 0;
|
||||
|
||||
async #read(size) {
|
||||
const result = Buffer.allocUnsafe(size);
|
||||
let offset = 0;
|
||||
while (offset < size) {
|
||||
if (this.#offset === this.#chunk.length) {
|
||||
const next = await this.#input.next();
|
||||
if (next.done) throw new ProtocolError('incomplete component frame');
|
||||
this.#chunk = next.value;
|
||||
this.#offset = 0;
|
||||
}
|
||||
const length = Math.min(size - offset, this.#chunk.length - this.#offset);
|
||||
this.#chunk.copy(result, offset, this.#offset, this.#offset + length);
|
||||
this.#offset += length;
|
||||
offset += length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async receive() {
|
||||
const size = (await this.#read(4)).readUInt32BE();
|
||||
if (size === 0 || size > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit');
|
||||
return parse(decoder.decode(await this.#read(size)));
|
||||
}
|
||||
|
||||
async send(message) {
|
||||
let count = 0;
|
||||
function bounded(value, depth) {
|
||||
if (++count > 65536 || depth > 64) throw new ProtocolError('wire JSON exceeds limit');
|
||||
if (typeof value === 'number' && !Number.isFinite(value)) throw new ProtocolError('non-finite JSON number');
|
||||
if (value && typeof value === 'object' && !JSON.isRawJSON(value)) {
|
||||
if (depth === 64) throw new ProtocolError('wire JSON exceeds depth limit');
|
||||
for (const item of Object.values(value)) bounded(item, depth + 1);
|
||||
}
|
||||
}
|
||||
bounded(message, 0);
|
||||
// 原生 JSON 保留完整 Int,不自写 JSON 编码器。运行时要求 Node 22 以上。
|
||||
const body = Buffer.from(JSON.stringify(message, (_key, value) => {
|
||||
if (typeof value === 'bigint') return JSON.rawJSON(value.toString());
|
||||
if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new ProtocolError('invalid JSON value');
|
||||
return value;
|
||||
}));
|
||||
if (body.length > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit');
|
||||
const header = Buffer.allocUnsafe(4);
|
||||
header.writeUInt32BE(body.length);
|
||||
if (!process.stdout.write(header)) await once(process.stdout, 'drain');
|
||||
await new Promise((resolve, reject) => process.stdout.write(body, error => error ? reject(error) : resolve()));
|
||||
}
|
||||
|
||||
close() { process.stdin.destroy(); }
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
"""Dever Worker:直接使用编译器的 manifest,业务只提供异步处理函数。"""
|
||||
import asyncio
|
||||
import simplejson as json
|
||||
from decimal import Decimal
|
||||
import math
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
VERSION = "dever-component-1"
|
||||
MAX_BYTES = 16 * 1024 * 1024
|
||||
MAX_DEPTH = 64
|
||||
MAX_ELEMENTS = 65_536
|
||||
CANCEL_GRACE = 1
|
||||
|
||||
class ProtocolError(Exception):
|
||||
pass
|
||||
|
||||
class BusinessError(Exception):
|
||||
def __init__(self, identity: str, payload: Any):
|
||||
super().__init__(identity)
|
||||
self.identity = identity
|
||||
self.payload = payload
|
||||
|
||||
def _typed(value: Any, schema: dict[str, Any]) -> Any:
|
||||
result = _value(value, schema)
|
||||
if value is not None and "minimum" in schema:
|
||||
number = Decimal(value)
|
||||
if not Decimal(schema["minimum"]) <= number <= Decimal(schema["maximum"]):
|
||||
raise ValueError("value is outside its declared range")
|
||||
return result
|
||||
|
||||
|
||||
def _value(value: Any, schema: dict[str, Any]) -> Any:
|
||||
kind = schema["type"]
|
||||
if kind == "enum":
|
||||
if value not in schema["values"]:
|
||||
raise ValueError("unknown enum value")
|
||||
return value
|
||||
if kind == "nullable":
|
||||
return None if value is None else _typed(value, schema["value"])
|
||||
if kind == "list":
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("expected list")
|
||||
for index, item in enumerate(value):
|
||||
value[index] = _typed(item, schema["value"])
|
||||
return value
|
||||
if kind == "record":
|
||||
fields = schema["fields"]
|
||||
if not isinstance(value, dict) or value.keys() != fields.keys():
|
||||
raise ValueError("missing or extra record fields")
|
||||
for name, field in fields.items():
|
||||
value[name] = _typed(value[name], field)
|
||||
return value
|
||||
if kind in ("int64", "duration", "model_id"):
|
||||
if type(value) is not int or not -(2**63) <= value < 2**63:
|
||||
raise ValueError("expected signed 64-bit integer")
|
||||
elif kind == "float64":
|
||||
if type(value) not in (int, float, Decimal) or not math.isfinite(value):
|
||||
raise ValueError("expected finite float")
|
||||
return float(value)
|
||||
elif kind == "bool":
|
||||
if type(value) is not bool:
|
||||
raise ValueError("expected boolean")
|
||||
elif kind == "json":
|
||||
pass # 整帧边界统一检查 JSON 预算。
|
||||
elif kind in ("text", "id", "secret", "decimal", "uuid", "datetime", "date", "time"):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("expected text")
|
||||
if kind == "decimal" and not re.fullmatch(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", value):
|
||||
raise ValueError("invalid decimal")
|
||||
if kind == "uuid":
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value):
|
||||
raise ValueError("invalid UUID")
|
||||
uuid.UUID(value)
|
||||
if kind == "date":
|
||||
import datetime
|
||||
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
||||
raise ValueError("invalid Date")
|
||||
datetime.date.fromisoformat(value)
|
||||
if kind == "time":
|
||||
import datetime
|
||||
if not re.fullmatch(r"\d{2}:\d{2}:\d{2}(?:\.\d{3})?", value):
|
||||
raise ValueError("invalid Time")
|
||||
datetime.time.fromisoformat(value)
|
||||
if kind == "datetime":
|
||||
import datetime
|
||||
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})", value):
|
||||
raise ValueError("invalid DateTime")
|
||||
datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
else:
|
||||
raise ValueError("unknown worker type")
|
||||
return value
|
||||
|
||||
|
||||
def _pairs(values: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
result = {}
|
||||
for key, value in values:
|
||||
if key in result:
|
||||
raise ProtocolError("duplicate JSON field")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _reject_constant(_: str) -> None:
|
||||
raise ProtocolError("invalid JSON number")
|
||||
|
||||
|
||||
def _bounded(value: Any, depth: int, budget: list[int]) -> None:
|
||||
if depth > MAX_DEPTH or (depth == MAX_DEPTH and isinstance(value, (dict, list))):
|
||||
raise ProtocolError("wire JSON exceeds depth limit")
|
||||
budget[0] -= 1
|
||||
if budget[0] < 0:
|
||||
raise ProtocolError("wire JSON exceeds element limit")
|
||||
if isinstance(value, dict):
|
||||
for child in value.values():
|
||||
_bounded(child, depth + 1, budget)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
_bounded(child, depth + 1, budget)
|
||||
elif isinstance(value, str):
|
||||
value.encode("utf-8")
|
||||
elif isinstance(value, Decimal) and not value.is_finite():
|
||||
raise ProtocolError("non-finite JSON number")
|
||||
elif isinstance(value, float) and not math.isfinite(value):
|
||||
raise ProtocolError("non-finite wire Float")
|
||||
|
||||
|
||||
def _decode(body: bytes) -> dict[str, Any]:
|
||||
try:
|
||||
value = json.loads(body.decode("utf-8"), object_pairs_hook=_pairs,
|
||||
parse_constant=_reject_constant, use_decimal=True)
|
||||
except (UnicodeError, ValueError, RecursionError) as error:
|
||||
raise ProtocolError("invalid component JSON") from error
|
||||
_bounded(value, 0, [MAX_ELEMENTS])
|
||||
if not isinstance(value, dict):
|
||||
raise ProtocolError("component message must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _fields(message: dict[str, Any], names: set[str]) -> None:
|
||||
if message.keys() != names:
|
||||
raise ProtocolError("component message has missing or extra fields")
|
||||
|
||||
|
||||
def _id(value: Any) -> int:
|
||||
if type(value) is not int or not 0 <= value <= 2**63 - 1:
|
||||
raise ProtocolError("invalid request id")
|
||||
return value
|
||||
|
||||
|
||||
async def _read_frame(reader: asyncio.StreamReader) -> dict[str, Any]:
|
||||
try:
|
||||
size = struct.unpack(">I", await reader.readexactly(4))[0]
|
||||
if not 0 < size <= MAX_BYTES:
|
||||
raise ProtocolError("component frame exceeds byte limit")
|
||||
return _decode(await reader.readexactly(size))
|
||||
except asyncio.IncompleteReadError as error:
|
||||
raise ProtocolError("incomplete component frame") from error
|
||||
|
||||
|
||||
def _write_frame(message: dict[str, Any]) -> None:
|
||||
try:
|
||||
body = json.dumps(message, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
|
||||
except (TypeError, ValueError) as error:
|
||||
raise ProtocolError("invalid handler response") from error
|
||||
_bounded(message, 0, [MAX_ELEMENTS])
|
||||
if not 0 < len(body) <= MAX_BYTES:
|
||||
raise ProtocolError("component frame exceeds byte limit")
|
||||
sys.__stdout__.buffer.write(struct.pack(">I", len(body)) + body)
|
||||
sys.__stdout__.buffer.flush()
|
||||
|
||||
|
||||
async def _stop_handler(task: asyncio.Task) -> None:
|
||||
task.cancel()
|
||||
completed, _ = await asyncio.wait({task}, timeout=CANCEL_GRACE)
|
||||
if not completed:
|
||||
raise ProtocolError("component handler did not stop after cancellation")
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self, manifest: dict, handlers: dict):
|
||||
if set(handlers) != set(manifest["operations"]):
|
||||
raise ValueError("handlers must cover the checked Port exactly")
|
||||
if any(not asyncio.iscoroutinefunction(handler) for handler in handlers.values()):
|
||||
raise ValueError("Worker handlers must be async")
|
||||
self.manifest = manifest
|
||||
self.handlers = handlers
|
||||
|
||||
async def serve(self) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
reader = asyncio.StreamReader()
|
||||
transport, _ = await loop.connect_read_pipe(
|
||||
lambda: asyncio.StreamReaderProtocol(reader), sys.stdin.buffer
|
||||
)
|
||||
try:
|
||||
await self._serve(reader)
|
||||
finally:
|
||||
transport.close()
|
||||
|
||||
async def _serve(self, reader: asyncio.StreamReader) -> None:
|
||||
hello = await _read_frame(reader)
|
||||
_fields(hello, {"kind", "version", "port", "schema", "adapter", "capabilities", "operations", "setting"})
|
||||
setting = hello.pop("setting")
|
||||
expected = {name: self.manifest[name] for name in
|
||||
("port", "schema", "adapter", "capabilities", "operations")}
|
||||
expected.update(kind="hello", version=VERSION)
|
||||
if hello != expected:
|
||||
raise ProtocolError("handshake differs from the checked Port")
|
||||
if self.manifest["setting"] is None:
|
||||
if setting is not None:
|
||||
raise ProtocolError("unexpected setting")
|
||||
else:
|
||||
_typed(setting, self.manifest["setting"])
|
||||
expected["kind"] = "ready"
|
||||
_write_frame(expected)
|
||||
messages: asyncio.Queue = asyncio.Queue(maxsize=4)
|
||||
|
||||
async def read_messages() -> None:
|
||||
while True:
|
||||
try:
|
||||
message = await _read_frame(reader)
|
||||
except (OSError, ProtocolError) as error:
|
||||
await messages.put(("fault", error))
|
||||
return
|
||||
await messages.put(("frame", message))
|
||||
|
||||
receiver = asyncio.create_task(read_messages())
|
||||
try:
|
||||
await self._dispatch(messages, setting)
|
||||
finally:
|
||||
receiver.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await receiver
|
||||
|
||||
async def _dispatch(self, messages: asyncio.Queue, setting: Any) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
active_id: int | None = None
|
||||
active_task: asyncio.Task | None = None
|
||||
active_operation: str | None = None
|
||||
next_id = 1
|
||||
last_cancelled = False
|
||||
completions: set[asyncio.Task] = set()
|
||||
|
||||
def on_done(task: asyncio.Task) -> None:
|
||||
try:
|
||||
task.exception()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
notification = loop.create_task(messages.put(("done", task)))
|
||||
completions.add(notification)
|
||||
notification.add_done_callback(completions.discard)
|
||||
|
||||
try:
|
||||
while True:
|
||||
event, value = await messages.get()
|
||||
if event == "fault":
|
||||
raise value
|
||||
if event == "done":
|
||||
task = value
|
||||
if task is active_task:
|
||||
try:
|
||||
payload = task.result()
|
||||
_typed(payload, self.manifest["outputs"][active_operation])
|
||||
_write_frame({"kind": "result", "id": active_id, "payload": payload})
|
||||
except BusinessError as error:
|
||||
if error.identity not in self.manifest["errors"]:
|
||||
raise ProtocolError("undeclared business error identity") from error
|
||||
_typed(error.payload, self.manifest["errors"][error.identity])
|
||||
_write_frame({"kind": "error", "id": active_id, "error": error.identity, "payload": error.payload})
|
||||
except asyncio.CancelledError as error:
|
||||
raise ProtocolError("handler cancelled without a cancel request") from error
|
||||
except Exception as error:
|
||||
raise ProtocolError("component handler failed") from error
|
||||
active_id, active_task, active_operation = None, None, None
|
||||
last_cancelled = False
|
||||
continue
|
||||
message = value
|
||||
kind = message.get("kind")
|
||||
if kind == "health":
|
||||
_fields(message, {"kind", "id"})
|
||||
if _id(message["id"]) != 0:
|
||||
raise ProtocolError("invalid health id")
|
||||
_write_frame(message)
|
||||
elif kind == "call":
|
||||
_fields(message, {"kind", "id", "operation", "payload"})
|
||||
request_id = _id(message["id"])
|
||||
operation = message["operation"]
|
||||
if request_id != next_id or active_task is not None or not isinstance(operation, str) or operation not in self.handlers:
|
||||
raise ProtocolError("invalid component call")
|
||||
next_id += 1
|
||||
handler = self.handlers[operation]
|
||||
try:
|
||||
payload = _typed(message["payload"], self.manifest["inputs"][operation])
|
||||
except Exception as error:
|
||||
raise ProtocolError("invalid component payload") from error
|
||||
async def invoke() -> Any:
|
||||
return await handler(payload, setting)
|
||||
active_id = request_id
|
||||
active_operation = operation
|
||||
active_task = loop.create_task(invoke())
|
||||
active_task.add_done_callback(on_done)
|
||||
elif kind == "cancel":
|
||||
_fields(message, {"kind", "id"})
|
||||
request_id = _id(message["id"])
|
||||
if request_id == 0:
|
||||
raise ProtocolError("invalid cancel id")
|
||||
if active_id == request_id and active_task is not None:
|
||||
stopped_task = active_task
|
||||
active_id, active_task, active_operation = None, None, None
|
||||
await _stop_handler(stopped_task)
|
||||
last_cancelled = True
|
||||
_write_frame({"kind": "error", "id": request_id, "error": "dever.cancelled", "payload": None})
|
||||
elif request_id != next_id - 1 or last_cancelled:
|
||||
raise ProtocolError("unknown component cancel id")
|
||||
elif kind == "shutdown":
|
||||
_fields(message, {"kind"})
|
||||
if active_task is not None:
|
||||
stopped_task = active_task
|
||||
active_id, active_task = None, None
|
||||
await _stop_handler(stopped_task)
|
||||
_write_frame({"kind": "shutdown"})
|
||||
return
|
||||
else:
|
||||
raise ProtocolError("unknown component message")
|
||||
|
||||
finally:
|
||||
if active_task is not None:
|
||||
active_task.remove_done_callback(on_done)
|
||||
await _stop_handler(active_task)
|
||||
for notification in completions:
|
||||
notification.cancel()
|
||||
await asyncio.gather(*completions, return_exceptions=True)
|
||||
|
||||
|
||||
def main(worker: Worker) -> None:
|
||||
# Runner 负责取消并等待残余任务,异常原因沿 Python 原始链路写 stderr。
|
||||
asyncio.run(worker.serve())
|
||||
@@ -0,0 +1,12 @@
|
||||
[project]
|
||||
name = "dever-component"
|
||||
version = "0.0.1"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = ["simplejson==3.20.2"]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools==80.9.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ["dever_component"]
|
||||
Generated
+62
@@ -0,0 +1,62 @@
|
||||
version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.11"
|
||||
|
||||
[[package]]
|
||||
name = "dever-component"
|
||||
version = "0.0.1"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "simplejson" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "simplejson", specifier = "==3.20.2" }]
|
||||
|
||||
[[package]]
|
||||
name = "simplejson"
|
||||
version = "3.20.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/41/f4/a1ac5ed32f7ed9a088d62a59d410d4c204b3b3815722e2ccfb491fa8251b/simplejson-3.20.2.tar.gz", hash = "sha256:5fe7a6ce14d1c300d80d08695b7f7e633de6cd72c80644021874d985b3393649", size = 85784, upload-time = "2025-09-26T16:29:36.64Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/3e/96898c6c66d9dca3f9bd14d7487bf783b4acc77471b42f979babbb68d4ca/simplejson-3.20.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06190b33cd7849efc413a5738d3da00b90e4a5382fd3d584c841ac20fb828c6f", size = 92633, upload-time = "2025-09-26T16:27:45.028Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/a2/cd2e10b880368305d89dd540685b8bdcc136df2b3c76b5ddd72596254539/simplejson-3.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4ad4eac7d858947a30d2c404e61f16b84d16be79eb6fb316341885bdde864fa8", size = 75309, upload-time = "2025-09-26T16:27:46.142Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/02/290f7282eaa6ebe945d35c47e6534348af97472446951dce0d144e013f4c/simplejson-3.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b392e11c6165d4a0fde41754a0e13e1d88a5ad782b245a973dd4b2bdb4e5076a", size = 75308, upload-time = "2025-09-26T16:27:47.542Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/91/43695f17b69e70c4b0b03247aa47fb3989d338a70c4b726bbdc2da184160/simplejson-3.20.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:51eccc4e353eed3c50e0ea2326173acdc05e58f0c110405920b989d481287e51", size = 143733, upload-time = "2025-09-26T16:27:48.673Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/4b/fdcaf444ac1c3cbf1c52bf00320c499e1cf05d373a58a3731ae627ba5e2d/simplejson-3.20.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:306e83d7c331ad833d2d43c76a67f476c4b80c4a13334f6e34bb110e6105b3bd", size = 153397, upload-time = "2025-09-26T16:27:49.89Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/83/21550f81a50cd03599f048a2d588ffb7f4c4d8064ae091511e8e5848eeaa/simplejson-3.20.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f820a6ac2ef0bc338ae4963f4f82ccebdb0824fe9caf6d660670c578abe01013", size = 141654, upload-time = "2025-09-26T16:27:51.168Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cf/54/d76c0e72ad02450a3e723b65b04f49001d0e73218ef6a220b158a64639cb/simplejson-3.20.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21e7a066528a5451433eb3418184f05682ea0493d14e9aae690499b7e1eb6b81", size = 144913, upload-time = "2025-09-26T16:27:52.331Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3f/49/976f59b42a6956d4aeb075ada16ad64448a985704bc69cd427a2245ce835/simplejson-3.20.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:438680ddde57ea87161a4824e8de04387b328ad51cfdf1eaf723623a3014b7aa", size = 144568, upload-time = "2025-09-26T16:27:53.41Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/c7/30bae30424ace8cd791ca660fed454ed9479233810fe25c3f3eab3d9dc7b/simplejson-3.20.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:cac78470ae68b8d8c41b6fca97f5bf8e024ca80d5878c7724e024540f5cdaadb", size = 146239, upload-time = "2025-09-26T16:27:54.502Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/79/3e/7f3b7b97351c53746e7b996fcd106986cda1954ab556fd665314756618d2/simplejson-3.20.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:7524e19c2da5ef281860a3d74668050c6986be15c9dd99966034ba47c68828c2", size = 154497, upload-time = "2025-09-26T16:27:55.885Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/48/7241daa91d0bf19126589f6a8dcbe8287f4ed3d734e76fd4a092708947be/simplejson-3.20.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0e9b6d845a603b2eef3394eb5e21edb8626cd9ae9a8361d14e267eb969dbe413", size = 148069, upload-time = "2025-09-26T16:27:57.039Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/f4/ef18d2962fe53e7be5123d3784e623859eec7ed97060c9c8536c69d34836/simplejson-3.20.2-cp311-cp311-win32.whl", hash = "sha256:47d8927e5ac927fdd34c99cc617938abb3624b06ff86e8e219740a86507eb961", size = 74158, upload-time = "2025-09-26T16:27:58.265Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/fd/3d1158ecdc573fdad81bf3cc78df04522bf3959758bba6597ba4c956c74d/simplejson-3.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:ba4edf3be8e97e4713d06c3d302cba1ff5c49d16e9d24c209884ac1b8455520c", size = 75911, upload-time = "2025-09-26T16:27:59.292Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/9e/1a91e7614db0416885eab4136d49b7303de20528860ffdd798ce04d054db/simplejson-3.20.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:4376d5acae0d1e91e78baeba4ee3cf22fbf6509d81539d01b94e0951d28ec2b6", size = 93523, upload-time = "2025-09-26T16:28:00.356Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/2b/d2413f5218fc25608739e3d63fe321dfa85c5f097aa6648dbe72513a5f12/simplejson-3.20.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f8fe6de652fcddae6dec8f281cc1e77e4e8f3575249e1800090aab48f73b4259", size = 75844, upload-time = "2025-09-26T16:28:01.756Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/f1/efd09efcc1e26629e120fef59be059ce7841cc6e1f949a4db94f1ae8a918/simplejson-3.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:25ca2663d99328d51e5a138f22018e54c9162438d831e26cfc3458688616eca8", size = 75655, upload-time = "2025-09-26T16:28:03.037Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/ec/5c6db08e42f380f005d03944be1af1a6bd501cc641175429a1cbe7fb23b9/simplejson-3.20.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:12a6b2816b6cab6c3fd273d43b1948bc9acf708272074c8858f579c394f4cbc9", size = 150335, upload-time = "2025-09-26T16:28:05.027Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/81/f5/808a907485876a9242ec67054da7cbebefe0ee1522ef1c0be3bfc90f96f6/simplejson-3.20.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ac20dc3fcdfc7b8415bfc3d7d51beccd8695c3f4acb7f74e3a3b538e76672868", size = 158519, upload-time = "2025-09-26T16:28:06.5Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/66/af/b8a158246834645ea890c36136584b0cc1c0e4b83a73b11ebd9c2a12877c/simplejson-3.20.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:db0804d04564e70862ef807f3e1ace2cc212ef0e22deb1b3d6f80c45e5882c6b", size = 148571, upload-time = "2025-09-26T16:28:07.715Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/20/05/ed9b2571bbf38f1a2425391f18e3ac11cb1e91482c22d644a1640dea9da7/simplejson-3.20.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:979ce23ea663895ae39106946ef3d78527822d918a136dbc77b9e2b7f006237e", size = 152367, upload-time = "2025-09-26T16:28:08.921Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/81/2c/bad68b05dd43e93f77994b920505634d31ed239418eb6a88997d06599983/simplejson-3.20.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a2ba921b047bb029805726800819675249ef25d2f65fd0edb90639c5b1c3033c", size = 150205, upload-time = "2025-09-26T16:28:10.086Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/69/46/90c7fc878061adafcf298ce60cecdee17a027486e9dce507e87396d68255/simplejson-3.20.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:12d3d4dc33770069b780cc8f5abef909fe4a3f071f18f55f6d896a370fd0f970", size = 151823, upload-time = "2025-09-26T16:28:11.329Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/27/b85b03349f825ae0f5d4f780cdde0bbccd4f06c3d8433f6a3882df887481/simplejson-3.20.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:aff032a59a201b3683a34be1169e71ddda683d9c3b43b261599c12055349251e", size = 158997, upload-time = "2025-09-26T16:28:12.917Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/ad/d7f3c331fb930638420ac6d236db68e9f4c28dab9c03164c3cd0e7967e15/simplejson-3.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:30e590e133b06773f0dc9c3f82e567463df40598b660b5adf53eb1c488202544", size = 154367, upload-time = "2025-09-26T16:28:14.393Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/46/5c67324addd40fa2966f6e886cacbbe0407c03a500db94fb8bb40333fcdf/simplejson-3.20.2-cp312-cp312-win32.whl", hash = "sha256:8d7be7c99939cc58e7c5bcf6bb52a842a58e6c65e1e9cdd2a94b697b24cddb54", size = 74285, upload-time = "2025-09-26T16:28:15.931Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/c9/5cc2189f4acd3a6e30ffa9775bf09b354302dbebab713ca914d7134d0f29/simplejson-3.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:2c0b4a67e75b945489052af6590e7dca0ed473ead5d0f3aad61fa584afe814ab", size = 75969, upload-time = "2025-09-26T16:28:17.017Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/9e/f326d43f6bf47f4e7704a4426c36e044c6bedfd24e072fb8e27589a373a5/simplejson-3.20.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:90d311ba8fcd733a3677e0be21804827226a57144130ba01c3c6a325e887dd86", size = 93530, upload-time = "2025-09-26T16:28:18.07Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/28/5a4b8f3483fbfb68f3f460bc002cef3a5735ef30950e7c4adce9c8da15c7/simplejson-3.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:feed6806f614bdf7f5cb6d0123cb0c1c5f40407ef103aa935cffaa694e2e0c74", size = 75846, upload-time = "2025-09-26T16:28:19.12Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/4d/30dfef83b9ac48afae1cf1ab19c2867e27b8d22b5d9f8ca7ce5a0a157d8c/simplejson-3.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6b1d8d7c3e1a205c49e1aee6ba907dcb8ccea83651e6c3e2cb2062f1e52b0726", size = 75661, upload-time = "2025-09-26T16:28:20.219Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/1d/171009bd35c7099d72ef6afd4bb13527bab469965c968a17d69a203d62a6/simplejson-3.20.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:552f55745044a24c3cb7ec67e54234be56d5d6d0e054f2e4cf4fb3e297429be5", size = 150579, upload-time = "2025-09-26T16:28:21.337Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/61/ae/229bbcf90a702adc6bfa476e9f0a37e21d8c58e1059043038797cbe75b8c/simplejson-3.20.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2da97ac65165d66b0570c9e545786f0ac7b5de5854d3711a16cacbcaa8c472d", size = 158797, upload-time = "2025-09-26T16:28:22.53Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/90/c5/fefc0ac6b86b9108e302e0af1cf57518f46da0baedd60a12170791d56959/simplejson-3.20.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f59a12966daa356bf68927fca5a67bebac0033cd18b96de9c2d426cd11756cd0", size = 148851, upload-time = "2025-09-26T16:28:23.733Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/f1/b392952200f3393bb06fbc4dd975fc63a6843261705839355560b7264eb2/simplejson-3.20.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:133ae2098a8e162c71da97cdab1f383afdd91373b7ff5fe65169b04167da976b", size = 152598, upload-time = "2025-09-26T16:28:24.962Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f4/b4/d6b7279e52a3e9c0fa8c032ce6164e593e8d9cf390698ee981ed0864291b/simplejson-3.20.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7977640af7b7d5e6a852d26622057d428706a550f7f5083e7c4dd010a84d941f", size = 150498, upload-time = "2025-09-26T16:28:26.114Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/62/22/ec2490dd859224326d10c2fac1353e8ad5c84121be4837a6dd6638ba4345/simplejson-3.20.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b530ad6d55e71fa9e93e1109cf8182f427a6355848a4ffa09f69cc44e1512522", size = 152129, upload-time = "2025-09-26T16:28:27.552Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/33/ce/b60214d013e93dd9e5a705dcb2b88b6c72bada442a97f79828332217f3eb/simplejson-3.20.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:bd96a7d981bf64f0e42345584768da4435c05b24fd3c364663f5fbc8fabf82e3", size = 159359, upload-time = "2025-09-26T16:28:28.667Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/99/21/603709455827cdf5b9d83abe726343f542491ca8dc6a2528eb08de0cf034/simplejson-3.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f28ee755fadb426ba2e464d6fcf25d3f152a05eb6b38e0b4f790352f5540c769", size = 154717, upload-time = "2025-09-26T16:28:30.288Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3c/f9/dc7f7a4bac16cf7eb55a4df03ad93190e11826d2a8950052949d3dfc11e2/simplejson-3.20.2-cp313-cp313-win32.whl", hash = "sha256:472785b52e48e3eed9b78b95e26a256f59bb1ee38339be3075dad799e2e1e661", size = 74289, upload-time = "2025-09-26T16:28:31.809Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/10/d42ad61230436735c68af1120622b28a782877146a83d714da7b6a2a1c4e/simplejson-3.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:a1a85013eb33e4820286139540accbe2c98d2da894b2dcefd280209db508e608", size = 75972, upload-time = "2025-09-26T16:28:32.883Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl", hash = "sha256:3b6bb7fb96efd673eac2e4235200bfffdc2353ad12c54117e1e4e2fc485ac017", size = 57309, upload-time = "2025-09-26T16:29:35.312Z" },
|
||||
]
|
||||
Reference in new issue
Block a user