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 wire contract of `channel_receive`/`channel_send` — the fixed
//! entrypoint pair a `kind = "channel"` plugin must implement (see
//! `extwasm.KindChannel`'s manifest requirement).
//!
//! These types are a field-for-field mirror of
//! internal/extwasm/adapter.go's `ReceiveRequest`/
//! `InboundMessage`/`ReceiveResult`/`SendRequest`.
//! Parity is pinned from the Go side by
//! internal/extwasm/sdkcontract_test.go, the same way [`crate::context`]'s
//! types are.
//!
//! # `channel_receive` is a pure function
//!
//! It answers "what messages does this webhook payload contain", nothing
//! more — no ticket is created or touched by the call itself. The host's
//! own channel webhook dispatcher ingests each returned
//! [`InboundMessage`] afterwards, at most once per message
//! returned. This is deliberate: a plugin's answer can never create
//! *more* tickets than the messages it actually reports, regardless of
//! what the plugin's own code does internally.
//!
//! It can create fewer, in exactly one case: the tenant's own bot flow
//! (internal/botflow) answers a message that would have opened a new
//! ticket, the same way it does for the native Telegram/WhatsApp
//! adapters. That is a tenant's configuration choice, invisible from here
//! and nothing a plugin needs to handle.
//!
//! # `channel_send` performs the delivery itself
//!
//! Unlike `channel_receive`, `channel_send`'s handler is expected to call
//! [`crate::http_fetch`] itself (its manifest's `http_hosts` scope must
//! allow the vendor's API) — the host only tells it *what* to send, not
//! *how*.
//!
//! ```no_run
//! use salamandr_plugin_sdk::channel::{InboundMessage, ReceiveRequest, ReceiveResult, ReceiveResultData};
//!
//! fn channel_receive(req: ReceiveRequest) -> ReceiveResult {
//!     // A trivial custom-webhook connector: {"from": "...", "name": "...", "text": "..."}.
//!     let payload: serde_json::Value = serde_json::from_str(&req.body)
//!         .map_err(|e| salamandr_plugin_sdk::OpError::Other(format!("invalid payload: {e}")))?;
//!     let from = payload["from"].as_str().unwrap_or_default().to_string();
//!     Ok(ReceiveResultData {
//!         messages: vec![InboundMessage {
//!             external_identity: from.clone(),
//!             display_name: payload["name"].as_str().unwrap_or(&from).to_string(),
//!             body: payload["text"].as_str().unwrap_or_default().to_string(),
//!             external_message_id: None,
//!             attachments: vec![],
//!         }],
//!     })
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// ReceiveRequest is what the host passes to `channel_receive` —
/// the inbound webhook request, normalized. `body` is UTF-8 verbatim
/// unless `body_encoding` is `"base64"` (a vendor sending a binary
/// payload — protobuf, a raw signature blob, ...).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ReceiveRequest {
    #[serde(default)]
    pub method: String,
    #[serde(default)]
    pub path: String,
    #[serde(default)]
    pub query: String,
    #[serde(default)]
    pub headers: HashMap<String, Vec<String>>,
    #[serde(default)]
    pub body: String,
    #[serde(default)]
    pub body_encoding: String,
}

impl ReceiveRequest {
    /// header reads the first value of a header, case-sensitively — the
    /// host forwards header names exactly as Go's `net/http` canonicalized
    /// them (e.g. `"X-Hub-Signature-256"`), so match that casing.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.first()).map(String::as_str)
    }

    /// is_binary_body reports whether `body` is base64-encoded
    /// (`body_encoding == "base64"`, set by the host when the raw payload
    /// wasn't valid UTF-8) rather than the vendor's text/JSON verbatim.
    /// This crate ships no base64 decoder — pull one into your own plugin
    /// crate if you need it; almost every webhook payload is text.
    pub fn is_binary_body(&self) -> bool {
        self.body_encoding == "base64"
    }
}

/// InboundMessage is one already-parsed inbound message
/// `channel_receive` answers with. `external_identity` is opaque to the
/// host (a chat id, a phone number, a username, ...) — pick whatever your
/// vendor's own webhook payload identifies the sender by; the host binds
/// it to a Salamandr customer record on its own (auto-provisioning one
/// the first time it sees a given identity for this plugin instance).
#[derive(Debug, Clone, Default, Serialize)]
pub struct InboundMessage {
    pub external_identity: String,
    #[serde(default)]
    pub display_name: String,
    pub body: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_message_id: Option<String>,
    /// Files that arrived with this message, named by URL rather than
    /// carried as bytes — see [`InboundAttachment`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<InboundAttachment>,
}

