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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Operation registration, dispatch, and the self-description the host
//! verifies a plugin's manifest against.

use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;

use crate::abi::{read_bytes, respond_err, respond_err_code, respond_err_retry, respond_ok};
use crate::error::{OpError, Outcome};

/// ABI_VERSION is the alloc/dealloc/handle contract's own version,
/// reported by `describe` so the host can refuse a binary built against
/// a wire format it no longer speaks — rather than discovering the
/// mismatch as a trap in the middle of a customer's ticket. Bump it here
/// and in abi.go's ABIVersion together, or not at all.
pub const ABI_VERSION: u32 = 1;

type OpFn = Box<dyn Fn(&[u8]) -> u64>;

/// Registry is the only path from a Go-supplied operation name to actual
/// Rust code. A plain function in a plugin's source is unreachable from
/// the host until it is registered here — which is what makes "what does
/// this plugin expose" answerable by reading one block (see the
/// [`crate::plugin!`] macro, which builds this for you and reports the
/// same list through `describe`).
#[derive(Default)]
pub struct Registry {
    ops: HashMap<&'static str, OpFn>,
    names: Vec<&'static str>,
    context_names: Vec<&'static str>,
    action_names: Vec<&'static str>,
    channel_names: Vec<&'static str>,
    chatops_names: Vec<&'static str>,
    connector_names: Vec<&'static str>,
}

impl Registry {
    pub fn new() -> Self {
        Self {
            ops: HashMap::new(),
            names: Vec::new(),
            context_names: Vec::new(),
            action_names: Vec::new(),
            channel_names: Vec::new(),
            chatops_names: Vec::new(),
            connector_names: Vec::new(),
        }
    }

