Skip to main content

simpleplatform_sdk/
run.rs

1//! The entry point, and the one guarantee it makes.
2//!
3//! ```no_run
4//! use simpleplatform_sdk::prelude::*;
5//!
6//! #[derive(Deserialize)]
7//! struct Input {
8//!     name: String,
9//! }
10//!
11//! #[derive(Serialize)]
12//! struct Output {
13//!     greeting: String,
14//! }
15//!
16//! fn main() {
17//!     simple::run(|request: Request<Input>| {
18//!         Ok(Output {
19//!             greeting: format!("Hello, {}!", request.data.name),
20//!         })
21//!     })
22//! }
23//! ```
24//!
25//! # Exactly one `__done__`, on every path
26//!
27//! The host learns a run is over from `__cast("__done__", envelope)` and from
28//! nothing else, so every path through this file ends in exactly one report: the
29//! handler returning a value, the handler returning an error, a payload that does
30//! not match the handler's input type, a host that never answered, and a panic.
31//! The claim is a single atomic swap, so the panic hook and the ordinary return
32//! cannot both fire.
33//!
34//! # No proc-macro
35//!
36//! `fn main() { simple::run(handler) }` rather than `#[simple::action]`. A macro
37//! would generate a body the author could have written, hide the one place they
38//! most want to step through, and put `syn` in the build graph of every action —
39//! measured at 9.1 s of cold build for zero bytes of artifact.
40
41use std::panic::{catch_unwind, AssertUnwindSafe};
42
43use serde::de::DeserializeOwned;
44use serde::{Deserialize, Serialize};
45use serde_json::{Map, Value};
46
47use crate::codes::{Category, Code};
48use crate::envelope;
49use crate::error::{Error, Fault};
50use crate::host;
51
52/// Request headers, as the host assembled them.
53pub type Headers = Map<String, Value>;
54
55/// Reads a member that may arrive as `null` into its default.
56///
57/// `#[serde(default)]` covers a member that is *absent*. Several of these arrive
58/// *present and null*, which is a different thing: a run nobody triggered has no
59/// trigger to name, and says so with a null.
60///
61/// An absent value and a null one mean the same thing here — nothing — so both
62/// read as the type's default and the handler sees its input either way.
63fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
64where
65    D: serde::Deserializer<'de>,
66    T: serde::Deserialize<'de> + Default,
67{
68    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
69}
70
71/// Which logic execution this is.
72#[derive(Clone, Debug, Default, Deserialize, Serialize)]
73#[serde(default)]
74pub struct Logic {
75    /// Unique to this run. Quote it when reporting a failure to support.
76    #[serde(default, deserialize_with = "null_as_default")]
77    pub execution_id: String,
78    /// The logic definition being run.
79    #[serde(default, deserialize_with = "null_as_default")]
80    pub id: String,
81    /// What started it.
82    #[serde(default, deserialize_with = "null_as_default")]
83    pub trigger_id: String,
84    /// The task this run belongs to, when it belongs to one.
85    pub task_id: Option<String>,
86    /// Where it is running.
87    #[serde(default, deserialize_with = "null_as_default")]
88    pub execution_env: String,
89}
90
91/// Which tenant this is running for.
92#[derive(Clone, Debug, Default, Deserialize, Serialize)]
93#[serde(default)]
94pub struct Tenant {
95    /// The tenant's hostname, when it has one.
96    pub host: Option<String>,
97    /// The tenant's identifier, when the host sent one.
98    pub id: Option<String>,
99    /// The tenant's name.
100    #[serde(default, deserialize_with = "null_as_default")]
101    pub name: String,
102}
103
104/// Who this is running for, when it is running for anybody.
105#[derive(Clone, Debug, Default, Deserialize, Serialize)]
106#[serde(default)]
107pub struct User {
108    /// The user's identifier.
109    pub id: Option<String>,
110}
111
112/// The execution context, as the host assembled it.
113///
114/// It travels host-to-guest and is read, not passed: the host assembles the
115/// context for every call itself, so there is nothing for an action to supply and
116/// nothing to thread through its own functions.
117#[derive(Clone, Debug, Default, Deserialize, Serialize)]
118#[serde(default)]
119pub struct Context {
120    /// Which logic execution this is.
121    pub logic: Logic,
122    /// Which tenant this is running for.
123    pub tenant: Tenant,
124    /// Who this is running for.
125    pub user: User,
126}
127
128/// One incoming request, with its payload already parsed.
129///
130/// `data` is the handler's own input type, checked before the handler runs — so
131/// a payload that does not match is a typed failure with a code, reported from
132/// the one place that knows what the handler expected.
133#[derive(Clone, Debug)]
134pub struct Request<T> {
135    /// The payload, parsed into the handler's input type.
136    pub data: T,
137    /// The execution context, as the host assembled it.
138    pub context: Context,
139    /// The request headers.
140    pub headers: Headers,
141}
142
143impl<T> Request<T> {
144    /// A request carrying this payload and an empty context.
145    ///
146    /// This is how a test calls a handler directly, with no host and no wasm:
147    ///
148    /// ```
149    /// use simpleplatform_sdk::prelude::*;
150    ///
151    /// struct Input {
152    ///     id: String,
153    /// }
154    ///
155    /// fn handler(request: Request<Input>) -> Result<String, Error> {
156    ///     Ok(request.data.id)
157    /// }
158    ///
159    /// let answer = handler(Request::new(Input { id: "KNOW1".into() })).unwrap();
160    ///
161    /// assert_eq!(answer, "KNOW1");
162    /// ```
163    pub fn new(data: T) -> Request<T> {
164        Request {
165            data,
166            context: Context::default(),
167            headers: Headers::new(),
168        }
169    }
170}
171
172/// What the host sends, before the payload inside it is parsed.
173#[derive(Deserialize)]
174struct Payload {
175    #[serde(default)]
176    context: Context,
177    /// The payload, as a JSON document inside a JSON string. An absent payload
178    /// and the four characters `null` both read as no payload.
179    #[serde(default)]
180    data: Option<String>,
181    #[serde(default)]
182    headers: Option<Headers>,
183}
184
185/// Run an action.
186///
187/// Installs the panic hook, reads the request, parses it into the handler's
188/// input type, calls the handler, and reports the result — exactly once,
189/// whatever happens.
190///
191/// It returns nothing, because there is nobody to return to: the result travels
192/// to the host, and everything that could go wrong has already been turned into
193/// a failure the host can read.
194pub fn run<T, R, F>(handler: F)
195where
196    T: DeserializeOwned,
197    R: Serialize,
198    F: FnOnce(Request<T>) -> Result<R, Error>,
199{
200    install_panic_hook();
201
202    let envelope = match catch_unwind(AssertUnwindSafe(|| execute(handler))) {
203        Ok(Ok(data)) => envelope::success(data),
204        Ok(Err(error)) => envelope::failure(&error),
205        Err(payload) => envelope::failure(&panicked(&panic_text(payload.as_ref()))),
206    };
207
208    // The hook may already have reported this run, in which case it said
209    // everything there was to say and a second report would be a second result.
210    if host::claim_report() {
211        host::report(envelope);
212    }
213}
214
215/// Everything between the host handing over a request and handing back a value.
216fn execute<T, R, F>(handler: F) -> Result<Value, Error>
217where
218    T: DeserializeOwned,
219    R: Serialize,
220    F: FnOnce(Request<T>) -> Result<R, Error>,
221{
222    host::install()?;
223
224    let transport = host::transport()?;
225
226    let payload = transport.context().ok_or_else(|| {
227        Error::failed("The host sent no request payload.")
228            .hint("This is a platform fault; quote the logic execution id when reporting it.")
229    })?;
230
231    let request = parse::<T>(&payload)?;
232    let result = handler(request)?;
233
234    let data = serde_json::to_value(result).map_err(|cause| {
235        // The handler already ran, so nothing here establishes that it changed
236        // nothing. The generic code is the one that claims no more than that.
237        Error::Json(Fault::new(
238            Code::unspecified(),
239            format!("The action's result could not be encoded as JSON: {cause}"),
240        ))
241        .category_of(Category::Internal)
242    })?;
243
244    reject_bare_string(&data)?;
245
246    Ok(data)
247}
248
249/// The host's request document, turned into a typed request.
250fn parse<T: DeserializeOwned>(payload: &str) -> Result<Request<T>, Error> {
251    let payload: Payload = serde_json::from_str(payload).map_err(|cause| {
252        Error::Input(Fault::new(
253            Code::InvalidToolInput,
254            format!("The request the host sent could not be read: {cause}"),
255        ))
256    })?;
257
258    let text = payload.data.unwrap_or_default();
259    let text = if text.trim().is_empty() {
260        "null"
261    } else {
262        text.as_str()
263    };
264
265    let data: T = serde_json::from_str(text).map_err(|cause| {
266        Error::Input(Fault::new(
267            Code::InvalidToolInput,
268            format!("The action input is invalid: {cause}"),
269        ))
270        .hint("Send an object matching this action's advertised input schema.")
271    })?;
272
273    Ok(Request {
274        data,
275        context: payload.context,
276        headers: payload.headers.unwrap_or_default(),
277    })
278}
279
280/// Refuse a result that is a bare JSON string.
281///
282/// A returned string is re-parsed as JSON on the way out, so a bare string is not
283/// a value an action can return unchanged. Naming it — `{ "text": ... }` — sends
284/// it as written, and the refusal here says so while the author is still looking
285/// at their own code.
286fn reject_bare_string(data: &Value) -> Result<(), Error> {
287    if !data.is_string() {
288        return Ok(());
289    }
290
291    Err(
292        Error::failed("An action cannot return a bare string.").hint(
293            "Return an object with a named member instead, for example { \"text\": ... }. \
294         The platform re-parses a returned string as JSON.",
295        ),
296    )
297}
298
299/// A recovered panic, as a failure.
300///
301/// The effect is unknown by construction: a panic proves nothing about what the
302/// action had already done, so nothing here claims it changed nothing.
303fn panicked(text: &str) -> Error {
304    Error::Panic(Fault::new(
305        Code::unspecified(),
306        format!("The action panicked: {text}"),
307    ))
308    .category_of(Category::Internal)
309    .hint("This is a fault in the action. Quote the logic execution id when reporting it.")
310}
311
312/// Whatever a panic payload has to say for itself.
313///
314/// A panic carries `&str` when the message is a literal and `String` when it is
315/// formatted. A payload of any other type still yields a sentence, so a panic
316/// always has something to report.
317fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
318    if let Some(text) = payload.downcast_ref::<&str>() {
319        return (*text).to_string();
320    }
321
322    if let Some(text) = payload.downcast_ref::<String>() {
323        return text.clone();
324    }
325
326    "no message".to_string()
327}
328
329/// Turn a panic into a reported failure rather than an opaque trap.
330///
331/// Only inside a module. A guest cannot unwind, so `catch_unwind` never catches
332/// there and the hook is the last thing that runs before the trap — it is the
333/// only chance to tell the host anything at all.
334///
335/// Off `wasm32` the hook is deliberately *not* installed: `set_hook` is
336/// process-global, so the standard hook is left in place for everything else
337/// sharing the process, and `catch_unwind` covers this side.
338#[cfg(target_arch = "wasm32")]
339fn install_panic_hook() {
340    use std::sync::Once;
341
342    static INSTALLED: Once = Once::new();
343
344    INSTALLED.call_once(|| {
345        std::panic::set_hook(Box::new(|info| {
346            if !host::claim_report() {
347                return;
348            }
349
350            let where_at = match info.location() {
351                Some(location) => format!(" at {}:{}", location.file(), location.line()),
352                None => String::new(),
353            };
354
355            let text = format!("{}{where_at}", panic_text(info.payload()));
356
357            host::report(envelope::failure(&panicked(&text)));
358        }));
359    });
360}
361
362#[cfg(not(target_arch = "wasm32"))]
363fn install_panic_hook() {}
364
365#[cfg(test)]
366mod tests {
367    use serde_json::json;
368
369    use super::*;
370
371    #[derive(Debug, Deserialize)]
372    struct Input {
373        ids: Vec<String>,
374    }
375
376    fn payload(data: Option<&str>) -> String {
377        let mut document = Map::new();
378        document.insert(
379            "context".to_string(),
380            json!({ "logic": { "execution_id": "EXEC1" }, "tenant": { "name": "acme" } }),
381        );
382        document.insert(
383            "data".to_string(),
384            data.map(|text| json!(text)).unwrap_or(Value::Null),
385        );
386        document.insert("headers".to_string(), json!({ "x-trace": "1" }));
387
388        Value::Object(document).to_string()
389    }
390
391    #[test]
392    fn the_payload_is_parsed_into_the_handlers_own_type() {
393        let request: Request<Input> = parse(&payload(Some(r#"{"ids":["KNOW1"]}"#))).unwrap();
394
395        assert_eq!(request.data.ids, vec!["KNOW1".to_string()]);
396        assert_eq!(request.context.logic.execution_id, "EXEC1");
397        assert_eq!(request.context.tenant.name, "acme");
398        assert_eq!(request.headers["x-trace"], json!("1"));
399    }
400
401    #[test]
402    fn a_payload_that_does_not_match_is_a_typed_failure_before_the_handler_runs() {
403        let error = parse::<Input>(&payload(Some(r#"{"nope":1}"#))).unwrap_err();
404
405        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
406        assert!(error.message().contains("input is invalid"));
407    }
408
409    #[test]
410    fn an_absent_payload_reads_as_null_rather_than_as_a_parse_error() {
411        let request: Request<Option<Input>> = parse(&payload(None)).unwrap();
412
413        assert!(request.data.is_none());
414    }
415
416    #[test]
417    fn an_encoded_null_reads_the_same_as_an_absent_one() {
418        let request: Request<Option<Input>> = parse(&payload(Some("null"))).unwrap();
419
420        assert!(request.data.is_none());
421    }
422
423    #[test]
424    fn a_context_the_host_only_half_filled_still_reads() {
425        let document = json!({ "context": { "logic": { "execution_id": "unknown" } } });
426        let request: Request<Option<Input>> = parse(&document.to_string()).unwrap();
427
428        assert_eq!(request.context.logic.execution_id, "unknown");
429        assert_eq!(request.context.tenant.name, "");
430    }
431
432    #[test]
433    fn a_bare_string_result_is_refused_and_a_named_one_is_not() {
434        assert!(reject_bare_string(&json!("123")).is_err());
435        assert!(reject_bare_string(&json!({ "text": "123" })).is_ok());
436        assert!(reject_bare_string(&json!(123)).is_ok());
437        assert!(reject_bare_string(&json!(null)).is_ok());
438    }
439
440    #[test]
441    fn a_panic_payload_is_read_whichever_type_it_is() {
442        let text: Box<dyn std::any::Any + Send> = Box::new("boom");
443        assert_eq!(panic_text(text.as_ref()), "boom");
444
445        let owned: Box<dyn std::any::Any + Send> = Box::new("boom".to_string());
446        assert_eq!(panic_text(owned.as_ref()), "boom");
447
448        let neither: Box<dyn std::any::Any + Send> = Box::new(7_u8);
449        assert_eq!(panic_text(neither.as_ref()), "no message");
450    }
451}
452
453#[cfg(test)]
454mod null_valued_members {
455    use super::*;
456
457    /// A member declared as a string is accepted when it arrives as `null`.
458    ///
459    /// `#[serde(default)]` covers a member that is absent; these arrive present
460    /// and null, and read as the empty string.
461    #[test]
462    fn a_null_trigger_id_is_not_a_failure() {
463        let context: Context = serde_json::from_str(
464            r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":null,
465                "task_id":null,"execution_env":"server"},
466                "tenant":{"name":"acme"},"user":{"id":"USR-1"}}"#,
467        )
468        .expect("a context with a null trigger id must deserialise");
469
470        assert_eq!(context.logic.trigger_id, "");
471    }
472
473    #[test]
474    fn a_null_tenant_name_is_not_a_failure() {
475        let context: Context = serde_json::from_str(
476            r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":"TRG-1",
477                "execution_env":"server"},
478                "tenant":{"name":null},"user":{}}"#,
479        )
480        .expect("a null tenant name must deserialise");
481
482        assert_eq!(context.tenant.name, "");
483    }
484}