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
//! The two error types a plugin author actually handles: [`HostError`]
//! (a host function refused or couldn't complete) and [`OpError`] (what
//! the plugin's own operation reports back to Go).

use serde::Serialize;

/// Well-known `code` values a host function can set on a failed envelope.
/// Matching on these rather than on the message text is deliberate: the
/// human message is free to be reworded without that silently becoming a
/// guest-visible behavior change.
pub mod code {
    /// host_get_config: the tenant never set this key.
    pub const NOT_SET: &str = "not_set";
    /// host_kv_get / host_core: the row or key does not exist.
    pub const NOT_FOUND: &str = "not_found";
}

/// HostError carries both the human message and the machine `code` a
/// host_* failure set (see hostfuncs.go's `envelope.Code`).
#[derive(Clone, PartialEq, Eq)]
pub struct HostError {
    pub code: String,
    pub message: String,
}

impl HostError {
    pub(crate) fn new(message: impl Into<String>) -> Self {
        Self { code: String::new(), message: message.into() }
    }

    /// is_not_found is the check every `Option`-returning wrapper in this
    /// crate makes — exposed because a plugin calling the untyped
    /// [`crate::host::core_call`] path needs the same test.
    pub fn is_not_found(&self) -> bool {
        self.code == code::NOT_FOUND
    }
}

impl std::fmt::Display for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.code.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "{} ({})", self.message, self.code)
        }
    }
}

// Debug renders the same text as Display so `unwrap()`/`expect()` in a
// plugin's own code print something a human can act on — the derived
// struct dump is unreadable in a wasm log line, which is the only place
// a plugin author will ever see it.
impl std::fmt::Debug for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "HostError({self})")
    }
}

impl std::error::Error for HostError {}

/// OpError is what a registered operation returns on failure. The two
/// "sentinel" variants map to internal/extwasm's own well-known envelope
/// codes (see adapter.go's CodeNotConfigured/CodeTicketTypeNotEnabled),
/// so a plugin implementing extension.ContextProvider's fetch_context
/// gets the same cross-provider errors.Is behavior a native Go provider
/// would. Everything else rides inside a successful envelope as an
/// [`Outcome`] instead — see [`crate::Registry::op`].
pub enum OpError {
    /// This tenant hasn't configured the extension yet — maps to
    /// internal/extension.ErrNotConfigured on the Go side.
    NotConfigured,
    /// This ticket's type isn't in the extension's allow-list — maps to
    /// internal/extension.ErrTicketTypeNotEnabled.
    TicketTypeNotEnabled,
    /// The requested resource doesn't exist — a business-level "not
    /// found," not an ABI failure (see Outcome::NotFound).
    NotFound,
    /// A paginated collection op was asked for a page/cursor past the
    /// end — many REST APIs answer that with an error rather than an
    /// empty page, and a host-side pagination loop needs to tell that
    /// apart from a real failure to know when to stop cleanly (see
    /// internal/ecommerce/providers/woocommerce's isPastLastPage, the concept this
    /// generalizes: WordPress's REST layer reports "you asked for a page
    /// beyond the end" as a 400 with a specific error code rather than
    /// `[]`).
    EndOfCollection(String),
    /// The upstream API rate-limited this request. retry_after is the
    /// raw Retry-After header value, if the response carried one — left
    /// unparsed so the host-side retry logic (which already knows how to
    /// read it, see internal/platform/httpretry) doesn't need a second
    /// implementation of that parsing here.
    RateLimited { retry_after: Option<String> },
    /// A failure safe to retry blindly (5xx, network) — the operation
    /// itself decides this, since only it knows whether the underlying
    /// call was idempotent (the same distinction
    /// internal/ecommerce/providers/woocommerce/client.go's retryableIfRead makes today).
    Transient(String),
    /// Anything else. Never retried.
    Other(String),
}

// Display/Debug so `?`, `expect()` and `assert!` work on an op's own
// Result in a plugin's tests — without them the very first line a plugin
// author writes in a #[test] fails to compile. Debug renders the same
// text for the same reason HostError's does: the derived dump is
// unreadable in the one place it shows up.
impl std::fmt::Display for OpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OpError::NotConfigured => write!(f, "not configured"),
            OpError::TicketTypeNotEnabled => write!(f, "context is not enabled for this ticket type"),
            OpError::NotFound => write!(f, "not found"),
            OpError::EndOfCollection(message) => write!(f, "end of collection: {message}"),
            OpError::RateLimited { retry_after } => match retry_after {
                Some(after) => write!(f, "rate limited (retry after {after})"),
                None => write!(f, "rate limited"),
            },
            OpError::Transient(message) => write!(f, "transient failure: {message}"),
            OpError::Other(message) => write!(f, "{message}"),
        }
    }
}

impl std::fmt::Debug for OpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "OpError({self})")
    }
}

impl std::error::Error for OpError {}

// A host call failing inside an op is overwhelmingly "give up and report
// it" — this is what lets an op body use `?` on http_fetch/get_config/
// core::* instead of a match arm per call. A host-side "not found" keeps
// its meaning across the conversion; nothing else can be classified any
// finer here, since only the op knows whether its own call was idempotent
// (hence OpError::Transient stays something an op opts into explicitly).
impl From<HostError> for OpError {
    fn from(e: HostError) -> Self {
        if e.is_not_found() {
            return OpError::NotFound;
        }
        OpError::Other(e.to_string())
    }
}

/// Outcome is the tagged shape a successful operation call's `data`
/// carries — internally tagged on "kind" (`{"kind":"ok","data":...}`,
/// `{"kind":"rate_limited","retry_after":...}`, ...) so the host side can
/// pattern-match on one flat JSON object. Business-level failures (not
/// found, rate limited, transient) travel this way rather than as an
/// envelope-level `ok:false`, because only NotConfigured/
/// TicketTypeNotEnabled are meant to flow through the generic
/// errors.Is-mappable sentinel path — everything else is this operation's
/// own business, which the caller (internal/ecommerce/providers/woocommerce/service.go, for
/// example) interprets with its own domain knowledge (an HTTP retry loop,
/// a pagination loop, ...).
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum Outcome<T> {
    Ok { data: T },
    NotFound,
    EndOfCollection { message: String },
    RateLimited { retry_after: Option<String> },
    Transient { message: String },
    Error { message: String },
}