use serde_json::Value;
use crate::error::Error;
pub(crate) const DONE: &str = "__done__";
pub(crate) const DB_EXECUTE: &str = "action:db/execute";
pub trait Transport {
fn call(&self, name: String, params: Value) -> Result<Value, Error>;
fn call_bytes(&self, name: String, params: Value, into: &mut Vec<u8>) -> Result<usize, Error> {
let _unsent = (params, into);
Err(Error::failed(format!(
"{name} answers with bytes, and this transport cannot carry them."
)))
}
fn cast(&self, name: String, params: Value);
fn context(&self) -> Option<String>;
}
pub(crate) fn unwrap_reply(name: &str, reply: Value) -> Result<Value, Error> {
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
return Ok(reply.get("data").cloned().unwrap_or(Value::Null));
}
let message = reply
.get("error")
.and_then(|error| error.get("message"))
.and_then(Value::as_str)
.filter(|message| !message.trim().is_empty())
.unwrap_or("The host refused the call and gave no reason.");
Err(Error::Host(crate::error::Fault::new(
crate::codes::Code::unspecified(),
format!("{name} failed: {message}"),
)))
}
#[cfg(target_arch = "wasm32")]
pub(crate) use guest::{claim_report, install, report, transport};
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use native::{claim_report, install, report, transport};
#[cfg(target_arch = "wasm32")]
mod guest {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use serde_json::Value;
use super::{Transport, DONE};
use crate::abi;
use crate::error::Error;
struct Guest;
impl Transport for Guest {
fn call(&self, name: String, params: Value) -> Result<Value, Error> {
let payload = encode(&name, ¶ms)?;
let reply = abi::call(&name, &payload).ok_or_else(|| {
Error::Host(crate::error::Fault::new(
crate::codes::Code::unspecified(),
format!("{name} returned nothing the action could read."),
))
})?;
let value: Value = serde_json::from_str(&reply).map_err(|cause| {
Error::Json(crate::error::Fault::new(
crate::codes::Code::unspecified(),
format!("{name} answered with something that is not JSON: {cause}"),
))
})?;
super::unwrap_reply(&name, value)
}
#[cfg(not(feature = "async"))]
fn call_bytes(
&self,
name: String,
params: Value,
into: &mut Vec<u8>,
) -> Result<usize, Error> {
let payload = encode(&name, ¶ms)?;
match abi::call_bytes(&name, &payload, into) {
abi::Bytes::Appended(count) => Ok(count),
abi::Bytes::Refused(envelope) => {
let value: Value = serde_json::from_str(&envelope).map_err(|cause| {
Error::Json(crate::error::Fault::new(
crate::codes::Code::unspecified(),
format!("{name} refused with something that is not JSON: {cause}"),
))
})?;
super::unwrap_reply(&name, value).and_then(|_contradicted| {
Err(Error::Host(crate::error::Fault::new(
crate::codes::Code::unspecified(),
format!("{name} was refused and gave no reason."),
)))
})
}
}
}
#[cfg(feature = "async")]
fn call_bytes(
&self,
name: String,
_params: Value,
_into: &mut Vec<u8>,
) -> Result<usize, Error> {
Err(Error::failed(format!(
"{name} answers with bytes, which only a server action can receive."
))
.hint("Set the action's execution environment to server."))
}
fn cast(&self, name: String, params: Value) {
let payload = serde_json::to_string(¶ms)
.unwrap_or_else(|_unencodable| crate::envelope::unreportable());
abi::cast(&name, &payload);
}
fn context(&self) -> Option<String> {
abi::context()
}
}
fn encode(name: &str, params: &Value) -> Result<String, Error> {
serde_json::to_string(params).map_err(|cause| {
Error::Json(crate::error::Fault::new(
crate::codes::Code::InvalidToolInput,
format!("The parameters for {name} could not be encoded: {cause}"),
))
})
}
static TRANSPORT: OnceLock<Guest> = OnceLock::new();
static REPORTED: AtomicBool = AtomicBool::new(false);
pub(crate) fn install() -> Result<(), Error> {
TRANSPORT.set(Guest).map_err(|_already| {
Error::failed("The action was started twice in one run.")
.hint("Call simple::run once, from main.")
})
}
pub(crate) fn transport() -> Result<&'static dyn Transport, Error> {
TRANSPORT
.get()
.map(|guest| guest as &dyn Transport)
.ok_or_else(|| {
Error::failed("The action tried to reach the host before it had started.")
.hint("Do the work inside the handler passed to simple::run.")
})
}
pub(crate) fn claim_report() -> bool {
!REPORTED.swap(true, Ordering::SeqCst)
}
pub(crate) fn report(envelope: Value) {
Guest.cast(DONE.to_string(), envelope);
}
}
#[cfg(not(target_arch = "wasm32"))]
mod native {
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use serde_json::Value;
use super::{Transport, DONE};
use crate::error::Error;
thread_local! {
static TRANSPORT: RefCell<Option<Rc<dyn Transport>>> = const { RefCell::new(None) };
static REPORTED: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn set(transport: Option<Rc<dyn Transport>>) {
TRANSPORT.with(|slot| {
if let Ok(mut slot) = slot.try_borrow_mut() {
*slot = transport;
}
});
REPORTED.with(|reported| reported.set(false));
}
pub(crate) fn install() -> Result<(), Error> {
Ok(())
}
pub(crate) fn transport() -> Result<Rc<dyn Transport>, Error> {
TRANSPORT
.with(|slot| slot.try_borrow().ok().and_then(|slot| slot.clone()))
.ok_or_else(|| {
Error::failed("No host is installed on this thread.")
.hint("Install one with simple::testing::install before calling the handler.")
})
}
pub(crate) fn claim_report() -> bool {
REPORTED.with(|reported| !reported.replace(true))
}
pub(crate) fn report(envelope: Value) {
match transport() {
Ok(transport) => transport.cast(DONE.to_string(), envelope),
Err(_nothing_installed) => {
eprintln!("[simple] no host installed; the run reported: {envelope}");
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use native::set;
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn a_successful_reply_unwraps_to_its_data() {
let reply = json!({ "ok": true, "data": { "rows": [] } });
assert_eq!(
unwrap_reply("action:db/execute", reply).unwrap(),
json!({ "rows": [] })
);
}
#[test]
fn a_refusal_keeps_the_hosts_own_message() {
let reply = json!({ "ok": false, "error": { "message": "permission denied" } });
let error = unwrap_reply("action:db/execute", reply).unwrap_err();
assert!(error.message().contains("permission denied"));
}
#[test]
fn a_refusal_with_no_message_still_says_something() {
let error = unwrap_reply("action:db/execute", json!({ "ok": false })).unwrap_err();
assert!(error.message().contains("gave no reason"));
}
#[test]
fn a_reply_with_no_data_member_is_null_rather_than_an_error() {
let reply = json!({ "ok": true });
assert_eq!(unwrap_reply("x", reply).unwrap(), json!(null));
}
}