feat(plugin-abi,sdk): versioned C ABI v1, host bindings, Rust SDK and C example

Blueprint section 10: a first-class plugin ABI independent of the legacy
MARQDO_ABI_VERSION=2, with a C ABI that is explicitly not a sandbox.

- include/marqdo_plugin_abi_v1.h: frozen stable-layout C contract with
  documented buffer ownership/lifetimes, size limits, NULL/zero-length
  semantics, single-threaded invocation, no hot-unload policy, version
  negotiation and target-triple requirements.
- marqdo-plugin-abi (host side): repr(C) mirrors with compile-time layout
  assertions, major/minor negotiation (wrong major fails, minor clamps),
  plugin.yaml parsing/validation, target selection and sha256 artifact
  verification, wire_version 1 typed JSON request/response envelopes,
  structured PluginError, and a libloading-based loader with host alloc/free,
  export registration and runtime ABI re-negotiation.
- marqdo-plugin-sdk (plugin side): mq_plugin_entry! macro, panic containment,
  safe byte-buffer wrappers, capability/logging context and JSON helpers; it
  depends only on the shared ABI crate.
- examples/plugin-demo: dependency-free C plugin (solver.add), manifest,
  build.sh that refreshes the artifact hash, README explaining that install,
  inspect and load are three different trust decisions.
- Tests: C plugin cross-compiled with cc and loaded, plus wrong ABI major,
  missing symbol/artifact, hash mismatch and malformed manifest cases.