    /// op registers `name` so a Go-side `Adapter.Call(ctx, tenantID,
    /// name, ...)` reaches `f`. `In` is JSON-decoded from the call's
    /// input; `f`'s Result becomes the response — `Ok(v)` as
    /// `{"ok":true,"data":{"kind":"ok","data":v}}`, an [`OpError`] as
    /// described on that type.
    ///
    /// `name` must also appear in the plugin's manifest.toml
    /// `entrypoints` list. Both halves are checked: `Adapter.Call`
    /// refuses an operation the manifest didn't declare, and
    /// `describe` lets the host refuse at *install* time a manifest that
    /// declares an operation the binary never registered.
    pub fn op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            // Registering twice is always a copy-paste bug: the second
            // silently wins, and the op the author thinks they wired is
            // simply gone. Panicking here surfaces it on the very first
            // call rather than as a wrong answer forever.
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.ops.insert(
            name,
            Box::new(move |input_bytes: &[u8]| -> u64 {
                let input: In = match decode_input(input_bytes) {
                    Ok(v) => v,
                    Err(e) => return respond_ok(&Outcome::<Out>::Error { message: format!("invalid input: {e}") }),
                };
                match f(input) {
                    Ok(v) => respond_ok(&Outcome::Ok { data: v }),
                    Err(OpError::NotConfigured) => respond_err_code("not configured", "not_configured"),
                    Err(OpError::TicketTypeNotEnabled) => {
                        respond_err_code("context is not enabled for this ticket type", "ticket_type_not_enabled")
                    }
                    Err(OpError::NotFound) => respond_ok(&Outcome::<Out>::NotFound),
                    Err(OpError::EndOfCollection(message)) => respond_ok(&Outcome::<Out>::EndOfCollection { message }),
                    Err(OpError::RateLimited { retry_after }) => {
                        respond_ok(&Outcome::<Out>::RateLimited { retry_after })
                    }
                    Err(OpError::Transient(message)) => respond_ok(&Outcome::<Out>::Transient { message }),
                    Err(OpError::Other(message)) => respond_ok(&Outcome::<Out>::Error { message }),
                }
            }),
        );
        self
    }

    /// context_op registers `name` the way [`Self::op`] does, except for
    /// the wire shape of the response — no [`Outcome`] tag, ever. This is
    /// what a plugin implementing extension.ContextProvider's
    /// "fetch_context" (required, see internal/extwasm's manifest
    /// validation) or one of the internal/crm-style stronger-typed
    /// convenience ops ("fetch_contact", ...) must use, and `op` must
    /// not: `Adapter.FetchContext`/`Adapter.Call`, called directly by
    /// internal/extwasm's own Service and by every internal/crm-family
    /// domain package (see internal/crm's wasmProvider), decode
    /// `env.Data` straight into the target Go type with no Outcome
    /// unwrapping — they were never written to know about this SDK's own
    /// convention, on purpose, since a plugin author not using this SDK
    /// at all is just as valid a `fetch_context` implementation (see
    /// internal/extwasm's rustplugin_test.go fixture, which hand-rolls
    /// exactly this raw shape). `op`'s Outcome tag exists for a
    /// different, narrower audience: a domain package's *own* Go caller
    /// that already knows to decode it (internal/ecommerce/providers/woocommerce's
    /// `callWoo`/`wooOutcome[T]`), which is never true of the two
    /// generic call sites above.
    ///
    /// `Ok(v)` becomes the same plain `{"ok":true,"data":v}` a host
    /// function itself returns. `Err`'s three "well-known" variants map
    /// onto the envelope's own `code` field, exactly what
    /// `internal/extwasm/adapter.go`'s `codeToSentinel` already expects
    /// (`CodeNotConfigured`/`CodeTicketTypeNotEnabled`/`CodeNotFound`) —
    /// `NotFound` here is therefore a real envelope-level failure, unlike
    /// `op`, where it is a *successful* envelope carrying an
    /// `Outcome::NotFound` tag instead. The remaining `OpError` variants
    /// (`EndOfCollection`/`RateLimited`/`Transient`) have no meaning for
    /// a context op — nothing paginates or retries a sidebar lookup — so
    /// they fold into a plain, uncoded failure the host logs and skips,
    /// same as any other unexpected error.
    pub fn context_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.context_names.push(name);
        self.ops.insert(name, raw_handler(f));
        self
    }

    /// action_op registers `name` as an **executable action** — the write
    /// half of a context tool (see [`crate::ActionRequest`]). Wire shape
    /// is [`Self::context_op`]'s exactly: no [`Outcome`] tag, because the
    /// host decodes the answer straight into `extension.ActionResult`,
    /// and the three well-known `OpError`s become envelope codes.
    ///
    /// It is a separate block from `context_ops` for one reason: the host
    /// checks it. An action's op name arrives from the browser (it is the
    /// `op` the plugin itself put on a rendered [`crate::Action`]), so
    /// `Adapter.RunAction` refuses any op the binary didn't register
    /// *here* — registering a write under `ops` or `context_ops` would
    /// otherwise leave every other entrypoint reachable from a click.
    ///
    /// The handler's input is [`crate::ActionRequest`] (or any type that
    /// deserializes from it — a first-party connector flattens its own
    /// settings alongside), and its output [`crate::ActionResult`].
    pub fn action_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.action_names.push(name);
        self.ops.insert(name, raw_handler(f));
        self
    }

    /// channel_op registers `name` the way [`Self::context_op`] does (same
    /// untagged wire shape, same three well-known `OpError`s becoming
    /// envelope codes) — for a KindChannel plugin's "channel_receive" and
    /// "channel_send", the fixed pair `extwasm.Manifest.validate`
    /// requires that Kind's `entrypoints` to include. A separate block
    /// from `context_ops` for the identical reason `action_op` is: the
    /// host's channel webhook dispatcher decodes `channel_receive`'s
    /// answer directly into `ChannelReceiveResult` with no `Outcome`
    /// unwrapping, so registering it under `ops`/`context_ops` by mistake
    /// compiles, installs and then breaks with no other symptom — caught
    /// at install time by `Adapter.VerifyChannelProvider`.
    pub fn channel_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.channel_names.push(name);
        self.ops.insert(name, raw_handler(f));
        self
    }

    /// chatops_op registers `name` the way [`Self::channel_op`] does (same
    /// untagged wire shape) — for a KindChatops plugin's
    /// "chatops_post_root"/"chatops_post_reply"/"chatops_receive" (the
    /// entrypoints `extwasm.Manifest.validate` requires that Kind) and the
    /// optional "chatops_search_members"/"chatops_list_channels"/
    /// "chatops_message_url". A separate block from `channel_ops` for the
    /// identical reason `channel_op` is separate from `context_ops`: the
    /// host's chatops dispatcher/provider wrapper decode each answer
    /// directly with no `Outcome` unwrapping, so registering one under
    /// `ops`/`context_ops`/`channel_ops` by mistake compiles, installs and
    /// then breaks with no other symptom — caught at install time by
    /// `Adapter.VerifyChatopsProvider`.
    pub fn chatops_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.chatops_names.push(name);
        self.ops.insert(name, raw_handler(f));
        self
    }

    /// connector_op registers `name` the way [`Self::chatops_op`] does
    /// (same untagged wire shape) — for a KindConnector plugin's
    /// "connector_create_meeting"/"connector_update_meeting"/
    /// "connector_delete_meeting", the fixed trio
    /// `extwasm.Manifest.validate` requires that Kind's `entrypoints` to
    /// include. Caught at install time by `Adapter.VerifyConnectorProvider`
    /// if registered under the wrong block.
    pub fn connector_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
    where
        In: DeserializeOwned,
        Out: Serialize,
        F: Fn(In) -> Result<Out, OpError> + 'static,
    {
        if self.ops.contains_key(name) {
            panic!("operation {name:?} is registered twice");
        }
        self.names.push(name);
        self.connector_names.push(name);
        self.ops.insert(name, raw_handler(f));
        self
    }

    /// names lists every registered operation, in registration order —
    /// what `describe` reports.
    pub fn names(&self) -> &[&'static str] {
        &self.names
    }

    /// action_names lists the subset registered through
    /// [`Self::action_op`]. `describe` reports it separately so
    /// `Adapter.RunAction` can refuse an op that isn't one — see that
    /// method's doc comment for why a write is checked at call time and
    /// not only at install.
    pub fn action_names(&self) -> &[&'static str] {
        &self.action_names
    }

    /// context_names lists the subset registered through
    /// [`Self::context_op`]. `describe` reports it separately so the host
    /// can refuse, at install time, a plugin that registered
    /// `fetch_context` through [`Self::op`] — which compiles, installs
    /// and then answers every sidebar lookup with an `Outcome`-tagged
    /// object the host has no idea how to unwrap. It is the one mistake
    /// in this SDK that has no other symptom.
    pub fn context_names(&self) -> &[&'static str] {
        &self.context_names
    }

    /// channel_names lists the subset registered through
    /// [`Self::channel_op`] — see that method's doc comment.
    pub fn channel_names(&self) -> &[&'static str] {
        &self.channel_names
    }

    /// chatops_names lists the subset registered through
    /// [`Self::chatops_op`] — see that method's doc comment.
    pub fn chatops_names(&self) -> &[&'static str] {
        &self.chatops_names
    }

    /// connector_names lists the subset registered through
    /// [`Self::connector_op`] — see that method's doc comment.
    pub fn connector_names(&self) -> &[&'static str] {
        &self.connector_names
    }

    /// dispatch is what the generated `handle` calls — not meant to be
    /// called directly by plugin code.
    #[doc(hidden)]
    pub fn dispatch(&self, op: &str, input_bytes: &[u8]) -> u64 {
        match self.ops.get(op) {
            Some(f) => f(input_bytes),
            None => respond_err(&format!(
                "unknown operation {op:?} (this plugin implements: {})",
                self.names.join(", ")
            )),
        }
    }
}

