1use std::panic::{catch_unwind, AssertUnwindSafe};
42
43use serde::de::DeserializeOwned;
44use serde::{Deserialize, Serialize};
45use serde_json::{Map, Value};
46
47use crate::codes::{Category, Code};
48use crate::envelope;
49use crate::error::{Error, Fault};
50use crate::host;
51
52pub type Headers = Map<String, Value>;
54
55fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
64where
65 D: serde::Deserializer<'de>,
66 T: serde::Deserialize<'de> + Default,
67{
68 Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
69}
70
71#[derive(Clone, Debug, Default, Deserialize, Serialize)]
73#[serde(default)]
74pub struct Logic {
75 #[serde(default, deserialize_with = "null_as_default")]
77 pub execution_id: String,
78 #[serde(default, deserialize_with = "null_as_default")]
80 pub id: String,
81 #[serde(default, deserialize_with = "null_as_default")]
83 pub trigger_id: String,
84 pub task_id: Option<String>,
86 #[serde(default, deserialize_with = "null_as_default")]
88 pub execution_env: String,
89}
90
91#[derive(Clone, Debug, Default, Deserialize, Serialize)]
93#[serde(default)]
94pub struct Tenant {
95 pub host: Option<String>,
97 pub id: Option<String>,
99 #[serde(default, deserialize_with = "null_as_default")]
101 pub name: String,
102}
103
104#[derive(Clone, Debug, Default, Deserialize, Serialize)]
106#[serde(default)]
107pub struct User {
108 pub id: Option<String>,
110}
111
112#[derive(Clone, Debug, Default, Deserialize, Serialize)]
118#[serde(default)]
119pub struct Context {
120 pub logic: Logic,
122 pub tenant: Tenant,
124 pub user: User,
126}
127
128#[derive(Clone, Debug)]
134pub struct Request<T> {
135 pub data: T,
137 pub context: Context,
139 pub headers: Headers,
141}
142
143impl<T> Request<T> {
144 pub fn new(data: T) -> Request<T> {
164 Request {
165 data,
166 context: Context::default(),
167 headers: Headers::new(),
168 }
169 }
170}
171
172#[derive(Deserialize)]
174struct Payload {
175 #[serde(default)]
176 context: Context,
177 #[serde(default)]
180 data: Option<String>,
181 #[serde(default)]
182 headers: Option<Headers>,
183}
184
185pub fn run<T, R, F>(handler: F)
195where
196 T: DeserializeOwned,
197 R: Serialize,
198 F: FnOnce(Request<T>) -> Result<R, Error>,
199{
200 install_panic_hook();
201
202 let envelope = match catch_unwind(AssertUnwindSafe(|| execute(handler))) {
203 Ok(Ok(data)) => envelope::success(data),
204 Ok(Err(error)) => envelope::failure(&error),
205 Err(payload) => envelope::failure(&panicked(&panic_text(payload.as_ref()))),
206 };
207
208 if host::claim_report() {
211 host::report(envelope);
212 }
213}
214
215fn execute<T, R, F>(handler: F) -> Result<Value, Error>
217where
218 T: DeserializeOwned,
219 R: Serialize,
220 F: FnOnce(Request<T>) -> Result<R, Error>,
221{
222 host::install()?;
223
224 let transport = host::transport()?;
225
226 let payload = transport.context().ok_or_else(|| {
227 Error::failed("The host sent no request payload.")
228 .hint("This is a platform fault; quote the logic execution id when reporting it.")
229 })?;
230
231 let request = parse::<T>(&payload)?;
232 let result = handler(request)?;
233
234 let data = serde_json::to_value(result).map_err(|cause| {
235 Error::Json(Fault::new(
238 Code::unspecified(),
239 format!("The action's result could not be encoded as JSON: {cause}"),
240 ))
241 .category_of(Category::Internal)
242 })?;
243
244 reject_bare_string(&data)?;
245
246 Ok(data)
247}
248
249fn parse<T: DeserializeOwned>(payload: &str) -> Result<Request<T>, Error> {
251 let payload: Payload = serde_json::from_str(payload).map_err(|cause| {
252 Error::Input(Fault::new(
253 Code::InvalidToolInput,
254 format!("The request the host sent could not be read: {cause}"),
255 ))
256 })?;
257
258 let text = payload.data.unwrap_or_default();
259 let text = if text.trim().is_empty() {
260 "null"
261 } else {
262 text.as_str()
263 };
264
265 let data: T = serde_json::from_str(text).map_err(|cause| {
266 Error::Input(Fault::new(
267 Code::InvalidToolInput,
268 format!("The action input is invalid: {cause}"),
269 ))
270 .hint("Send an object matching this action's advertised input schema.")
271 })?;
272
273 Ok(Request {
274 data,
275 context: payload.context,
276 headers: payload.headers.unwrap_or_default(),
277 })
278}
279
280fn reject_bare_string(data: &Value) -> Result<(), Error> {
287 if !data.is_string() {
288 return Ok(());
289 }
290
291 Err(
292 Error::failed("An action cannot return a bare string.").hint(
293 "Return an object with a named member instead, for example { \"text\": ... }. \
294 The platform re-parses a returned string as JSON.",
295 ),
296 )
297}
298
299fn panicked(text: &str) -> Error {
304 Error::Panic(Fault::new(
305 Code::unspecified(),
306 format!("The action panicked: {text}"),
307 ))
308 .category_of(Category::Internal)
309 .hint("This is a fault in the action. Quote the logic execution id when reporting it.")
310}
311
312fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
318 if let Some(text) = payload.downcast_ref::<&str>() {
319 return (*text).to_string();
320 }
321
322 if let Some(text) = payload.downcast_ref::<String>() {
323 return text.clone();
324 }
325
326 "no message".to_string()
327}
328
329#[cfg(target_arch = "wasm32")]
339fn install_panic_hook() {
340 use std::sync::Once;
341
342 static INSTALLED: Once = Once::new();
343
344 INSTALLED.call_once(|| {
345 std::panic::set_hook(Box::new(|info| {
346 if !host::claim_report() {
347 return;
348 }
349
350 let where_at = match info.location() {
351 Some(location) => format!(" at {}:{}", location.file(), location.line()),
352 None => String::new(),
353 };
354
355 let text = format!("{}{where_at}", panic_text(info.payload()));
356
357 host::report(envelope::failure(&panicked(&text)));
358 }));
359 });
360}
361
362#[cfg(not(target_arch = "wasm32"))]
363fn install_panic_hook() {}
364
365#[cfg(test)]
366mod tests {
367 use serde_json::json;
368
369 use super::*;
370
371 #[derive(Debug, Deserialize)]
372 struct Input {
373 ids: Vec<String>,
374 }
375
376 fn payload(data: Option<&str>) -> String {
377 let mut document = Map::new();
378 document.insert(
379 "context".to_string(),
380 json!({ "logic": { "execution_id": "EXEC1" }, "tenant": { "name": "acme" } }),
381 );
382 document.insert(
383 "data".to_string(),
384 data.map(|text| json!(text)).unwrap_or(Value::Null),
385 );
386 document.insert("headers".to_string(), json!({ "x-trace": "1" }));
387
388 Value::Object(document).to_string()
389 }
390
391 #[test]
392 fn the_payload_is_parsed_into_the_handlers_own_type() {
393 let request: Request<Input> = parse(&payload(Some(r#"{"ids":["KNOW1"]}"#))).unwrap();
394
395 assert_eq!(request.data.ids, vec!["KNOW1".to_string()]);
396 assert_eq!(request.context.logic.execution_id, "EXEC1");
397 assert_eq!(request.context.tenant.name, "acme");
398 assert_eq!(request.headers["x-trace"], json!("1"));
399 }
400
401 #[test]
402 fn a_payload_that_does_not_match_is_a_typed_failure_before_the_handler_runs() {
403 let error = parse::<Input>(&payload(Some(r#"{"nope":1}"#))).unwrap_err();
404
405 assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
406 assert!(error.message().contains("input is invalid"));
407 }
408
409 #[test]
410 fn an_absent_payload_reads_as_null_rather_than_as_a_parse_error() {
411 let request: Request<Option<Input>> = parse(&payload(None)).unwrap();
412
413 assert!(request.data.is_none());
414 }
415
416 #[test]
417 fn an_encoded_null_reads_the_same_as_an_absent_one() {
418 let request: Request<Option<Input>> = parse(&payload(Some("null"))).unwrap();
419
420 assert!(request.data.is_none());
421 }
422
423 #[test]
424 fn a_context_the_host_only_half_filled_still_reads() {
425 let document = json!({ "context": { "logic": { "execution_id": "unknown" } } });
426 let request: Request<Option<Input>> = parse(&document.to_string()).unwrap();
427
428 assert_eq!(request.context.logic.execution_id, "unknown");
429 assert_eq!(request.context.tenant.name, "");
430 }
431
432 #[test]
433 fn a_bare_string_result_is_refused_and_a_named_one_is_not() {
434 assert!(reject_bare_string(&json!("123")).is_err());
435 assert!(reject_bare_string(&json!({ "text": "123" })).is_ok());
436 assert!(reject_bare_string(&json!(123)).is_ok());
437 assert!(reject_bare_string(&json!(null)).is_ok());
438 }
439
440 #[test]
441 fn a_panic_payload_is_read_whichever_type_it_is() {
442 let text: Box<dyn std::any::Any + Send> = Box::new("boom");
443 assert_eq!(panic_text(text.as_ref()), "boom");
444
445 let owned: Box<dyn std::any::Any + Send> = Box::new("boom".to_string());
446 assert_eq!(panic_text(owned.as_ref()), "boom");
447
448 let neither: Box<dyn std::any::Any + Send> = Box::new(7_u8);
449 assert_eq!(panic_text(neither.as_ref()), "no message");
450 }
451}
452
453#[cfg(test)]
454mod null_valued_members {
455 use super::*;
456
457 #[test]
462 fn a_null_trigger_id_is_not_a_failure() {
463 let context: Context = serde_json::from_str(
464 r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":null,
465 "task_id":null,"execution_env":"server"},
466 "tenant":{"name":"acme"},"user":{"id":"USR-1"}}"#,
467 )
468 .expect("a context with a null trigger id must deserialise");
469
470 assert_eq!(context.logic.trigger_id, "");
471 }
472
473 #[test]
474 fn a_null_tenant_name_is_not_a_failure() {
475 let context: Context = serde_json::from_str(
476 r#"{"logic":{"execution_id":"LEX-1","id":"LGC-1","trigger_id":"TRG-1",
477 "execution_env":"server"},
478 "tenant":{"name":null},"user":{}}"#,
479 )
480 .expect("a null tenant name must deserialise");
481
482 assert_eq!(context.tenant.name, "");
483 }
484}