This commit is contained in:
cflmy committed 2026-11-20 10:43:59 +08:00
1 parent f6c3efa849
commit 6da206a906
20 files changed
+5171 -1

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
//! Safe wrappers around the raw `MqBytes` / `MqOwnedBytes` ABI buffers.
//!
//! Ownership rules (see the canonical header):
//! - [`BytesRef`] is a borrowed, validated view of host input; it is only
//! valid for the call that produced it.
//! - [`HostBuffer`] is plugin output allocated with the host allocator and
//! handed back to the host, which frees it after copying.
use std::ffi::c_void;
use std::marker::PhantomData;
use std::ptr;
use marqdo_plugin_abi::abi::{MqBytes, MqHostApi, MqOwnedBytes};
use crate::PluginError;
/// Validated borrowed view of an ABI byte buffer (`MqBytes`).
pub struct BytesRef<'a> {
raw: MqBytes,
_marker: PhantomData<&'a [u8]>,
}
impl<'a> BytesRef<'a> {
/// Validate a raw borrowed buffer.
///
/// # Safety
///
/// If `raw.len > 0`, `raw.data` must point to `raw.len` initialized bytes
/// that stay alive for `'a`. Within the ABI, `'a` must not outlive the
/// call that produced the buffer.
pub unsafe fn from_raw(raw: MqBytes) -> Result<Self, PluginError> {
raw.validate()?;
Ok(Self {
raw,
_marker: PhantomData,
})
}
/// The underlying raw ABI view.
pub fn as_raw(&self) -> MqBytes {
self.raw
}
/// The bytes as a slice (valid for `'a`).
pub fn as_slice(&self) -> &'a [u8] {
if self.raw.len == 0 {
return &[];
}
// SAFETY: `from_raw` validated the pointer/length pair and `'a` is
// tied to the caller's borrow guarantee.
unsafe { std::slice::from_raw_parts(self.raw.data, self.raw.len) }
}
/// Length in bytes.
pub fn len(&self) -> usize {
self.raw.len
}
/// Whether the buffer is empty.
pub fn is_empty(&self) -> bool {
self.raw.len == 0
}
}
/// A byte buffer allocated with the host allocator and owned by the host.
///
/// The plugin writes its response/error wire into a [`HostBuffer`] and
/// transfers ownership through the ABI output parameter. The plugin must
/// never free this buffer itself; the host frees it after copying.
pub struct HostBuffer {
raw: MqOwnedBytes,
}
impl HostBuffer {
/// The empty buffer `{NULL, 0}`.
pub fn empty() -> Self {
Self {
raw: MqOwnedBytes::EMPTY,
}
}
/// Allocate a host buffer and copy `bytes` into it.
///
/// `host` must be the host API table provided to the entry point (the SDK
/// stores it for the plugin lifetime). Returns an out-of-memory error if
/// the host allocator returns NULL.
pub fn copy_from(host: &MqHostApi, bytes: &[u8]) -> Result<Self, PluginError> {
if bytes.is_empty() {
return Ok(Self::empty());
}
// SAFETY: host alloc/free pointers are non-NULL and valid for the
// plugin lifetime (validated during the entry call).
let pointer = unsafe { (host.alloc)(host.host_data, bytes.len()) };
if pointer.is_null() {
return Err(PluginError::invoke(
"out_of_memory",
"host allocator returned NULL for a plugin output buffer",
));
}
// SAFETY: pointer has bytes.len() writable bytes and does not overlap
// the source slice.
unsafe {
ptr::copy_nonoverlapping(bytes.as_ptr(), pointer as *mut u8, bytes.len());
}
Ok(Self {
raw: MqOwnedBytes::new(pointer as *mut u8, bytes.len()),
})
}
/// The raw owner-transfer buffer.
pub fn into_raw(self) -> MqOwnedBytes {
self.raw
}
/// Length in bytes.
pub fn len(&self) -> usize {
self.raw.len
}
/// Whether the buffer is empty.
pub fn is_empty(&self) -> bool {
self.raw.len == 0
}
}
/// Borrowed view of a capability reply or other host-allocated buffer.
///
/// The plugin copies what it needs and then must release the buffer with the
/// host allocator; use [`release_host_buffer`].
///
/// # Safety
///
/// `buffer` must be a host-allocated buffer that is still alive; the returned
/// slice must not outlive the release of that buffer.
pub unsafe fn reply_slice<'a>(buffer: MqOwnedBytes) -> &'a [u8] {
if buffer.len == 0 {
return &[];
}
// SAFETY: host-allocated buffer is initialized for `buffer.len` bytes; the
// caller must not retain the slice beyond the release point.
unsafe { std::slice::from_raw_parts(buffer.data, buffer.len) }
}
/// Release a host-allocated buffer through the host allocator.
///
/// # Safety
///
/// `buffer.data` must be NULL or a pointer returned by the host allocator
/// (`MqHostApi::alloc`) that has not been freed yet.
pub unsafe fn release_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) {
if buffer.data.is_null() {
return;
}
// SAFETY: alloc/free pair and non-NULL pointer per the caller contract.
unsafe { (host.free)(host.host_data, buffer.data as *mut c_void) };
}
+115
View File
@@ -0,0 +1,115 @@
//! Per-invocation context passed to plugin handlers.
//!
//! The context is valid only for the duration of one invocation. It exists to
//! carry host capabilities into the plugin: capability requests are answered
//! by the host's authorization layer and can never be escalated by plugin
//! code. Do not cache this value, its raw pointer or any capability token.
use marqdo_plugin_abi::abi::{
MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MAX_CAPABILITY_REPLY_BYTES,
};
use marqdo_plugin_abi::PluginError;
use crate::bytes;
/// Context for one plugin invocation.
pub struct CallContext {
raw: *mut MqCallContext,
host: &'static MqHostApi,
}
impl CallContext {
/// Wrap the host-provided context pointer.
///
/// # Safety
///
/// `raw` must be the context pointer provided by the host for the current
/// invocation, and `host` must be the validated host API table.
pub(crate) unsafe fn new(raw: *mut MqCallContext, host: &'static MqHostApi) -> Self {
Self { raw, host }
}
/// The host API table of this plugin instance.
pub fn host(&self) -> &'static MqHostApi {
self.host
}
/// Request an already-authorized host capability for this call.
///
/// `request` is a UTF-8 JSON capability request; the reply is opaque bytes
/// owned by the host. The SDK copies the reply and releases the host buffer.
pub fn capability_request(
&mut self,
name: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
if self.raw.is_null() {
return Err(PluginError::capability(
"missing_call_context",
"capability request requires an active invocation context",
));
}
let mut reply = MqOwnedBytes::EMPTY;
// SAFETY: raw context and host table are valid for this invocation.
let code = unsafe {
(self.host.request_capability)(
self.raw,
MqBytes::from_slice(name.as_bytes()),
MqBytes::from_slice(request),
&mut reply,
)
};
// SAFETY: host-allocated reply is initialized for `reply.len` bytes.
let reply_bytes = unsafe { reply.to_vec() };
// SAFETY: the host allocated `reply` with its allocator for us; release
// it exactly once after copying.
unsafe { bytes::release_host_buffer(self.host, reply) };
let reply_bytes = reply_bytes.map_err(|error| {
PluginError::capability(
"invalid_capability_reply",
"host capability reply violates the buffer contract",
)
.with_detail(error.to_string())
})?;
if reply_bytes.len() > MAX_CAPABILITY_REPLY_BYTES {
return Err(PluginError::capability(
"capability_reply_too_large",
format!(
"capability reply is {} bytes, limit is {MAX_CAPABILITY_REPLY_BYTES}",
reply_bytes.len()
),
));
}
if code != crate::result_code::OK {
return Err(PluginError::capability(
"capability_request_failed",
format!("host rejected capability request `{name}`"),
)
.with_detail(format!(
"result code `{}` ({code})",
crate::result_code::name(code)
)));
}
Ok(reply_bytes)
}
/// Best-effort structured log through the `log` capability.
pub fn log(&mut self, level: &str, message: &str) -> Result<(), PluginError> {
let request = serde_json::json!({"level": level, "message": message});
let request = serde_json::to_vec(&request).map_err(|error| {
PluginError::capability("log_encode_failed", "could not encode log request")
.with_detail(error.to_string())
})?;
let _ = self.capability_request("log", &request)?;
Ok(())
}
}
impl std::fmt::Debug for CallContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CallContext")
.field("raw", &self.raw)
.field("host", &(self.host as *const MqHostApi))
.finish()
}
}
+199
View File
@@ -0,0 +1,199 @@
//! Entry-point plumbing used by [`mq_plugin_entry!`](crate::mq_plugin_entry).
//!
//! These functions are the "runtime" of the SDK macro. They are public so the
//! macro can reference them through `$crate` from a plugin crate, but they are
//! not intended for direct use.
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicPtr, Ordering};
use marqdo_plugin_abi::abi::{
check_host_api, result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi,
MqPluginInvoke, ABI_MAJOR, ABI_MINOR, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
MAX_RESULT_WIRE_BYTES,
};
use marqdo_plugin_abi::{PluginError, WireResponse};
use crate::bytes::{release_host_buffer, HostBuffer};
use crate::call::CallContext;
use crate::HandlerFn;
/// Host API table captured by the entry point for the plugin lifetime.
static CURRENT_HOST: AtomicPtr<MqHostApi> = AtomicPtr::new(std::ptr::null_mut());
/// The host API table captured at load time, if a plugin is loaded.
pub(crate) fn current_host() -> Option<&'static MqHostApi> {
let pointer = CURRENT_HOST.load(Ordering::SeqCst);
if pointer.is_null() {
return None;
}
// SAFETY: the pointer was stored from a validated host table and the host
// guarantees it is valid for the plugin lifetime (single-threaded model).
Some(unsafe { &*pointer })
}
/// Initialize the ABI tables for the generated entry point.
///
/// # Safety
///
/// `host` and `plugin` must be the pointers provided by the host to
/// `mq_plugin_entry_v1` and must satisfy the header contract.
pub unsafe fn initialize(
host: *const MqHostApi,
plugin: *mut MqPluginApi,
metadata: &'static [u8],
) -> i32 {
if plugin.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: host pointer comes from the host and is checked before use.
let negotiated = match unsafe { check_host_api(host) } {
Ok(version) => version,
Err(_) => return result::ABI_MISMATCH,
};
if negotiated.major != ABI_MAJOR {
return result::ABI_MISMATCH;
}
CURRENT_HOST.store(host as *mut MqHostApi, Ordering::SeqCst);
// SAFETY: plugin table is host-provided, writable and valid for this call.
unsafe {
(*plugin).struct_size = std::mem::size_of::<MqPluginApi>() as u32;
(*plugin).abi_major = ABI_MAJOR;
(*plugin).abi_minor = ABI_MINOR;
(*plugin).plugin_metadata_wire = MqBytes::from_slice(metadata);
}
result::OK
}
/// Register one export through the host table.
///
/// # Safety
///
/// `host` must be the table validated by [`initialize`]; both strings must be
/// valid UTF-8 dotted export names/signatures declared in `plugin.yaml`.
pub unsafe fn register_export(
host: *const MqHostApi,
name: &str,
signature: &str,
invoke: MqPluginInvoke,
) -> i32 {
if host.is_null() || name.is_empty() || name.len() > MAX_EXPORT_NAME_BYTES {
return result::INVALID_ARGUMENT;
}
// SAFETY: host pointer is non-NULL and valid for the plugin lifetime.
let host = unsafe { &*host };
let signature_wire = match serde_json::to_vec(&serde_json::json!({"signature": signature})) {
Ok(bytes) => bytes,
Err(_) => return result::BAD_WIRE,
};
// SAFETY: host table was validated; strings outlive the call.
unsafe {
(host.register_function)(
host.host_data,
MqBytes::from_slice(name.as_bytes()),
MqBytes::from_slice(&signature_wire),
invoke,
)
}
}
/// Dispatch one invocation to a plugin handler and write the response.
///
/// # Safety
///
/// Must be called as the body of a `MqPluginInvoke` callback with the buffers
/// provided by the host for that invocation.
pub unsafe fn dispatch(
handler: HandlerFn,
ctx: *mut MqCallContext,
args: MqBytes,
result_out: *mut MqOwnedBytes,
error_out: *mut MqOwnedBytes,
) -> i32 {
if result_out.is_null() || error_out.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: output pointers are non-NULL host-provided out-parameters.
unsafe {
*result_out = MqOwnedBytes::EMPTY;
*error_out = MqOwnedBytes::EMPTY;
}
let Some(host) = current_host() else {
return result::INTERNAL;
};
// SAFETY: borrowed request buffer is valid for this callback.
let args_bytes = match unsafe { args.as_slice() } {
Ok(bytes) => bytes.to_vec(),
Err(_) => return result::INVALID_ARGUMENT,
};
// SAFETY: context pointer is the host-minted context for this invocation.
let mut context = unsafe { CallContext::new(ctx, host) };
let outcome = catch_unwind(AssertUnwindSafe(|| handler(&mut context, &args_bytes)));
let response = match outcome {
Ok(Ok(bytes)) => Ok(bytes),
Ok(Err(error)) => Err(error),
Err(_) => Err(PluginError::invoke(
"plugin_panic",
"plugin handler panicked; the panic was caught at the ABI boundary",
)),
};
match response {
Ok(bytes) => {
if bytes.len() > MAX_RESULT_WIRE_BYTES {
return write_error(
host,
error_out,
&PluginError::wire(
"result_too_large",
format!(
"plugin result is {} bytes, limit is {MAX_RESULT_WIRE_BYTES}",
bytes.len()
),
),
);
}
match HostBuffer::copy_from(host, &bytes) {
Ok(buffer) => {
// SAFETY: result_out is a valid out-parameter.
unsafe { *result_out = buffer.into_raw() };
result::OK
}
Err(error) => write_error(host, error_out, &error),
}
}
Err(error) => write_error(host, error_out, &error),
}
}
fn write_error(host: &'static MqHostApi, error_out: *mut MqOwnedBytes, error: &PluginError) -> i32 {
let encoded = match WireResponse::from_error(error).to_json_bytes() {
Ok(bytes) if bytes.len() <= MAX_ERROR_WIRE_BYTES => bytes,
_ => br#"{"wire_version":1,"kind":"response","error":{"kind":"invoke","code":"plugin_error","message":"plugin failed with an unencodable error"}}"#.to_vec(),
};
let code = match error.kind {
marqdo_plugin_abi::ErrorKind::Wire => result::BAD_WIRE,
marqdo_plugin_abi::ErrorKind::Capability => result::CAPABILITY,
marqdo_plugin_abi::ErrorKind::Unsupported => result::UNSUPPORTED,
_ => result::INTERNAL,
};
match HostBuffer::copy_from(host, &encoded) {
Ok(buffer) => {
// SAFETY: error_out is a valid out-parameter.
unsafe { *error_out = buffer.into_raw() };
code
}
Err(_) => result::OUT_OF_MEMORY,
}
}
/// Free a host-owned buffer (used by generated code/tests).
///
/// # Safety
///
/// `buffer` must have been allocated by the host allocator and not freed yet.
pub unsafe fn free_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) {
// SAFETY: caller guarantees the alloc/free pair.
unsafe { release_host_buffer(host, buffer) };
}
+143
View File
@@ -0,0 +1,143 @@
//! Rust SDK for writing Marqdo native plugins against plugin ABI v1.
//!
//! The SDK is the plugin-developer side of `include/marqdo_plugin_abi_v1.h`.
//! It hides the raw C layout behind safe wrappers and provides the
//! [`mq_plugin_entry!`] macro that exports the required
//! `mq_plugin_entry_v1` symbol:
//!
//! ```
//! use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value};
//!
//! fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
//! let request = marqdo_plugin_sdk::wire::decode_request(args)?;
//! let values = request.typed_args()?;
//! let a = marqdo_plugin_sdk::wire::int_arg(&values, "a")?;
//! let b = marqdo_plugin_sdk::wire::int_arg(&values, "b")?;
//! marqdo_plugin_sdk::wire::success(Some(Value::Int((a + b).into())))
//! }
//!
//! mq_plugin_entry! {
//! name: "demo.solver",
//! version: "0.1.0",
//! exports: {
//! "solver.add" => "($a: Int, $b: Int) -> Int" => add,
//! }
//! }
//! ```
//!
//! The SDK never depends on host-only crates: it only uses the shared ABI
//! types and the JSON wire envelope from `marqdo-plugin-abi`. Building a
//! plugin does not grant it any capability; authorization is a separate host
//! decision performed before loading.
#![deny(missing_docs)]
pub use marqdo_plugin_abi::abi::result as result_code;
pub use marqdo_plugin_abi::abi::{
MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, ABI_MAJOR,
ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
};
pub use marqdo_plugin_abi::{PluginError, Value, WireRequest, WireResponse, WIRE_VERSION};
pub mod bytes;
pub mod call;
pub mod entry;
pub mod wire;
pub use bytes::{BytesRef, HostBuffer};
pub use call::CallContext;
pub use wire::{
bool_arg, decode_request, error_response, int_arg, response_value, success, success_raw,
text_arg, value_arg,
};
/// Plugin handler signature.
///
/// A handler receives the per-call context (for capability requests and
/// logging) and the raw request envelope bytes, and returns the raw response
/// envelope bytes on success.
///
/// Use [`wire::decode_request`] and [`wire::success`] to build the response;
/// handlers should never panic: panics are caught by the SDK and converted
/// into a structured error, but the plugin process stays healthy only if the
/// panic does not corrupt plugin state.
pub type HandlerFn = fn(&mut CallContext, &[u8]) -> Result<Vec<u8>, PluginError>;
/// Declare a plugin and export `mq_plugin_entry_v1`.
///
/// ```ignore
/// marqdo_plugin_sdk::mq_plugin_entry! {
/// name: "demo.solver",
/// version: "0.1.0",
/// exports: {
/// "solver.add" => "($a: Int, $b: Int) -> Int" => add,
/// "solver.echo" => "($text: Text) -> Text" => echo,
/// }
/// }
/// ```
///
/// Each handler is a path (or non-capturing closure) with the [`HandlerFn`]
/// signature. The macro:
/// - validates the host ABI table (major version and `struct_size`),
/// - reports the plugin ABI version and a metadata envelope,
/// - registers every export and fails the load if registration fails.
#[macro_export]
macro_rules! mq_plugin_entry {
(
name: $name:literal,
version: $version:literal,
exports: {
$( $export_name:literal => $signature:literal => $handler:expr ),* $(,)?
}
) => {
/// Marqdo plugin ABI v1 entry point (generated by the SDK macro).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn mq_plugin_entry_v1(
host: *const $crate::MqHostApi,
plugin: *mut $crate::MqPluginApi,
) -> i32 {
const METADATA: &[u8] = concat!(
"{\"name\":\"", $name, "\",\"version\":\"", $version, "\"}"
)
.as_bytes();
let metadata: &'static [u8] = METADATA;
// SAFETY: the host provides the ABI tables per the header contract.
let init = unsafe { $crate::entry::initialize(host, plugin, metadata) };
if init != 0 {
return init;
}
$(
{
extern "C" fn invoke(
ctx: *mut $crate::MqCallContext,
args: $crate::MqBytes,
result: *mut $crate::MqOwnedBytes,
error: *mut $crate::MqOwnedBytes,
) -> i32 {
// Expand the user's handler expression in a safe
// context (also required by `macro_metavars_in_unsafe`).
let handler: $crate::HandlerFn = $handler;
// SAFETY: the host owns the invocation buffers; the SDK
// validates them and never retains them.
unsafe {
$crate::entry::dispatch(handler, ctx, args, result, error)
}
}
let export_name: &str = $export_name;
let signature: &str = $signature;
// SAFETY: host table is valid for the plugin lifetime and
// was validated by `initialize`.
let code =
unsafe { $crate::entry::register_export(host, export_name, signature, invoke) };
if code != 0 {
return code;
}
}
)*
$crate::result_code::OK
}
};
}
#[cfg(test)]
mod tests;
+245
View File
@@ -0,0 +1,245 @@
//! End-to-end SDK tests: run the macro-generated entry point against a tiny
//! in-process host table and invoke the registered export.
use std::ffi::c_void;
use std::ptr;
use marqdo_plugin_abi::abi::{
result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke,
ABI_MAJOR, ABI_MINOR,
};
use crate::wire;
use crate::{CallContext, PluginError, Value, WireRequest, WireResponse};
/// ABI v1 is single-threaded: the generated plugin stores the host table in a
/// process-global. Serialize tests that call the entry point so they do not
/// race (the SDK's own contract, not a test-only limitation).
static ABI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn abi_test_lock() -> std::sync::MutexGuard<'static, ()> {
ABI_TEST_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[derive(Default)]
struct TestHostState {
registrations: Vec<(String, String, MqPluginInvoke)>,
}
unsafe extern "C" fn test_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void {
const HEADER: usize = 16;
if size == 0 {
return ptr::null_mut();
}
let Ok(layout) = std::alloc::Layout::from_size_align(size + HEADER, 16) else {
return ptr::null_mut();
};
// SAFETY: non-zero layout.
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
return ptr::null_mut();
}
// SAFETY: allocation has room for the header.
unsafe { (base as *mut usize).write(size) };
// SAFETY: offset within the allocation.
unsafe { base.add(HEADER) as *mut c_void }
}
unsafe extern "C" fn test_free(_host_data: *mut c_void, pointer: *mut c_void) {
const HEADER: usize = 16;
if pointer.is_null() {
return;
}
// SAFETY: only pointers from test_alloc are freed.
unsafe {
let base = (pointer as *mut u8).sub(HEADER);
let size = (base as *const usize).read();
std::alloc::dealloc(
base,
std::alloc::Layout::from_size_align_unchecked(size + HEADER, 16),
);
}
}
unsafe extern "C" fn test_register(
host_data: *mut c_void,
export_name: MqBytes,
signature_wire: MqBytes,
invoke: MqPluginInvoke,
) -> i32 {
if host_data.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: host_data points at TestHostState for the test.
let state = unsafe { &mut *(host_data as *mut TestHostState) };
// SAFETY: buffers are valid for this callback.
let name = match unsafe { export_name.as_slice() } {
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
Err(_) => return result::INVALID_ARGUMENT,
};
// SAFETY: buffers are valid for this callback.
let signature = match unsafe { signature_wire.as_slice() } {
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
Err(_) => return result::INVALID_ARGUMENT,
};
state.registrations.push((name, signature, invoke));
result::OK
}
unsafe extern "C" fn test_capability(
_ctx: *mut MqCallContext,
_name: MqBytes,
_request: MqBytes,
reply: *mut MqOwnedBytes,
) -> i32 {
if !reply.is_null() {
// SAFETY: output pointer is non-NULL.
unsafe { *reply = MqOwnedBytes::EMPTY };
}
result::UNSUPPORTED
}
fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
let request = wire::decode_request(args)?;
let values = request.typed_args()?;
let a = wire::int_arg(&values, "a")?;
let b = wire::int_arg(&values, "b")?;
wire::success(Some(Value::Int((a + b).into())))
}
crate::mq_plugin_entry! {
name: "sdk.test",
version: "0.1.0",
exports: {
"test.add" => "($a: Int, $b: Int) -> Int" => add,
}
}
struct TestHost {
_state: Box<TestHostState>,
api: MqHostApi,
}
fn test_host() -> TestHost {
let mut state = Box::new(TestHostState::default());
let api = MqHostApi {
struct_size: std::mem::size_of::<MqHostApi>() as u32,
abi_major: ABI_MAJOR,
abi_minor: ABI_MINOR,
host_data: (&mut *state) as *mut TestHostState as *mut c_void,
alloc: test_alloc,
free: test_free,
register_function: test_register,
request_capability: test_capability,
};
TestHost { _state: state, api }
}
#[test]
fn macro_exports_and_registers() {
let _guard = abi_test_lock();
let host = test_host();
let mut plugin_api = MqPluginApi::host_initialized();
// SAFETY: test host table follows the ABI contract.
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
assert_eq!(code, result::OK);
assert_eq!(plugin_api.abi_major, ABI_MAJOR);
assert_eq!(plugin_api.abi_minor, ABI_MINOR);
// SAFETY: metadata is plugin static data valid during the entry call.
let metadata = unsafe { plugin_api.plugin_metadata_wire.as_slice() }.expect("metadata");
let metadata = String::from_utf8_lossy(metadata);
assert!(metadata.contains("\"name\":\"sdk.test\""));
assert_eq!(host._state.registrations.len(), 1);
assert_eq!(host._state.registrations[0].0, "test.add");
assert!(host._state.registrations[0]
.1
.contains("($a: Int, $b: Int) -> Int"));
}
#[test]
fn registered_export_roundtrips_wire_request() {
let _guard = abi_test_lock();
let host = test_host();
let mut plugin_api = MqPluginApi::host_initialized();
// SAFETY: test host table follows the ABI contract.
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
assert_eq!(code, result::OK);
let request = WireRequest::new("test.add")
.with_arg("a", &Value::Int(20_i64.into()))
.with_arg("b", &Value::Int(22_i64.into()));
let request_bytes = request.to_json_bytes().expect("request");
let (_, _, invoke) = &host._state.registrations[0];
let mut result_buffer = MqOwnedBytes::EMPTY;
let mut error_buffer = MqOwnedBytes::EMPTY;
// SAFETY: invoke is the SDK callback; null ctx is fine because the handler
// does not request a capability. Buffers are valid out-parameters.
let code = unsafe {
invoke(
ptr::null_mut(),
MqBytes::from_slice(&request_bytes),
&mut result_buffer,
&mut error_buffer,
)
};
assert_eq!(code, result::OK);
assert!(error_buffer.is_empty());
// SAFETY: result buffer was allocated by test_alloc for us.
let response_bytes = unsafe { result_buffer.to_vec() }.expect("result");
// SAFETY: allocated by test_alloc; release exactly once.
unsafe { test_free(ptr::null_mut(), result_buffer.data as *mut c_void) };
let response = WireResponse::from_json_bytes(&response_bytes).expect("response");
assert_eq!(
response.typed_value().expect("typed"),
Some(Value::Int(42_i64.into()))
);
}
#[test]
fn handler_error_is_written_as_error_envelope() {
let _guard = abi_test_lock();
let host = test_host();
let mut plugin_api = MqPluginApi::host_initialized();
// SAFETY: test host table follows the ABI contract.
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
assert_eq!(code, result::OK);
let request = WireRequest::new("test.add"); // missing arguments
let request_bytes = request.to_json_bytes().expect("request");
let (_, _, invoke) = &host._state.registrations[0];
let mut result_buffer = MqOwnedBytes::EMPTY;
let mut error_buffer = MqOwnedBytes::EMPTY;
// SAFETY: invoke is the SDK callback with valid out-parameters.
let code = unsafe {
invoke(
ptr::null_mut(),
MqBytes::from_slice(&request_bytes),
&mut result_buffer,
&mut error_buffer,
)
};
assert_ne!(code, result::OK);
assert!(result_buffer.is_empty());
// SAFETY: error buffer was allocated by test_alloc for us.
let error_bytes = unsafe { error_buffer.to_vec() }.expect("error");
// SAFETY: allocated by test_alloc; release exactly once.
unsafe { test_free(ptr::null_mut(), error_buffer.data as *mut c_void) };
let response = WireResponse::from_error_json_bytes(&error_bytes).expect("decode");
let error = response.into_result().expect_err("error");
assert_eq!(error.code, "missing_argument");
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Invoke);
}
#[test]
fn initialization_rejects_bad_host_major() {
let _guard = abi_test_lock();
let mut host = test_host();
host.api.abi_major = 2;
let mut plugin_api = MqPluginApi::host_initialized();
// SAFETY: intentionally inconsistent host table; entry must reject it.
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
assert_eq!(code, result::ABI_MISMATCH);
}
+98
View File
@@ -0,0 +1,98 @@
//! Wire envelope helpers for plugin handlers.
//!
//! The canonical envelope is defined by `marqdo-plugin-abi` and documented in
//! `spec/value-wire.md`: UTF-8 JSON, `wire_version == 1`, type-tagged values.
//! Handlers normally do:
//!
//! ```ignore
//! fn add(ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
//! let request = decode_request(args)?;
//! let values = request.typed_args()?;
//! success(Some(Value::Int((int_arg(&values, "a")? + int_arg(&values, "b")?).into())))
//! }
//! ```
use std::collections::BTreeMap;
use marqdo_plugin_abi::{
bool_from_value, int_from_value, text_from_value, PluginError, Value, WireRequest, WireResponse,
};
use serde_json::Value as Json;
/// Decode and validate a request envelope received from the host.
pub fn decode_request(bytes: &[u8]) -> Result<WireRequest, PluginError> {
WireRequest::from_json_bytes(bytes)
}
/// Look up a typed argument by name.
pub fn value_arg<'a>(
values: &'a BTreeMap<String, Value>,
name: &str,
) -> Result<&'a Value, PluginError> {
values.get(name).ok_or_else(|| {
PluginError::invoke(
"missing_argument",
format!("required argument `{name}` is missing"),
)
})
}
/// Look up an integer argument (must fit in `i64`).
pub fn int_arg(values: &BTreeMap<String, Value>, name: &str) -> Result<i64, PluginError> {
let value = value_arg(values, name)?;
int_from_value(value).ok_or_else(|| {
PluginError::invoke(
"invalid_argument_type",
format!("argument `{name}` must be an Int"),
)
})
}
/// Look up a text argument.
pub fn text_arg<'a>(
values: &'a BTreeMap<String, Value>,
name: &str,
) -> Result<&'a str, PluginError> {
let value = value_arg(values, name)?;
text_from_value(value).ok_or_else(|| {
PluginError::invoke(
"invalid_argument_type",
format!("argument `{name}` must be Text"),
)
})
}
/// Look up a boolean argument.
pub fn bool_arg(values: &BTreeMap<String, Value>, name: &str) -> Result<bool, PluginError> {
let value = value_arg(values, name)?;
bool_from_value(value).ok_or_else(|| {
PluginError::invoke(
"invalid_argument_type",
format!("argument `{name}` must be Bool"),
)
})
}
/// Encode a successful response envelope.
pub fn success(value: Option<Value>) -> Result<Vec<u8>, PluginError> {
success_raw(value.as_ref().map(marqdo_plugin_abi::to_wire_json))
}
/// Encode a successful response with an already-encoded type-tagged value.
pub fn success_raw(value: Option<Json>) -> Result<Vec<u8>, PluginError> {
WireResponse::success_raw(value).to_json_bytes()
}
/// Encode an error response envelope.
///
/// The SDK's dispatch layer uses this automatically when a handler returns an
/// error; handlers may also build custom error responses with it.
pub fn error_response(error: &PluginError) -> Result<Vec<u8>, PluginError> {
WireResponse::from_error(error).to_json_bytes()
}
/// Decode a response value back into a typed [`Value`] (useful in tests and
/// plugins that compose calls).
pub fn response_value(bytes: &[u8]) -> Result<Option<Value>, PluginError> {
WireResponse::from_json_bytes(bytes)?.typed_value()
}