/// raw_handler builds the dispatch closure shared by [`Registry::context_op`]
/// and [`Registry::action_op`] — the untagged shape, where the answer is
/// whatever the host's own Go type expects and the three well-known
/// [`OpError`]s travel as envelope *codes* rather than as an `Outcome`
/// tag inside a successful envelope — including the two retryable ones,
/// which the host turns back into a real retry (adapter.go's
/// CodeRateLimited/CodeTransient). Only EndOfCollection has no meaning on
/// either path, since nothing paginates a sidebar lookup or a one-shot
/// write, and folds into a plain failure.
fn raw_handler<In, Out, F>(f: F) -> OpFn
where
    In: DeserializeOwned,
    Out: Serialize,
    F: Fn(In) -> Result<Out, OpError> + 'static,
{
    Box::new(move |input_bytes: &[u8]| -> u64 {
        let input: In = match decode_input(input_bytes) {
            Ok(v) => v,
            Err(e) => return respond_err(&format!("invalid input: {e}")),
        };
        match f(input) {
            Ok(v) => respond_ok(&v),
            Err(OpError::NotConfigured) => respond_err_code("not configured", "not_configured"),
            Err(OpError::TicketTypeNotEnabled) => {
                respond_err_code("context is not enabled for this ticket type", "ticket_type_not_enabled")
            }
            Err(OpError::NotFound) => respond_err_code("not found", "not_found"),
            Err(OpError::EndOfCollection(message)) => respond_err(&message),
            // The two retryable kinds became envelope *codes* rather than
            // a plain failure: a vendor's 429 during fetch_context used to
            // reach the ticket sidebar as "nothing found", which is what
            // it also shows when no record is linked yet — so it offered
            // Create over a link the host had merely failed to read.
            Err(OpError::RateLimited { retry_after }) => respond_err_retry(
                "rate limited",
                "rate_limited",
                &retry_after.unwrap_or_default(),
            ),
            Err(OpError::Transient(message)) => respond_err_code(&message, "transient"),
            Err(OpError::Other(message)) => respond_err(&message),
        }
    })
}

