core/plugin/wasmguest/hostcalls.go
Alex Dunmow bec3a43f55 feat(wasmguest): guest capability stubs over host calls (WO-WZ-003)
Every CoreServices interface (core/plugin/deps.go) now has a guest-side stub
that marshals to the WO-WZ-001 capability messages and dispatches through the
generic host_call transport, so plugin service code compiles and runs
unchanged against content.Content, settings.Settings, plugin.PluginBridge, etc.

- core/plugin/wasmguest/caps/: one file per family (17 families, 38 methods),
  a var _ <iface> = (*stub)(nil) compile proof each, and NewCoreServices(call)
  assembling them. The transport is injected (CallFunc) so marshaling is
  natively testable; the wasm shim binds it to CallHost, DESCRIBE probes pass
  nil (capability calls fail cleanly instead of nil-panicking).
- Error mapping wraps AbiError with <family>.<method> context and maps
  DEADLINE_EXCEEDED onto context.DeadlineExceeded.
- RAGService.RegisterContentFetcher stays guest-side (RAGStub) for
  HOOK_RAG_FETCH dispatch; Query/OnContentChanged marshal out. dispatch.go and
  describe.go now source fetchers from the caps RAG stub.
- caps_roundtrip_test.go: fake transport + 76 deterministic golden payloads
  (family_method_{req,resp}.pb) covering 100% of families, plus error-mapping,
  deadline, nil-transport, and guest-side-fetcher tests. WO-WZ-006 replays the
  same goldens to prevent host/guest drift.
- Acceptance: testdata/fixture Load hook calls deps.Content/Settings/Bridge
  unchanged (compiles for wasip1); caps_wasmhost_test.go drives it end-to-end
  through a real wazero module + fake host_call table.
- Disposition table in docs/wasm-abi.md: every member stub | host-side
  (Pool, Interceptors, AppURL/MediaPath, CoreServiceBindings host-side).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 14:23:58 +08:00

120 lines
4.2 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
// init binds the capability-stub transport (package caps) to the real
// host_call-backed CallHost. Only wasip1 has a host to call; native builds
// leave caps' transport nil, so their capability calls fail cleanly.
func init() { capTransport = CallHost }
// 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)
}
// AbiErrorCode exposes the underlying ABI error code so the capability stubs
// (package caps) can map a DEADLINE_EXCEEDED reply onto context.DeadlineExceeded
// without importing this wasip1-only package.
func (e *HostError) AbiErrorCode() abiv1.AbiErrorCode { return e.Code }
// 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
}