salamandr-plugin-sdk 0.3.0

Write Salamandr helpdesk extensions in Rust: safe typed wrappers for every host capability, the fetch_context wire contract, and an in-process mock host for testing.
Documentation
//! Safe Rust SDK for writing Salamandr WASM extensions — see
//! backend/internal/extwasm's package doc comment (doc.go) for the
//! manifest/scopes/host-function design this implements the guest side
//! of, and abi.go for the exact alloc/dealloc/handle wire contract.
//!
//! # What a plugin can do
//!
//! Exactly four things, each behind a scope its manifest.toml declares
//! and a tenant admin approves:
//!
//! | capability | module | scope |
//! |---|---|---|
//! | one HTTP call at a time | [`http_fetch`] | `http_hosts` |
//! | tenant-supplied config/secrets | [`get_config`] | `config_keys` |
//! | a small private key/value store | [`kv_get`]/[`kv_set`]/[`kv_delete`]/[`kv_list`] | `kv` |
//! | the tenant's own helpdesk data | [`core`] | `core` |
//!
//! plus [`log`], which needs no scope. There is no filesystem, no
//! environment, no clock but the host's, no sockets, and no WASI.
//!
//! # Writing a plugin
//!
//! Start from `sdk/examples/hello-crm`, a complete working plugin — this
//! is the same code with the vendor call cut out. The crate's README.md
//! is the full guide (manifest schema, build, install, testing).
//!
//! ```ignore
//! use salamandr_plugin_sdk::{plugin, ContextBlock, ContextRequest, ContextResult};
//!
//! fn fetch_context(req: ContextRequest) -> ContextResult {
//!     let Some(email) = req.primary_email() else { return Ok(vec![]) };
//!     // `?` works directly on host calls — HostError converts into
//!     // OpError, and a host-side "not found" stays a not-found.
//!     let key = salamandr_plugin_sdk::get_config("api_key")?.unwrap_or_default();
//!     Ok(vec![ContextBlock::new("Acme CRM")
//!         .field("Email", email)
//!         .field("Key configured", if key.is_empty() { "no" } else { "yes" })])
//! }
//!
//! plugin! {
//!     name: "my-plugin",
//!     version: env!("CARGO_PKG_VERSION"),
//!     // fetch_context goes in context_ops, never ops — see below.
//!     context_ops: {
//!         "fetch_context" => fetch_context,
//!     }
//! }
//! ```
//!
//! # `ops` vs `context_ops`
//!
//! Two blocks, two wire shapes, and picking the wrong one is the single
//! mistake in this SDK that compiles, installs and then silently
//! misbehaves:
//!
//!   - **`context_ops`** — the host decodes your answer *directly* into
//!     its own Go type. This is what `"fetch_context"` (and any
//!     `"fetch_contact"`-style typed convenience op) must use. Almost
//!     every community plugin uses only this block.
//!   - **`ops`** — the answer is wrapped in an internally-tagged
//!     `Outcome` (`{"kind":"ok","data":…}`) that only a Go caller written
//!     to unwrap it can read. It exists for first-party connectors whose
//!     own Go package decodes them (internal/ecommerce/providers/woocommerce,
//!     internal/extension/providers/hubspot). A community plugin has no such caller.
//!
//! Registering `fetch_context` under `ops` is refused at install time
//! rather than discovered in production — `describe` reports which block
//! each op came from (see [`Registry::context_names`]).
//!
//! # Testing without a server
//!
//! [`testing::MockHost`] stands in for the host on non-wasm targets, so
//! `cargo test` runs your operations natively — with your real
//! manifest's scopes enforced:
//!
//! ```ignore
//! let _host = MockHost::from_manifest(include_str!("../manifest.toml"))
//!     .config("api_key", "test-key")
//!     .http(|req| Ok(HttpResponse { status: 200, body: "{}".into(), ..Default::default() }))
//!     .install();
//! assert_eq!(fetch_context(request).unwrap().len(), 1);
//! ```
//!
//! # Why the [`plugin!`] macro is the whole export surface
//!
//! Rust exports whatever is marked `#[no_mangle] extern "C"`, wherever
//! that happens to be written — so a plugin hand-rolling the ABI has no
//! structural reason its WASM export table contains only what its author
//! meant to expose. This crate makes that mistake unreachable:
//!
//!   - The **only** four functions a plugin built with this SDK ever
//!     exports are `alloc`, `dealloc`, `handle` and `describe`, all
//!     generated by [`plugin!`]. `#[no_mangle]` should not appear
//!     anywhere in a plugin's own source.
//!   - An operation is reachable from Go **only** by appearing in that
//!     macro's `ops` block. A plain Rust function is just a function.
//!     "What does this plugin expose" is answered by reading one list.
//!   - That same list is what the generated `describe` export reports,
//!     so the host verifies a manifest's `entrypoints` against what the
//!     binary actually registered — at install time, not when a customer
//!     hits the missing operation.
//!   - Every host call is a safe, typed wrapper. An op author never
//!     touches a raw pointer or hand-encodes the wire envelope.

