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

+252
View File
@@ -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
}
+3
View File
@@ -0,0 +1,3 @@
module dever/component
go 1.25.0
+178
View File
@@ -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
View File
@@ -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")
}
}