core/plugin/wasmguest/hostcalls.go
Alex Dunmow c35199f0bc feat(wasmguest): guest runtime shim for the wasm plugin ABI (WO-WZ-002)
The wasip1 half of the ABI: bn_alloc/bn_invoke/bn_free exports with a
live-pin map so the GC never frees host-visible buffers, the generic
`blockninja.host_call` import (single import decided over per-family
symbols; recorded in wasm-abi.md), and a dispatch table adapting an
unmodified plugin.PluginRegistration to all nine v1 hooks. Panics inside
plugin hooks come back as ABI_ERROR_CODE_INTERNAL — the instance stays
callable; traps stay reserved for runtime corruption.

DESCRIBE builds the PluginManifest from the registration's static funcs
plus a capture-only Register pass (block metas via the same
PluginBlockRegistry prefixing the .so loader applies, template/system/
page-template/email-wrapper keys), probes JobHandlers/ServiceHandlers/
Load with capture-only services for job types, RBAC roles, core-service
bindings, and RAG fetcher types. RenderContext values are rehydrated
through the exact core/blocks context keys, so existing block code
reading from ctx works unchanged.

Plugins build in REACTOR mode (go build -buildmode=c-shared): init()
calls wasmguest.Serve (non-blocking), main is never called, and the host
runs _initialize before any bn_invoke. Command mode deadlocks or exits
(verified against wazero v1.12.0) — documented prominently in
wasm-abi.md, which also now reconciles the import module namespace to
`blockninja` and requires bn_alloc'd buffers on both directions.

Dispatch/describe/context logic is buildable on every GOOS; only
exports.go and hostcalls.go carry the wasip1 tag. dispatch_test.go
covers describe, hook routing, envelope mismatch, decode failures,
template-override resolution, panic recovery, and lifecycle hooks
natively.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:53:24 +08:00

110 lines
3.6 KiB
Go

//go:build wasip1
package wasmguest
import (
"fmt"
"runtime"
abiv1 "git.dev.alexdunmow.com/block/core/abi/v1"
"google.golang.org/protobuf/proto"
)
// Guest→host capability calls use ONE generic import rather than one import
// per capability family: the method string inside HostCallRequest already
// selects the family ("<family>.<snake_method>", including the db.* driver
// messages), so per-family import symbols would add ~40 declarations on
// both sides of the boundary for zero type safety — the payloads are opaque
// protobuf bytes either way. Decision recorded in core/docs/wasm-abi.md.
//
// Shape (mirrors bn_invoke in reverse): the guest passes (ptr, len) framing
// a serialized HostCallRequest; the host returns packed ((ptr << 32) | len)
// framing a HostCallResponse it wrote into guest memory via bn_alloc.
// packed == 0 means the host could not produce an envelope.
//
//go:wasmimport blockninja host_call
//go:noescape
func hostCall(ptr uint32, size uint32) uint64
// HostError is a failed capability call's AbiError surfaced as a Go error.
type HostError struct {
Code abiv1.AbiErrorCode
Message string
}
func (e *HostError) Error() string {
return fmt.Sprintf("host call failed (%s): %s", e.Code, e.Message)
}
// HostCall performs one guest→host capability call. method is
// "<family>.<snake_method>" (e.g. "crypto.encrypt_secret"); payload is the
// serialized family request message. It returns the serialized family
// response payload. The capability-stub implementations of the CoreServices
// interfaces are built on this.
func HostCall(method string, payload []byte) ([]byte, error) {
raw, err := proto.Marshal(&abiv1.HostCallRequest{Method: method, Payload: payload})
if err != nil {
return nil, fmt.Errorf("wasmguest: marshal HostCallRequest: %w", err)
}
var ptr, size uint32
if len(raw) > 0 {
ptr = bufPtr(raw)
size = uint32(len(raw))
}
packed := hostCall(ptr, size)
runtime.KeepAlive(raw)
if packed == 0 {
return nil, &HostError{
Code: abiv1.AbiErrorCode_ABI_ERROR_CODE_INTERNAL,
Message: "host returned packed 0 (no envelope) for " + method,
}
}
respPtr := uint32(packed >> 32)
respLen := uint32(packed)
buf, ok := pinned[respPtr]
if !ok || uint32(len(buf)) < respLen {
// The ABI requires the host to write responses into bn_alloc'd
// memory; anything else is a protocol violation.
return nil, &HostError{
Code: abiv1.AbiErrorCode_ABI_ERROR_CODE_DECODE,
Message: "host response pointer was not allocated via bn_alloc for " + method,
}
}
respBytes := buf[:respLen:respLen]
resp := &abiv1.HostCallResponse{}
unmarshalErr := proto.Unmarshal(respBytes, resp) // copies; safe to release the buffer
delete(pinned, respPtr) // host allocated via bn_alloc; the shim owns the release
if unmarshalErr != nil {
return nil, fmt.Errorf("wasmguest: decode HostCallResponse for %s: %w", method, unmarshalErr)
}
if e := resp.GetError(); e != nil {
return nil, &HostError{Code: e.GetCode(), Message: e.GetMessage()}
}
return resp.GetPayload(), nil
}
// CallHost marshals req, performs the capability call, and unmarshals the
// response into resp — the typed convenience wrapper capability stubs use.
func CallHost(method string, req, resp proto.Message) error {
var payload []byte
if req != nil {
b, err := proto.Marshal(req)
if err != nil {
return fmt.Errorf("wasmguest: marshal %s request: %w", method, err)
}
payload = b
}
out, err := HostCall(method, payload)
if err != nil {
return err
}
if resp != nil {
if err := proto.Unmarshal(out, resp); err != nil {
return fmt.Errorf("wasmguest: decode %s response: %w", method, err)
}
}
return nil
}