/// decode_input treats an empty payload as `null` so an operation whose
/// input type is `()` or an all-optional struct doesn't need the host to
/// send `{}` — several call sites legitimately have nothing to say.
fn decode_input<In: DeserializeOwned>(bytes: &[u8]) -> Result<In, serde_json::Error> {
    if bytes.is_empty() {
        return serde_json::from_slice(b"null");
    }
    serde_json::from_slice(bytes)
}

/// Descriptor is what `describe` answers with — mirrored by
/// extwasm.Descriptor on the Go side, which compares `ops` against the
/// manifest's `entrypoints` at install time.
#[derive(Serialize)]
pub struct Descriptor<'a> {
    pub abi_version: u32,
    pub sdk: &'a str,
    pub sdk_version: &'a str,
    #[serde(skip_serializing_if = "str::is_empty")]
    pub name: &'a str,
    #[serde(skip_serializing_if = "str::is_empty")]
    pub version: &'a str,
    pub ops: &'a [&'a str],
    /// The subset of `ops` registered as context ops — see
    /// [`Registry::context_names`]. Absent on binaries built against SDK
    /// < 0.3, which is why the Go side treats an empty list as "this
    /// binary can't tell me" rather than "none".
    pub context_ops: &'a [&'a str],
    /// The subset of `ops` registered as executable actions — see
    /// [`Registry::action_names`]. Same "absent on older binaries"
    /// reasoning as `context_ops`; `Adapter.RunAction` refuses any op
    /// missing from this list once a binary reports it.
    pub action_ops: &'a [&'a str],
    /// The subset of `ops` registered as channel ops — see
    /// [`Registry::channel_names`]. Same "absent on older binaries"
    /// reasoning as `context_ops`/`action_ops`.
    pub channel_ops: &'a [&'a str],
    /// The subset of `ops` registered as chatops ops — see
    /// [`Registry::chatops_names`]. Same "absent on older binaries"
    /// reasoning as `context_ops`/`action_ops`/`channel_ops`.
    pub chatops_ops: &'a [&'a str],
    /// The subset of `ops` registered as connector ops — see
    /// [`Registry::connector_names`]. Same "absent on older binaries"
    /// reasoning as the other *_ops fields.
    pub connector_ops: &'a [&'a str],
}

/// handle_call is what the generated `handle` export delegates to —
/// reads the op name and input from guest memory (written there by the
/// host, per abi.go), builds the registry, and dispatches.
///
/// Rebuilding the registry per call is deliberate and free: it is a
/// handful of closures in a HashMap, and the module is instantiated fresh
/// per call anyway (see internal/extwasm's doc comment on why).
#[doc(hidden)]
pub fn handle_call(op_ptr: u32, op_len: u32, in_ptr: u32, in_len: u32, build_registry: fn() -> Registry) -> u64 {
    let op = match std::str::from_utf8(read_bytes(op_ptr, op_len)) {
        Ok(s) => s,
        Err(_) => return respond_err("operation name is not valid UTF-8"),
    };
    build_registry().dispatch(op, read_bytes(in_ptr, in_len))
}

/// describe_call is what the generated `describe` export delegates to.
#[doc(hidden)]
pub fn describe_call(name: &str, version: &str, build_registry: fn() -> Registry) -> u64 {
    let registry = build_registry();
    respond_ok(&Descriptor {
        abi_version: ABI_VERSION,
        sdk: env!("CARGO_PKG_NAME"),
        sdk_version: env!("CARGO_PKG_VERSION"),
        name,
        version,
        ops: registry.names(),
        context_ops: registry.context_names(),
        action_ops: registry.action_names(),
        channel_ops: registry.channel_names(),
        chatops_ops: registry.chatops_names(),
        connector_ops: registry.connector_names(),
    })
}