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 and do not wait for it.
55    fn cast(&self, name: String, params: Value);
56
57    /// The initial request payload, exactly as the host wrote it.
58    fn context(&self) -> Option<String>;
59}
60
61/// Turn the host's reply envelope into a result.
62///
63/// `{ "ok": true, "data": ... }` becomes the data, and anything else becomes a
64/// typed error carrying whatever the host said. It is written once, here, so
65/// every call site gets the same reading of the same reply.
66pub(crate) fn unwrap_reply(name: &str, reply: Value) -> Result<Value, Error> {
67    if reply.get("ok").and_then(Value::as_bool) == Some(true) {
68        return Ok(reply.get("data").cloned().unwrap_or(Value::Null));
69    }
70
71    let message = reply
72        .get("error")
73        .and_then(|error| error.get("message"))
74        .and_then(Value::as_str)
75        .filter(|message| !message.trim().is_empty())
76        .unwrap_or("The host refused the call and gave no reason.");
77
78    // A refused call establishes nothing about what it did before refusing, so
79    // it takes the generic code rather than a canonical one that would claim
80    // more than is known.
81    Err(Error::Host(crate::error::Fault::new(
82        crate::codes::Code::unspecified(),
83        format!("{name} failed: {message}"),
84    )))
85}
86
87#[cfg(target_arch = "wasm32")]
88pub(crate) use guest::{claim_report, install, report, transport};
89
90#[cfg(not(target_arch = "wasm32"))]
91pub(crate) use native::{claim_report, install, report, transport};
92
93/// The slot as it exists inside a running module.
94#[cfg(target_arch = "wasm32")]
95mod guest {
96    use std::sync::atomic::{AtomicBool, Ordering};
97    use std::sync::OnceLock;
98
99    use serde_json::Value;
100
101    use super::{Transport, DONE};
102    use crate::abi;
103    use crate::error::Error;
104
105    /// The real ABI, as a value with nothing in it. There is one host and it
106    /// holds no state, so the slot below marks initialisation rather than
107    /// storing anything.
108    struct Guest;
109
110    impl Transport for Guest {
111        fn call(&self, name: String, params: Value) -> Result<Value, Error> {
112            let payload = serde_json::to_string(&params).map_err(|cause| {
113                Error::Json(crate::error::Fault::new(
114                    crate::codes::Code::InvalidToolInput,
115                    format!("The parameters for {name} could not be encoded: {cause}"),
116                ))
117            })?;
118
119            let reply = abi::call(&name, &payload).ok_or_else(|| {
120                Error::Host(crate::error::Fault::new(
121                    crate::codes::Code::unspecified(),
122                    format!("{name} returned nothing the action could read."),
123                ))
124            })?;
125
126            let value: Value = serde_json::from_str(&reply).map_err(|cause| {
127                Error::Json(crate::error::Fault::new(
128                    crate::codes::Code::unspecified(),
129                    format!("{name} answered with something that is not JSON: {cause}"),
130                ))
131            })?;
132
133            super::unwrap_reply(&name, value)
134        }
135
136        fn cast(&self, name: String, params: Value) {
137            // A cast has nowhere to report a failure to, and the one cast that
138            // matters is `__done__` — which is how the host learns a run
139            // finished. An envelope that cannot be encoded is replaced by one
140            // that always can, so the report is made either way.
141            let payload = serde_json::to_string(&params)
142                .unwrap_or_else(|_unencodable| crate::envelope::unreportable());
143
144            abi::cast(&name, &payload);
145        }
146
147        fn context(&self) -> Option<String> {
148            abi::context()
149        }
150    }
151
152    static TRANSPORT: OnceLock<Guest> = OnceLock::new();
153    static REPORTED: AtomicBool = AtomicBool::new(false);
154
155    /// Fill the slot. A second call answers `Err`, which is what a run entered
156    /// twice looks like.
157    pub(crate) fn install() -> Result<(), Error> {
158        TRANSPORT.set(Guest).map_err(|_already| {
159            Error::failed("The action was started twice in one run.")
160                .hint("Call simple::run once, from main.")
161        })
162    }
163
164    /// What is in the slot, or a typed error saying nothing is.
165    pub(crate) fn transport() -> Result<&'static dyn Transport, Error> {
166        TRANSPORT
167            .get()
168            .map(|guest| guest as &dyn Transport)
169            .ok_or_else(|| {
170                Error::failed("The action tried to reach the host before it had started.")
171                    .hint("Do the work inside the handler passed to simple::run.")
172            })
173    }
174
175    /// True exactly once, for whoever gets there first.
176    pub(crate) fn claim_report() -> bool {
177        !REPORTED.swap(true, Ordering::SeqCst)
178    }
179
180    /// Tell the host the run is over.
181    ///
182    /// This does not go through the slot: the panic hook can be reached before
183    /// the slot is filled, and the report is made whether it was filled or not.
184    pub(crate) fn report(envelope: Value) {
185        Guest.cast(DONE.to_string(), envelope);
186    }
187}
188
189/// The slot as it exists on the machine an action is written on.
190#[cfg(not(target_arch = "wasm32"))]
191mod native {
192    use std::cell::{Cell, RefCell};
193    use std::rc::Rc;
194
195    use serde_json::Value;
196
197    use super::{Transport, DONE};
198    use crate::error::Error;
199
200    thread_local! {
201        static TRANSPORT: RefCell<Option<Rc<dyn Transport>>> = const { RefCell::new(None) };
202        static REPORTED: Cell<bool> = const { Cell::new(false) };
203    }
204
205    /// Put a transport in this thread's slot, and forget any report already
206    /// made. Called by the test seam, never by an action.
207    pub(crate) fn set(transport: Option<Rc<dyn Transport>>) {
208        TRANSPORT.with(|slot| {
209            if let Ok(mut slot) = slot.try_borrow_mut() {
210                *slot = transport;
211            }
212        });
213        REPORTED.with(|reported| reported.set(false));
214    }
215
216    /// Nothing to fill: off `wasm32` the slot is filled by whoever is testing.
217    pub(crate) fn install() -> Result<(), Error> {
218        Ok(())
219    }
220
221    /// What this thread installed, or a typed error saying nothing did.
222    pub(crate) fn transport() -> Result<Rc<dyn Transport>, Error> {
223        TRANSPORT
224            .with(|slot| slot.try_borrow().ok().and_then(|slot| slot.clone()))
225            .ok_or_else(|| {
226                Error::failed("No host is installed on this thread.")
227                    .hint("Install one with simple::testing::install before calling the handler.")
228            })
229    }
230
231    /// True exactly once per installed session.
232    pub(crate) fn claim_report() -> bool {
233        REPORTED.with(|reported| !reported.replace(true))
234    }
235
236    /// Hand the finished envelope to whatever is standing in for the host.
237    ///
238    /// With nothing installed there is nobody to tell, so it goes to stderr —
239    /// which is where a developer running a handler by hand will look.
240    pub(crate) fn report(envelope: Value) {
241        match transport() {
242            Ok(transport) => transport.cast(DONE.to_string(), envelope),
243            Err(_nothing_installed) => {
244                eprintln!("[simple] no host installed; the run reported: {envelope}");
245            }
246        }
247    }
248}
249
250#[cfg(not(target_arch = "wasm32"))]
251pub(crate) use native::set;
252
253#[cfg(test)]
254mod tests {
255    use serde_json::json;
256
257    use super::*;
258
259    #[test]
260    fn a_successful_reply_unwraps_to_its_data() {
261        let reply = json!({ "ok": true, "data": { "rows": [] } });
262
263        assert_eq!(
264            unwrap_reply("action:db/execute", reply).unwrap(),
265            json!({ "rows": [] })
266        );
267    }
268
269    #[test]
270    fn a_refusal_keeps_the_hosts_own_message() {
271        let reply = json!({ "ok": false, "error": { "message": "permission denied" } });
272        let error = unwrap_reply("action:db/execute", reply).unwrap_err();
273
274        assert!(error.message().contains("permission denied"));
275    }
276
277    #[test]
278    fn a_refusal_with_no_message_still_says_something() {
279        let error = unwrap_reply("action:db/execute", json!({ "ok": false })).unwrap_err();
280
281        assert!(error.message().contains("gave no reason"));
282    }
283
284    #[test]
285    fn a_reply_with_no_data_member_is_null_rather_than_an_error() {
286        let reply = json!({ "ok": true });
287
288        assert_eq!(unwrap_reply("x", reply).unwrap(), json!(null));
289    }
290}