Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user