salamandr_plugin_sdk/lib.rs
1//! Safe Rust SDK for writing Salamandr WASM extensions — see
2//! backend/internal/extwasm's package doc comment (doc.go) for the
3//! manifest/scopes/host-function design this implements the guest side
4//! of, and abi.go for the exact alloc/dealloc/handle wire contract.
5//!
6//! # What a plugin can do
7//!
8//! Exactly four things, each behind a scope its manifest.toml declares
9//! and a tenant admin approves:
10//!
11//! | capability | module | scope |
12//! |---|---|---|
13//! | one HTTP call at a time | [`http_fetch`] | `http_hosts` |
14//! | tenant-supplied config/secrets | [`get_config`] | `config_keys` |
15//! | a small private key/value store | [`kv_get`]/[`kv_set`]/[`kv_delete`]/[`kv_list`] | `kv` |
16//! | the tenant's own helpdesk data | [`core`] | `core` |
17//!
18//! plus [`log`], which needs no scope. There is no filesystem, no
19//! environment, no clock but the host's, no sockets, and no WASI.
20//!
21//! # Writing a plugin
22//!
23//! Start from `sdk/examples/hello-crm`, a complete working plugin — this
24//! is the same code with the vendor call cut out. The crate's README.md
25//! is the full guide (manifest schema, build, install, testing).
26//!
27//! ```ignore
28//! use salamandr_plugin_sdk::{plugin, ContextBlock, ContextRequest, ContextResult};
29//!
30//! fn fetch_context(req: ContextRequest) -> ContextResult {
31//! let Some(email) = req.primary_email() else { return Ok(vec![]) };
32//! // `?` works directly on host calls — HostError converts into
33//! // OpError, and a host-side "not found" stays a not-found.
34//! let key = salamandr_plugin_sdk::get_config("api_key")?.unwrap_or_default();
35//! Ok(vec![ContextBlock::new("Acme CRM")
36//! .field("Email", email)
37//! .field("Key configured", if key.is_empty() { "no" } else { "yes" })])
38//! }
39//!
40//! plugin! {
41//! name: "my-plugin",
42//! version: env!("CARGO_PKG_VERSION"),
43//! // fetch_context goes in context_ops, never ops — see below.
44//! context_ops: {
45//! "fetch_context" => fetch_context,
46//! }
47//! }
48//! ```
49//!
50//! # `ops` vs `context_ops`
51//!
52//! Two blocks, two wire shapes, and picking the wrong one is the single
53//! mistake in this SDK that compiles, installs and then silently
54//! misbehaves:
55//!
56//! - **`context_ops`** — the host decodes your answer *directly* into
57//! its own Go type. This is what `"fetch_context"` (and any
58//! `"fetch_contact"`-style typed convenience op) must use. Almost
59//! every community plugin uses only this block.
60//! - **`ops`** — the answer is wrapped in an internally-tagged
61//! `Outcome` (`{"kind":"ok","data":…}`) that only a Go caller written
62//! to unwrap it can read. It exists for first-party connectors whose
63//! own Go package decodes them (internal/ecommerce/providers/woocommerce,
64//! internal/extension/providers/hubspot). A community plugin has no such caller.
65//!
66//! Registering `fetch_context` under `ops` is refused at install time
67//! rather than discovered in production — `describe` reports which block
68//! each op came from (see [`Registry::context_names`]).
69//!
70//! # Testing without a server
71//!
72//! [`testing::MockHost`] stands in for the host on non-wasm targets, so
73//! `cargo test` runs your operations natively — with your real
74//! manifest's scopes enforced:
75//!
76//! ```ignore
77//! let _host = MockHost::from_manifest(include_str!("../manifest.toml"))
78//! .config("api_key", "test-key")
79//! .http(|req| Ok(HttpResponse { status: 200, body: "{}".into(), ..Default::default() }))
80//! .install();
81//! assert_eq!(fetch_context(request).unwrap().len(), 1);
82//! ```
83//!
84//! # Why the [`plugin!`] macro is the whole export surface
85//!
86//! Rust exports whatever is marked `#[no_mangle] extern "C"`, wherever
87//! that happens to be written — so a plugin hand-rolling the ABI has no
88//! structural reason its WASM export table contains only what its author
89//! meant to expose. This crate makes that mistake unreachable:
90//!
91//! - The **only** four functions a plugin built with this SDK ever
92//! exports are `alloc`, `dealloc`, `handle` and `describe`, all
93//! generated by [`plugin!`]. `#[no_mangle]` should not appear
94//! anywhere in a plugin's own source.
95//! - An operation is reachable from Go **only** by appearing in that
96//! macro's `ops` block. A plain Rust function is just a function.
97//! "What does this plugin expose" is answered by reading one list.
98//! - That same list is what the generated `describe` export reports,
99//! so the host verifies a manifest's `entrypoints` against what the
100//! binary actually registered — at install time, not when a customer
101//! hits the missing operation.
102//! - Every host call is a safe, typed wrapper. An op author never
103//! touches a raw pointer or hand-encodes the wire envelope.
104
105mod abi;
106pub mod calendar_sync;
107pub mod channel;
108pub mod chatops;
109pub mod connector;
110mod context;
111pub mod core;
112mod error;
113pub mod host;
114mod persistent;
115mod registry;
116#[cfg(not(target_arch = "wasm32"))]
117pub mod testing;
118
119#[doc(hidden)]
120pub use abi::{sdk_alloc, sdk_dealloc};
121pub use context::{
122 Action, ActionField, ActionOutcome, ActionRequest, ActionResult, Actor, ContextBlock, ContextRequest,
123 ContextResult, Field, FieldOption, FieldSpec, TicketRef, FIELD_DATE, FIELD_MULTISELECT, FIELD_NUMBER,
124 FIELD_SELECT, FIELD_TEXT, FIELD_TEXTAREA, RICH_TEXT_FORMAT_JIRA_WIKI, RICH_TEXT_FORMAT_MARKDOWN,
125};
126pub use error::{code, HostError, OpError};
127pub use host::{
128 core_call, get_config, http_fetch, http_upload, kv_delete, kv_get, kv_list, kv_set, log, oauth_fetch,
129 richtext_to_jira_wiki, richtext_to_markdown, self_info, ws_send, HttpRequest, HttpResponse, OAuthFetchRequest,
130 SelfInfo, UploadRequest,
131};
132pub use persistent::{
133 PersistentConnectRequest, PersistentConnectResult, PersistentReceiveRequest, PersistentReceiveResponse,
134 PersistentReceiveResult,
135};
136pub use registry::{Descriptor, Registry, ABI_VERSION};
137#[doc(hidden)]
138pub use registry::{describe_call, handle_call};
139
140/// plugin! generates the **only** four functions a Salamandr WASM plugin
141/// ever exports — `alloc`, `dealloc`, `handle` and `describe` — from one
142/// declarative list of operations. See this crate's doc comment for why
143/// that list, rather than a scattering of `#[no_mangle]`s, is the design.
144///
145/// ```ignore
146/// plugin! {
147/// name: "woocommerce",
148/// version: env!("CARGO_PKG_VERSION"),
149/// ops: {
150/// "get_order" => ops::get_order,
151/// "create_refund" => ops::create_refund,
152/// }
153/// }
154/// ```
155///
156/// `name`/`version` are optional and purely descriptive — they travel in
157/// `describe`'s answer so an operator inspecting an installed binary can
158/// see what it claims to be. Each op's handler is any
159/// `Fn(In) -> Result<Out, OpError>` where `In: Deserialize` and
160/// `Out: Serialize`.
161///
162/// `context_ops` is a second, optional block for anything the *host*
163/// calls directly and unmarshals with no knowledge of this SDK's own
164/// wire convention — `"fetch_context"` (required on every plugin the
165/// normal community-extension path installs) and any
166/// internal/crm-family stronger-typed convenience op
167/// (`"fetch_contact"`, ...). See [`Registry::context_op`] for exactly
168/// how its wire shape differs from `ops`' and why the two must not be
169/// mixed up:
170///
171/// ```ignore
172/// plugin! {
173/// name: "hubspot",
174/// version: env!("CARGO_PKG_VERSION"),
175/// ops: {
176/// "get_order" => ops::get_order,
177/// },
178/// context_ops: {
179/// "fetch_context" => ops::fetch_context,
180/// "fetch_contact" => ops::fetch_contact,
181/// }
182/// }
183/// ```
184/// A third, optional `action_ops` block registers **executable actions**
185/// — the write half of a context tool. An op there is reachable from a
186/// button an agent clicks in the ticket sidebar (see [`Action::run`] and
187/// [`ActionRequest`]), and *only* from there: the host refuses to run an
188/// op that isn't in this block, so the ops that answer questions never
189/// become clickable by accident. Blocks are written in the order
190/// `ops`, `context_ops`, `action_ops`; any subset may be omitted.
191///
192/// ```ignore
193/// plugin! {
194/// name: "acme-crm",
195/// version: env!("CARGO_PKG_VERSION"),
196/// context_ops: {
197/// "fetch_context" => ops::fetch_context,
198/// },
199/// action_ops: {
200/// "log_note" => ops::log_note,
201/// }
202/// }
203/// ```
204///
205/// A `kind = "channel"` manifest (a ticket-creation channel connector,
206/// not a context tool) uses `channel_ops` instead — the fixed pair
207/// `"channel_receive"`/`"channel_send"` (see [`crate::channel`]),
208/// optionally alongside a plain `ops` block for anything else the plugin
209/// wants to expose. Never combined with `context_ops`/`action_ops`: a
210/// channel plugin has no ticket requester to answer a context lookup
211/// for.
212///
213/// ```ignore
214/// plugin! {
215/// name: "custom-webhook",
216/// version: env!("CARGO_PKG_VERSION"),
217/// channel_ops: {
218/// "channel_receive" => ops::channel_receive,
219/// "channel_send" => ops::channel_send,
220/// }
221/// }
222/// ```
223///
224/// A `kind = "chatops"` manifest (a team-chat mirror connector) uses
225/// `chatops_ops` instead — the fixed trio `"chatops_post_root"`/
226/// `"chatops_post_reply"`/`"chatops_receive"` (see [`crate::chatops`]),
227/// plus optionally `"chatops_search_members"`/`"chatops_list_channels"`/
228/// `"chatops_message_url"`. Never combined with `context_ops`/
229/// `action_ops`, same reasoning as `channel_ops`.
230///
231/// ```ignore
232/// plugin! {
233/// name: "generic-chatops",
234/// version: env!("CARGO_PKG_VERSION"),
235/// chatops_ops: {
236/// "chatops_post_root" => ops::post_root,
237/// "chatops_post_reply" => ops::post_reply,
238/// "chatops_receive" => ops::receive,
239/// }
240/// }
241/// ```
242///
243/// A `kind = "connector"` manifest (an OAuth video-conferencing
244/// connector) uses `connector_ops` instead — the fixed trio
245/// `"connector_create_meeting"`/`"connector_update_meeting"`/
246/// `"connector_delete_meeting"` (see [`crate::connector`]). Never
247/// combined with `context_ops`/`action_ops`, same reasoning as
248/// `channel_ops`/`chatops_ops`.
249///
250/// ```ignore
251/// plugin! {
252/// name: "generic-video",
253/// version: env!("CARGO_PKG_VERSION"),
254/// connector_ops: {
255/// "connector_create_meeting" => ops::create_meeting,
256/// "connector_update_meeting" => ops::update_meeting,
257/// "connector_delete_meeting" => ops::delete_meeting,
258/// }
259/// }
260/// ```
261#[macro_export]
262macro_rules! plugin {
263 // The one arm that generates code. Everything below normalizes onto
264 // it, so there is exactly one definition of what a plugin exports.
265 (@build $name:expr, $version:expr,
266 ops: { $($op:literal => $handler:expr),* $(,)? },
267 context_ops: { $($cop:literal => $chandler:expr),* $(,)? },
268 action_ops: { $($aop:literal => $ahandler:expr),* $(,)? },
269 channel_ops: { $($chop:literal => $chhandler:expr),* $(,)? },
270 chatops_ops: { $($ctop:literal => $cthandler:expr),* $(,)? },
271 connector_ops: { $($cnop:literal => $cnhandler:expr),* $(,)? } $(,)?
272 ) => {
273 // Not `pub`: nothing outside this crate may reach the registry,
274 // and the generated exports below are the only callers.
275 #[doc(hidden)]
276 fn __salamandr_build_registry() -> $crate::Registry {
277 $crate::Registry::new()
278 $(.op($op, $handler))*
279 $(.context_op($cop, $chandler))*
280 $(.action_op($aop, $ahandler))*
281 $(.channel_op($chop, $chhandler))*
282 $(.chatops_op($ctop, $cthandler))*
283 $(.connector_op($cnop, $cnhandler))*
284 }
285
286 #[no_mangle]
287 pub extern "C" fn alloc(size: u32) -> u32 {
288 $crate::sdk_alloc(size)
289 }
290
291 #[no_mangle]
292 pub extern "C" fn dealloc(ptr: u32, size: u32) {
293 $crate::sdk_dealloc(ptr, size)
294 }
295
296 #[no_mangle]
297 pub extern "C" fn handle(op_ptr: u32, op_len: u32, in_ptr: u32, in_len: u32) -> u64 {
298 $crate::handle_call(op_ptr, op_len, in_ptr, in_len, __salamandr_build_registry)
299 }
300
301 #[no_mangle]
302 pub extern "C" fn describe() -> u64 {
303 $crate::describe_call($name, $version, __salamandr_build_registry)
304 }
305 };
306
307 // Block normalization: fill in whichever of the six blocks the
308 // author left out. Written out rather than munched so a misspelled
309 // block name is a "no rules expected this token" at the call site
310 // instead of silently registering nothing.
311 //
312 // channel_ops/chatops_ops/connector_ops are each only normalized
313 // paired with ops or alone: a kind="channel"/kind="chatops"/
314 // kind="connector" manifest's fixed entrypoints have no reason to
315 // sit alongside context_ops/action_ops — those answer
316 // extension.ContextProvider's "what does the outside system know
317 // about this requester" shape, which none of those three plugin
318 // kinds (each keyed by something other than a ticket's requester)
319 // ever implements. Mixing them is not a combination this macro
320 // supports; a plugin needing both is two plugins.
321 (@blocks $n:expr, $v:expr,
322 ops: { $($o:tt)* }, context_ops: { $($c:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
323 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: { $($c)* }, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
324 };
325 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, context_ops: { $($c:tt)* } $(,)?) => {
326 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: { $($c)* }, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
327 };
328 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
329 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
330 };
331 (@blocks $n:expr, $v:expr, context_ops: { $($c:tt)* }, action_ops: { $($a:tt)* } $(,)?) => {
332 $crate::plugin!(@build $n, $v, ops: {}, context_ops: { $($c)* }, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
333 };
334 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, channel_ops: { $($ch:tt)* } $(,)?) => {
335 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: { $($ch)* }, chatops_ops: {}, connector_ops: {});
336 };
337 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, chatops_ops: { $($ct:tt)* } $(,)?) => {
338 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: { $($ct)* }, connector_ops: {});
339 };
340 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* }, connector_ops: { $($cn:tt)* } $(,)?) => {
341 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: { $($cn)* });
342 };
343 (@blocks $n:expr, $v:expr, ops: { $($o:tt)* } $(,)?) => {
344 $crate::plugin!(@build $n, $v, ops: { $($o)* }, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
345 };
346 (@blocks $n:expr, $v:expr, context_ops: { $($c:tt)* } $(,)?) => {
347 $crate::plugin!(@build $n, $v, ops: {}, context_ops: { $($c)* }, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: {});
348 };
349 (@blocks $n:expr, $v:expr, action_ops: { $($a:tt)* } $(,)?) => {
350 $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: { $($a)* }, channel_ops: {}, chatops_ops: {}, connector_ops: {});
351 };
352 (@blocks $n:expr, $v:expr, channel_ops: { $($ch:tt)* } $(,)?) => {
353 $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: { $($ch)* }, chatops_ops: {}, connector_ops: {});
354 };
355 (@blocks $n:expr, $v:expr, chatops_ops: { $($ct:tt)* } $(,)?) => {
356 $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: { $($ct)* }, connector_ops: {});
357 };
358 (@blocks $n:expr, $v:expr, connector_ops: { $($cn:tt)* } $(,)?) => {
359 $crate::plugin!(@build $n, $v, ops: {}, context_ops: {}, action_ops: {}, channel_ops: {}, chatops_ops: {}, connector_ops: { $($cn)* });
360 };
361
362 // Public entry points: name/version are optional, everything after
363 // them is blocks.
364 (name: $name:expr, version: $version:expr, $($blocks:tt)*) => {
365 $crate::plugin!(@blocks $name, $version, $($blocks)*);
366 };
367 ($($blocks:tt)*) => {
368 $crate::plugin!(@blocks "", "", $($blocks)*);
369 };
370}