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 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 fn cast(&self, name: String, params: Value);
72
73 fn context(&self) -> Option<String>;
75}
76
77pub(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 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#[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 struct Guest;
125
126 impl Transport for Guest {
127 fn call(&self, name: String, params: Value) -> Result<Value, Error> {
128 let payload = encode(&name, ¶ms)?;
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, ¶ms)?;
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 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 let payload = serde_json::to_string(¶ms)
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 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 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 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 pub(crate) fn claim_report() -> bool {
242 !REPORTED.swap(true, Ordering::SeqCst)
243 }
244
245 pub(crate) fn report(envelope: Value) {
250 Guest.cast(DONE.to_string(), envelope);
251 }
252}
253
254#[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 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 pub(crate) fn install() -> Result<(), Error> {
283 Ok(())
284 }
285
286 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 pub(crate) fn claim_report() -> bool {
298 REPORTED.with(|reported| !reported.replace(true))
299 }
300
301 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}