mod abi;
pub mod calendar_sync;
pub mod channel;
pub mod chatops;
pub mod connector;
mod context;
pub mod core;
mod error;
pub mod host;
mod persistent;
mod registry;
#[cfg(not(target_arch = "wasm32"))]
pub mod testing;

#[doc(hidden)]
pub use abi::{sdk_alloc, sdk_dealloc};
pub use context::{
    Action, ActionField, ActionOutcome, ActionRequest, ActionResult, Actor, ContextBlock, ContextRequest,
    ContextResult, Field, FieldOption, FieldSpec, TicketRef, FIELD_DATE, FIELD_MULTISELECT, FIELD_NUMBER,
    FIELD_SELECT, FIELD_TEXT, FIELD_TEXTAREA, RICH_TEXT_FORMAT_JIRA_WIKI, RICH_TEXT_FORMAT_MARKDOWN,
};
pub use error::{code, HostError, OpError};
pub use host::{
    core_call, get_config, http_fetch, http_upload, kv_delete, kv_get, kv_list, kv_set, log, oauth_fetch,
    richtext_to_jira_wiki, richtext_to_markdown, self_info, ws_send, HttpRequest, HttpResponse, OAuthFetchRequest,
    SelfInfo, UploadRequest,
};
pub use persistent::{
    PersistentConnectRequest, PersistentConnectResult, PersistentReceiveRequest, PersistentReceiveResponse,
    PersistentReceiveResult,
};
pub use registry::{Descriptor, Registry, ABI_VERSION};
#[doc(hidden)]
pub use registry::{describe_call, handle_call};

