Skip to main content

simpleplatform_sdk/
host.rs

1//! The ambient transport: what an action talks to, and where it is kept.
2//!
3//! # Why it is ambient
4//!
5//! The host assembles the execution context for every call itself, so an action
6//! has nothing to pass it and no reason to carry a context parameter down through
7//! its own functions.
8//!
9//! What remains is a transport, and there is exactly one of it per run. It lives
10//! in a slot [`crate::run`] fills before the handler is called, so
11//! [`crate::graphql`] can reach it without an argument and without a handle.
12//!
13//! # Two slots, because there are two worlds
14//!
15//! Under `wasm32` the guest is single-threaded, the transport is the real ABI,
16//! and a `OnceLock` fails safe in both directions that matter: a second `set`
17//! answers `Err` instead of corrupting, and a read before the first `set` is
18//! `None` — a typed error rather than a panic.
19//!
20//! Off `wasm32` — which is `cargo test`, on the developer's own machine — the
21//! transport is whatever a test installed, tests run in parallel threads, and a
22//! `thread_local!` is the only honest home for it.
23//!
24//! **The split is by target, not by `cfg(test)`.** `cfg(test)` is set only while
25//! *this* crate's own tests build; an action crate running `cargo test` sees this
26//! crate compiled without it. Splitting by target is what puts the seam in the
27//! crate an action depends on, which is the audience it exists for.
28
29use serde_json::Value;
30
31use crate::error::Error;
32
33/// The action name a run reports its result under. The host learns a run is
34/// over from this and from nothing else.
35pub(crate) const DONE: &str = "__done__";
36
37/// The host action that executes a GraphQL document.
38pub(crate) const DB_EXECUTE: &str = "action:db/execute";
39
40/// What an action can ask of its host.
41///
42/// Implemented twice: once for the real ABI inside a module, and once by
43/// [`crate::testing`] for a host on your own machine. It is public so that the
44/// two are visibly the same contract, and so a later phase can add a transport
45/// without changing what an action sees.
46pub trait Transport {
47    /// Run an action and answer with its result.
48    ///
49    /// The envelope the host replies in is unwrapped here, so callers see
50    /// either the result or a typed error and never a three-member document
51    /// they have to inspect themselves.
52    fn call(&self, name: String, params: Value) -> Result<Value, Error>;
53
54    /// Run an action whose reply is a run of bytes, and append them to `into`.
55    ///
56    /// Answers with how many bytes were appended. The bytes arrive as they
57    /// are — no envelope, no text encoding — and a host that refused answers
58    /// with a typed error instead, exactly as [`Transport::call`] does.
59    ///
60    /// Provided, so a transport written before this method existed still
61    /// compiles; the provided one refuses every such call.
62    fn call_bytes(&self, name: String, params: Value, into: &mut Vec<u8>) -> Result<usize, Error> {
63        let _unsent = (params, into);
64
65        Err(Error::failed(format!(
66            "{name} answers with bytes, and this transport cannot carry them."
67        )))
68    }
69
70    /// Run an action and do not wait for it.
71    fn cast(&self, name: String, params: Value);
72
73    /// The initial request payload, exactly as the host wrote it.
74    fn context(&self) -> Option<String>;
75}
76
77/// Turn the host's reply envelope into a result.
78///
79/// `{ "ok": true, "data": ... }` becomes the data, and anything else becomes a
80/// typed error carrying whatever the host said. It is written once, here, so
81/// every call site gets the same reading of the same reply.
82pub(crate) fn unwrap_reply(name: &str, reply: Value) -> Result<Value, Error> {
83    if reply.get("ok").and_then(Value::as_bool) == Some(true) {
84        return Ok(reply.get("data").cloned().unwrap_or(Value::Null));
85    }
86
87    let message = reply
88        .get("error")
89        .and_then(|error| error.get("message"))
90        .and_then(Value::as_str)
91        .filter(|message| !message.trim().is_empty())
92        .unwrap_or("The host refused the call and gave no reason.");
93
94    // A refused call establishes nothing about what it did before refusing, so
95    // it takes the generic code rather than a canonical one that would claim
96    // more than is known.
97    Err(Error::Host(crate::error::Fault::new(
98        crate::codes::Code::unspecified(),
99        format!("{name} failed: {message}"),
100    )))
101}
102
103#[cfg(target_arch = "wasm32")]
104pub(crate) use guest::{claim_report, install, report, transport};
105
106#[cfg(not(target_arch = "wasm32"))]
107pub(crate) use native::{claim_report, install, report, transport};
108
109/// The slot as it exists inside a running module.
110#[cfg(target_arch = "wasm32")]
111mod guest {
112    use std::sync::atomic::{AtomicBool, Ordering};
113    use std::sync::OnceLock;
114
115    use serde_json::Value;
116
117    use super::{Transport, DONE};
118    use crate::abi;
119    use crate::error::Error;
120
121    /// The real ABI, as a value with nothing in it. There is one host and it
122    /// holds no state, so the slot below marks initialisation rather than
123    /// storing anything.
124    struct Guest;
125
126    impl Transport for Guest {
127        fn call(&self, name: String, params: Value) -> Result<Value, Error> {
128            let payload = encode(&name, &params)?;
129
130            let reply = abi::call(&name, &payload).ok_or_else(|| {
131                Error::Host(crate::error::Fault::new(
132                    crate::codes::Code::unspecified(),
133                    format!("{name} returned nothing the action could read."),
134                ))
135            })?;
136
137            let value: Value = serde_json::from_str(&reply).map_err(|cause| {
138                Error::Json(crate::error::Fault::new(
139                    crate::codes::Code::unspecified(),
140                    format!("{name} answered with something that is not JSON: {cause}"),
141                ))
142            })?;
143
144            super::unwrap_reply(&name, value)
145        }
146
147        #[cfg(not(feature = "async"))]
148        fn call_bytes(
149            &self,
150            name: String,
151            params: Value,
152            into: &mut Vec<u8>,
153        ) -> Result<usize, Error> {
154            let payload = encode(&name, &params)?;
155
156            match abi::call_bytes(&name, &payload, into) {
157                abi::Bytes::Appended(count) => Ok(count),
158                abi::Bytes::Refused(envelope) => {
159                    let value: Value = serde_json::from_str(&envelope).map_err(|cause| {
160                        Error::Json(crate::error::Fault::new(
161                            crate::codes::Code::unspecified(),
162                            format!("{name} refused with something that is not JSON: {cause}"),
163                        ))
164                    })?;
165
166                    // The size said refusal, so a document saying otherwise is
167                    // still a refusal: nothing was appended.
168                    super::unwrap_reply(&name, value).and_then(|_contradicted| {
169                        Err(Error::Host(crate::error::Fault::new(
170                            crate::codes::Code::unspecified(),
171                            format!("{name} was refused and gave no reason."),
172                        )))
173                    })
174                }
175            }
176        }
177
178        #[cfg(feature = "async")]
179        fn call_bytes(
180            &self,
181            name: String,
182            _params: Value,
183            _into: &mut Vec<u8>,
184        ) -> Result<usize, Error> {
185            Err(Error::failed(format!(
186                "{name} answers with bytes, which only a server action can receive."
187            ))
188            .hint("Set the action's execution environment to server."))
189        }
190
191        fn cast(&self, name: String, params: Value) {
192            // A cast has nowhere to report a failure to, and the one cast that
193            // matters is `__done__` — which is how the host learns a run
194            // finished. An envelope that cannot be encoded is replaced by one
195            // that always can, so the report is made either way.
196            let payload = serde_json::to_string(&params)
197                .unwrap_or_else(|_unencodable| crate::envelope::unreportable());
198
199            abi::cast(&name, &payload);
200        }
201
202        fn context(&self) -> Option<String> {
203            abi::context()
204        }
205    }
206
207    /// The parameters as the JSON text the host reads.
208    fn encode(name: &str, params: &Value) -> Result<String, Error> {
209        serde_json::to_string(params).map_err(|cause| {
210            Error::Json(crate::error::Fault::new(
211                crate::codes::Code::InvalidToolInput,
212                format!("The parameters for {name} could not be encoded: {cause}"),
213            ))
214        })
215    }
216
217    static TRANSPORT: OnceLock<Guest> = OnceLock::new();
218    static REPORTED: AtomicBool = AtomicBool::new(false);
219
220    /// Fill the slot. A second call answers `Err`, which is what a run entered
221    /// twice looks like.
222    pub(crate) fn install() -> Result<(), Error> {
223        TRANSPORT.set(Guest).map_err(|_already| {
224            Error::failed("The action was started twice in one run.")
225                .hint("Call simple::run once, from main.")
226        })
227    }
228
229    /// What is in the slot, or a typed error saying nothing is.
230    pub(crate) fn transport() -> Result<&'static dyn Transport, Error> {
231        TRANSPORT
232            .get()
233            .map(|guest| guest as &dyn Transport)
234            .ok_or_else(|| {
235                Error::failed("The action tried to reach the host before it had started.")
236                    .hint("Do the work inside the handler passed to simple::run.")
237            })
238    }
239
240    /// True exactly once, for whoever gets there first.
241    pub(crate) fn claim_report() -> bool {
242        !REPORTED.swap(true, Ordering::SeqCst)
243    }
244
245    /// Tell the host the run is over.
246    ///
247    /// This does not go through the slot: the panic hook can be reached before
248    /// the slot is filled, and the report is made whether it was filled or not.
249    pub(crate) fn report(envelope: Value) {
250        Guest.cast(DONE.to_string(), envelope);
251    }
252}
253
254/// The slot as it exists on the machine an action is written on.
255#[cfg(not(target_arch = "wasm32"))]
256mod native {
257    use std::cell::{Cell, RefCell};
258    use std::rc::Rc;
259
260    use serde_json::Value;
261
262    use super::{Transport, DONE};
263    use crate::error::Error;
264
265    thread_local! {
266        static TRANSPORT: RefCell<Option<Rc<dyn Transport>>> = const { RefCell::new(None) };
267        static REPORTED: Cell<bool> = const { Cell::new(false) };
268    }
269
270    /// Put a transport in this thread's slot, and forget any report already
271    /// made. Called by the test seam, never by an action.
272    pub(crate) fn set(transport: Option<Rc<dyn Transport>>) {
273        TRANSPORT.with(|slot| {
274            if let Ok(mut slot) = slot.try_borrow_mut() {
275                *slot = transport;
276            }
277        });
278        REPORTED.with(|reported| reported.set(false));
279    }
280
281    /// Nothing to fill: off `wasm32` the slot is filled by whoever is testing.
282    pub(crate) fn install() -> Result<(), Error> {
283        Ok(())
284    }
285
286    /// What this thread installed, or a typed error saying nothing did.
287    pub(crate) fn transport() -> Result<Rc<dyn Transport>, Error> {
288        TRANSPORT
289            .with(|slot| slot.try_borrow().ok().and_then(|slot| slot.clone()))
290            .ok_or_else(|| {
291                Error::failed("No host is installed on this thread.")
292                    .hint("Install one with simple::testing::install before calling the handler.")
293            })
294    }
295
296    /// True exactly once per installed session.
297    pub(crate) fn claim_report() -> bool {
298        REPORTED.with(|reported| !reported.replace(true))
299    }
300
301    /// Hand the finished envelope to whatever is standing in for the host.
302    ///
303    /// With nothing installed there is nobody to tell, so it goes to stderr —
304    /// which is where a developer running a handler by hand will look.
305    pub(crate) fn report(envelope: Value) {
306        match transport() {
307            Ok(transport) => transport.cast(DONE.to_string(), envelope),
308            Err(_nothing_installed) => {
309                eprintln!("[simple] no host installed; the run reported: {envelope}");
310            }
311        }
312    }
313}
314
315#[cfg(not(target_arch = "wasm32"))]
316pub(crate) use native::set;
317
318#[cfg(test)]
319mod tests {
320    use serde_json::json;
321
322    use super::*;
323
324    #[test]
325    fn a_successful_reply_unwraps_to_its_data() {
326        let reply = json!({ "ok": true, "data": { "rows": [] } });
327
328        assert_eq!(
329            unwrap_reply("action:db/execute", reply).unwrap(),
330            json!({ "rows": [] })
331        );
332    }
333
334    #[test]
335    fn a_refusal_keeps_the_hosts_own_message() {
336        let reply = json!({ "ok": false, "error": { "message": "permission denied" } });
337        let error = unwrap_reply("action:db/execute", reply).unwrap_err();
338
339        assert!(error.message().contains("permission denied"));
340    }
341
342    #[test]
343    fn a_refusal_with_no_message_still_says_something() {
344        let error = unwrap_reply("action:db/execute", json!({ "ok": false })).unwrap_err();
345
346        assert!(error.message().contains("gave no reason"));
347    }
348
349    #[test]
350    fn a_reply_with_no_data_member_is_null_rather_than_an_error() {
351        let reply = json!({ "ok": true });
352
353        assert_eq!(unwrap_reply("x", reply).unwrap(), json!(null));
354    }
355}