simpleplatform_sdk/
host.rs1use serde_json::Value;
30
31use crate::error::Error;
32
33pub(crate) const DONE: &str = "__done__";
36
37pub(crate) const DB_EXECUTE: &str = "action:db/execute";
39
40pub trait Transport {
47 fn call(&self, name: String, params: Value) -> Result<Value, Error>;
53
54 fn cast(&self, name: String, params: Value);
56
57 fn context(&self) -> Option<String>;
59}
60
61pub(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 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#[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 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(¶ms).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 let payload = serde_json::to_string(¶ms)
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 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 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 pub(crate) fn claim_report() -> bool {
177 !REPORTED.swap(true, Ordering::SeqCst)
178 }
179
180 pub(crate) fn report(envelope: Value) {
185 Guest.cast(DONE.to_string(), envelope);
186 }
187}
188
189#[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 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 pub(crate) fn install() -> Result<(), Error> {
218 Ok(())
219 }
220
221 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 pub(crate) fn claim_report() -> bool {
233 REPORTED.with(|reported| !reported.replace(true))
234 }
235
236 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}