/// plugin! generates the **only** four functions a Salamandr WASM plugin
/// ever exports — `alloc`, `dealloc`, `handle` and `describe` — from one
/// declarative list of operations. See this crate's doc comment for why
/// that list, rather than a scattering of `#[no_mangle]`s, is the design.
///
/// ```ignore
/// plugin! {
///     name: "woocommerce",
///     version: env!("CARGO_PKG_VERSION"),
///     ops: {
///         "get_order"     => ops::get_order,
///         "create_refund" => ops::create_refund,
///     }
/// }
/// ```
///
/// `name`/`version` are optional and purely descriptive — they travel in
/// `describe`'s answer so an operator inspecting an installed binary can
/// see what it claims to be. Each op's handler is any
/// `Fn(In) -> Result<Out, OpError>` where `In: Deserialize` and
/// `Out: Serialize`.
///
/// `context_ops` is a second, optional block for anything the *host*
/// calls directly and unmarshals with no knowledge of this SDK's own
/// wire convention — `"fetch_context"` (required on every plugin the
/// normal community-extension path installs) and any
/// internal/crm-family stronger-typed convenience op
/// (`"fetch_contact"`, ...). See [`Registry::context_op`] for exactly
/// how its wire shape differs from `ops`' and why the two must not be
/// mixed up:
///
/// ```ignore
/// plugin! {
///     name: "hubspot",
///     version: env!("CARGO_PKG_VERSION"),
///     ops: {
///         "get_order" => ops::get_order,
///     },
///     context_ops: {
///         "fetch_context" => ops::fetch_context,
///         "fetch_contact" => ops::fetch_contact,
///     }
/// }
/// ```
/// A third, optional `action_ops` block registers **executable actions**
/// — the write half of a context tool. An op there is reachable from a
/// button an agent clicks in the ticket sidebar (see [`Action::run`] and
/// [`ActionRequest`]), and *only* from there: the host refuses to run an
/// op that isn't in this block, so the ops that answer questions never
/// become clickable by accident. Blocks are written in the order
/// `ops`, `context_ops`, `action_ops`; any subset may be omitted.
///
/// ```ignore
/// plugin! {
///     name: "acme-crm",
///     version: env!("CARGO_PKG_VERSION"),
///     context_ops: {
///         "fetch_context" => ops::fetch_context,
///     },
///     action_ops: {
///         "log_note" => ops::log_note,
///     }
/// }
/// ```
///
/// A `kind = "channel"` manifest (a ticket-creation channel connector,
/// not a context tool) uses `channel_ops` instead — the fixed pair
/// `"channel_receive"`/`"channel_send"` (see [`crate::channel`]),
/// optionally alongside a plain `ops` block for anything else the plugin
/// wants to expose. Never combined with `context_ops`/`action_ops`: a
/// channel plugin has no ticket requester to answer a context lookup
/// for.
///
/// ```ignore
/// plugin! {
///     name: "custom-webhook",
///     version: env!("CARGO_PKG_VERSION"),
///     channel_ops: {
///         "channel_receive" => ops::channel_receive,
///         "channel_send" => ops::channel_send,
///     }
/// }
/// ```
///
/// A `kind = "chatops"` manifest (a team-chat mirror connector) uses
/// `chatops_ops` instead — the fixed trio `"chatops_post_root"`/
/// `"chatops_post_reply"`/`"chatops_receive"` (see [`crate::chatops`]),
/// plus optionally `"chatops_search_members"`/`"chatops_list_channels"`/
/// `"chatops_message_url"`. Never combined with `context_ops`/
/// `action_ops`, same reasoning as `channel_ops`.
///
/// ```ignore
/// plugin! {
///     name: "generic-chatops",
///     version: env!("CARGO_PKG_VERSION"),
///     chatops_ops: {
///         "chatops_post_root" => ops::post_root,
///         "chatops_post_reply" => ops::post_reply,
///         "chatops_receive" => ops::receive,
///     }
/// }
/// ```
///
/// A `kind = "connector"` manifest (an OAuth video-conferencing
/// connector) uses `connector_ops` instead — the fixed trio
/// `"connector_create_meeting"`/`"connector_update_meeting"`/
/// `"connector_delete_meeting"` (see [`crate::connector`]). Never
/// combined with `context_ops`/`action_ops`, same reasoning as
/// `channel_ops`/`chatops_ops`.
///
/// ```ignore
/// plugin! {
///     name: "generic-video",
///     version: env!("CARGO_PKG_VERSION"),
///     connector_ops: {
///         "connector_create_meeting" => ops::create_meeting,
///         "connector_update_meeting" => ops::update_meeting,
///         "connector_delete_meeting" => ops::delete_meeting,
///     }
/// }
/// ```
#[macro_export]
macro_rules! plugin {
    // The one arm that generates code. Everything below normalizes onto
    // it, so there is exactly one definition of what a plugin exports.
    (@build $name:expr, $version:expr,
        ops: { $($op:literal => $handler:expr),* $(,)? },
        context_ops: { $($cop:literal => $chandler:expr),* $(,)? },
        action_ops: { $($aop:literal => $ahandler:expr),* $(,)? },
        channel_ops: { $($chop:literal => $chhandler:expr),* $(,)? },
        chatops_ops: { $($ctop:literal => $cthandler:expr),* $(,)? },
        connector_ops: { $($cnop:literal => $cnhandler:expr),* $(,)? } $(,)?
    ) => {
        // Not `pub`: nothing outside this crate may reach the registry,
        // and the generated exports below are the only callers.
        #[doc(hidden)]
        fn __salamandr_build_registry() -> $crate::Registry {
            $crate::Registry::new()
                $(.op($op, $handler))*
                $(.context_op($cop, $chandler))*
                $(.action_op($aop, $ahandler))*
                $(.channel_op($chop, $chhandler))*
                $(.chatops_op($ctop, $cthandler))*
                $(.connector_op($cnop, $cnhandler))*
        }

        #[no_mangle]
        pub extern "C" fn alloc(size: u32) -> u32 {
            $crate::sdk_alloc(size)
        }

        #[no_mangle]
        pub extern "C" fn dealloc(ptr: u32, size: u32) {
            $crate::sdk_dealloc(ptr, size)
        }

        #[no_mangle]
        pub extern "C" fn handle(op_ptr: u32, op_len: u32, in_ptr: u32, in_len: u32) -> u64 {
            $crate::handle_call(op_ptr, op_len, in_ptr, in_len, __salamandr_build_registry)
        }

        #[no_mangle]
        pub extern "C" fn describe() -> u64 {
            $crate::describe_call($name, $version, __salamandr_build_registry)
        }
    };

    // Block normalization: fill in whichever of the six blocks the
    // author left out. Written out rather than munched so a misspelled
    // block name is a "no rules expected this token" at the call site
    // instead of silently registering nothing.
    //
    // channel_ops/chatops_ops/connector_ops are each only normalized
    // paired with ops or alone: a kind="channel"/kind="chatops"/
    // kind="connector" manifest's fixed entrypoints have no reason to
    // sit alongside context_ops/action_ops — those answer
    // extension.ContextProvider's "what does the outside system know
    // about this requester" shape, which none of those three plugin
    // kinds (each keyed by something other than a ticket's requester)
    // ever implements. Mixing them is not a combination this macro
    // supports; a plugin needing both is two plugins.
    (@blocks $n:expr, $v:expr,
        ops: { $($o:tt)* }, context_ops: { $($c:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: { $($c)* }, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, context_ops: { $($c:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: { $($c)* }, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, context_ops: { $($c:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: { $($c)* }, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, channel_ops: { $($ch:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: { $($ch)* }, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, chatops_ops: { $($ct:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: { $($ct)* }, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, connector_ops: { $($cn:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: { $($cn)* });
    };
    (@blocks $n:expr, $v:expr, ops: { $($o:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, context_ops: { $($c:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: { $($c)* }, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, action_ops: { $($a:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, channel_ops: { $($ch:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: { $($ch)* }, chatops_ops: {}, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, chatops_ops: { $($ct:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: { $($ct)* }, connector_ops: {});
    };
    (@blocks $n:expr, $v:expr, connector_ops: { $($cn:tt)* } $(,)?) => {
        $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: { $($cn)* });
    };

    // Public entry points: name/version are optional, everything after
    // them is blocks.
    (name: $name:expr, version: $version:expr, $($blocks:tt)*) => {
        $crate::plugin!(@blocks $name, $version, $($blocks)*);
    };
    ($($blocks:tt)*) => {
        $crate::plugin!(@blocks "", "", $($blocks)*);
    };
}