/// InboundAttachment is one file arriving with an inbound message.
/// The plugin resolves *where* the bytes are (a Telegram `getFile` path, a
/// WhatsApp media URL, a signed link) and the host fetches them: the guest
/// never carries the bytes.
///
/// The `url` is fetched under the same policy as [`crate::http_fetch`] —
/// it must be on this extension's granted `http_hosts` (redirects
/// re-checked at every hop) and the dial is SSRF-guarded — so a plugin
/// cannot use this to reach somewhere its manifest didn't declare, and an
/// admin reading that manifest sees every host files could come from.
#[derive(Debug, Clone, Default, Serialize)]
pub struct InboundAttachment {
    /// What the file is called on the ticket. Sanitized host-side, so a
    /// plugin cannot choose a path.
    pub file_name: String,
    /// The vendor's own type when it reported one. Empty means "whatever
    /// the download says", falling back to `application/octet-stream`.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub content_type: String,
    /// Where the host fetches the bytes from.
    pub url: String,
    /// Headers sent with that fetch — a vendor whose media endpoint needs
    /// the plugin's own bearer token.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
}

/// ReceiveResult is the exact return type `channel_receive` must
/// have — a plain list, no [`crate::OpError`] wrapper: a webhook delivery
/// carrying zero messages (a vendor's own handshake/ping event, say) is
/// `Ok(ReceiveResult { messages: vec![] })`, not an error.
pub type ReceiveResult = Result<ReceiveResultData, crate::OpError>;

/// The data half of [`ReceiveResult`] — split out because
/// `type … = Result<Self, _>` isn't valid Rust for a type naming itself,
/// unlike [`crate::context::ContextResult`], whose `Ok` payload is
/// `Vec<ContextBlock>`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ReceiveResultData {
    pub messages: Vec<InboundMessage>,
}

/// SendRequest is what `channel_send` receives for an outbound
/// reply.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SendRequest {
    pub external_identity: String,
    #[serde(default)]
    pub ticket_id: String,
    #[serde(default)]
    pub message_id: String,
    pub body: String,
    /// The files an agent attached to this reply — metadata only. Send
    /// one with [`crate::http_upload`], which streams the bytes host-side
    /// and accepts only the ids listed here.
    #[serde(default)]
    pub attachments: Vec<OutboundAttachment>,
}

/// OutboundAttachment describes one file on an outgoing reply. It
/// deliberately carries no bytes and no storage path: everything needed to
/// decide *how* to send a file, nothing needed to read one.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct OutboundAttachment {
    pub id: String,
    #[serde(default)]
    pub file_name: String,
    #[serde(default)]
    pub content_type: String,
    #[serde(default)]
    pub size_bytes: i64,
}

/// SendResult is the exact return type `channel_send` must have —
/// a bare acknowledgement; the host discards the `Ok` payload.
pub type SendResult = Result<(), crate::OpError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn receive_result_serializes_to_the_go_wire_shape() {
        let data = ReceiveResultData {
            messages: vec![InboundMessage {
                external_identity: "chat-1".into(),
                display_name: "Ada".into(),
                body: "hello".into(),
                external_message_id: Some("42".into()),
                attachments: vec![],
            }],
        };
        let got = serde_json::to_value(&data).expect("serialize");
        let want = serde_json::json!({
            "messages": [{
                "external_identity": "chat-1",
                "display_name": "Ada",
                "body": "hello",
                "external_message_id": "42",
            }],
        });
        assert_eq!(got, want);
    }

    #[test]
    fn external_message_id_is_omitted_when_absent() {
        let data = ReceiveResultData {
            messages: vec![InboundMessage {
                external_identity: "chat-1".into(),
                body: "hi".into(),
                ..Default::default()
            }],
        };
        let got = serde_json::to_value(&data).expect("serialize");
        assert!(got["messages"][0].get("external_message_id").is_none());
    }

    #[test]
    fn request_decodes_the_host_input() {
        let req: ReceiveRequest = serde_json::from_str(
            r#"{"method":"POST","path":"/x","query":"","headers":{"X-Sig":["abc"]},"body":"hi","body_encoding":""}"#,
        )
        .expect("decode");
        assert_eq!(req.header("X-Sig"), Some("abc"));
        assert!(!req.is_binary_body());
    }
}