use std::panic::{catch_unwind, AssertUnwindSafe};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::codes::{Category, Code};
use crate::envelope;
use crate::error::{Error, Fault};
use crate::host;
pub type Headers = Map<String, Value>;
fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de> + Default,
{
Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Logic {
#[serde(default, deserialize_with = "null_as_default")]
pub execution_id: String,
#[serde(default, deserialize_with = "null_as_default")]
pub id: String,
#[serde(default, deserialize_with = "null_as_default")]
pub trigger_id: String,
pub task_id: Option<String>,
#[serde(default, deserialize_with = "null_as_default")]
pub execution_env: String,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Tenant {
pub host: Option<String>,
pub id: Option<String>,
#[serde(default, deserialize_with = "null_as_default")]
pub name: String,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct User {
pub id: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Context {
pub logic: Logic,
pub tenant: Tenant,
pub user: User,
}
#[derive(Clone, Debug)]
pub struct Request<T> {
pub data: T,
pub context: Context,
pub headers: Headers,
}
impl<T> Request<T> {
pub fn new(data: T) -> Request<T> {
Request {
data,
context: Context::default(),
headers: Headers::new(),
}
}
}
#[derive(Deserialize)]
struct Payload {
#[serde(default)]
context: Context,
#[serde(default)]
data: Option<String>,
#[serde(default)]
headers: Option<Headers>,
}
pub fn run<T, R, F>(handler: F)
where
T: DeserializeOwned,
R: Serialize,
F: FnOnce(Request<T>) -> Result<R, Error>,
{
install_panic_hook();
let envelope = match catch_unwind(AssertUnwindSafe(|| execute(handler))) {
Ok(Ok(data)) => envelope::success(data),
Ok(Err(error)) => envelope::failure(&error),
Err(payload) => envelope::failure(&panicked(&panic_text(payload.as_ref()))),
};
if host::claim_report() {
host::report(envelope);
}
}
fn execute<T, R, F>(handler: F) -> Result<Value, Error>
where
T: DeserializeOwned,
R: Serialize,
F: FnOnce(Request<T>) -> Result<R, Error>,
{
host::install()?;
let transport = host::transport()?;
let payload = transport.context().ok_or_else(|| {
Error::failed("The host sent no request payload.")
.hint("This is a platform fault; quote the logic execution id when reporting it.")
})?;
let request = parse::<T>(&payload)?;
let result = handler(request)?;
let data = serde_json::to_value(result).map_err(|cause| {
Error::Json(Fault::new(
Code::unspecified(),
format!("The action's result could not be encoded as JSON: {cause}"),
))
.category_of(Category::Internal)
})?;
reject_bare_string(&data)?;
Ok(data)
}
fn parse<T: DeserializeOwned>(payload: &str) -> Result<Request<T>, Error> {
let payload: Payload = serde_json::from_str(payload).map_err(|cause| {
Error::Input(Fault::new(
Code::InvalidToolInput,
format!("The request the host sent could not be read: {cause}"),
))
})?;
let text = payload.data.unwrap_or_default();
let text = if text.trim().is_empty() {
"null"
} else {
text.as_str()
};
let data: T = serde_json::from_str(text).map_err(|cause| {
Error::Input(Fault::new(
Code::InvalidToolInput,
format!("The action input is invalid: {cause}"),
))
.hint("Send an object matching this action's advertised input schema.")
})?;
Ok(Request {
data,
context: payload.context,
headers: payload.headers.unwrap_or_default(),
})
}
fn reject_bare_string(data: &Value) -> Result<(), Error> {
if !data.is_string() {
return Ok(());
}
Err(
Error::failed("An action cannot return a bare string.").hint(
"Return an object with a named member instead, for example { \"text\": ... }. \
The platform re-parses a returned string as JSON.",
),
)
}
fn panicked(text: &str) -> Error {
Error::Panic(Fault::new(
Code::unspecified(),
format!("The action panicked: {text}"),
))
.category_of(Category::Internal)
.hint("This is a fault in the action. Quote the logic execution id when reporting it.")
}
fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(text) = payload.downcast_ref::<&str>() {
return (*text).to_string();
}
if let Some(text) = payload.downcast_ref::<String>() {
return text.clone();
}
"no message".to_string()
}
#[cfg(target_arch = "wasm32")]
fn install_panic_hook() {
use std::sync::Once;
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
std::panic::set_hook(Box::new(|info| {
if !host::claim_report() {
return;
}
let where_at = match info.location() {
Some(location) => format!(" at {}:{}", location.file(), location.line()),
None => String::new(),
};
let text = format!("{}{where_at}", panic_text(info.payload()));
host::report(envelope::failure(&panicked(&text)));
}));
});
}
#[cfg(not(target_arch = "wasm32"))]
fn install_panic_hook() {}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[derive(Debug, Deserialize)]
struct Input {
ids: Vec<String>,
}
fn payload(data: Option<&str>) -> String {
let mut document = Map::new();
document.insert(
"context".to_string(),
json!({ "logic": { "execution_id": "EXEC1" }, "tenant": { "name": "acme" } }),
);
document.insert(
"data".to_string(),
data.map(|text| json!(text)).unwrap_or(Value::Null),
);
document.insert("headers".to_string(), json!({ "x-trace": "1" }));
Value::Object(document).to_string()
}
#[test]
fn the_payload_is_parsed_into_the_handlers_own_type() {
let request: Request<Input> = parse(&payload(Some(r#"{"ids":["KNOW1"]}"#))).unwrap();
assert_eq!(request.data.ids, vec!["KNOW1".to_string()]);
assert_eq!(request.context.logic.execution_id, "EXEC1");
assert_eq!(request.context.tenant.name, "acme");
assert_eq!(request.headers["x-trace"], json!("1"));
}
#[test]
fn a_payload_that_does_not_match_is_a_typed_failure_before_the_handler_runs() {
let error = parse::<Input>(&payload(Some(r#"{"nope":1}"#))).unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert!(error.message().contains("input is invalid"));
}
#[test]
fn an_absent_payload_reads_as_null_rather_than_as_a_parse_error() {
let request: Request<Option<Input>> = parse(&payload(None)).unwrap();
assert!(request.data.is_none());
}
#[test]
fn an_encoded_null_reads_the_same_as_an_absent_one() {
let request: Request<Option<Input>> = parse(&payload(Some("null"))).unwrap();
assert!(request.data.is_none());
}
#[test]
fn a_context_the_host_only_half_filled_still_reads() {
let document = json!({ "context": { "logic": { "execution_id": "unknown" } } });
let request: Request<Option<Input>> = parse(&document.to_string()).unwrap();
assert_eq!(request.context.logic.execution_id, "unknown");
assert_eq!(request.context.tenant.name, "");
}
#[test]
fn a_bare_string_result_is_refused_and_a_named_one_is_not() {
assert!(reject_bare_string(&json!("123")).is_err());
assert!(reject_bare_string(&json!({ "text": "123" })).is_ok());
assert!(reject_bare_string(&json!(123)).is_ok());
assert!(reject_bare_string(&json!(null)).is_ok());
}
#[test]
fn a_panic_payload_is_read_whichever_type_it_is() {
let text: Box<dyn std::any::Any + Send> = Box::new("boom");
assert_eq!(panic_text(text.as_ref()), "boom");
let owned: Box<dyn std::any::Any + Send> = Box::new("boom".to_string());
assert_eq!(panic_text(owned.as_ref()), "boom");
let neither: Box<dyn std::any::Any + Send> = Box::new(7_u8);
assert_eq!(panic_text(neither.as_ref()), "no message");
}
}
#[cfg(test)]
mod null_valued_members {
use super::*;
#[test]
fn a_null_trigger_id_is_not_a_failure() {
let context: Context = serde_json::from_str(
r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":null,
"task_id":null,"execution_env":"server"},
"tenant":{"name":"acme"},"user":{"id":"USR-1"}}"#,
)
.expect("a context with a null trigger id must deserialise");
assert_eq!(context.logic.trigger_id, "");
}
#[test]
fn a_null_tenant_name_is_not_a_failure() {
let context: Context = serde_json::from_str(
r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":"TRG-1",
"execution_env":"server"},
"tenant":{"name":null},"user":{}}"#,
)
.expect("a null tenant name must deserialise");
assert_eq!(context.tenant.name, "");
}
}