astro_run/execution_context/
context_payload.rs

1use serde::{Deserialize, Serialize};
2use std::any::Any;
3
4#[typetag::serde]
5pub trait ContextPayloadExt: Any + Send + Sync {
6  fn as_any(&self) -> &dyn Any;
7}
8
9#[derive(Serialize, Deserialize)]
10pub struct ContextPayload(Box<dyn ContextPayloadExt>);
11
12impl ContextPayload {
13  pub fn new<P>(payload: P) -> Self
14  where
15    P: ContextPayloadExt,
16  {
17    ContextPayload(Box::new(payload))
18  }
19
20  pub fn payload<P>(&self) -> Option<&P>
21  where
22    P: ContextPayloadExt + 'static,
23  {
24    self.0.as_ref().as_any().downcast_ref::<P>()
25  }
26}
27
28impl std::fmt::Debug for ContextPayload {
29  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30    // Implement a empty payload for debug
31    f.debug_struct("ContextPayload").finish()
32  }
33}
34
35impl Clone for ContextPayload {
36  fn clone(&self) -> Self {
37    let payload_string = serde_json::to_string(&self.0).expect("Failed to serialize payload");
38
39    let payload: Box<dyn ContextPayloadExt> =
40      serde_json::from_str(&payload_string).expect("Failed to deserialize payload");
41
42    ContextPayload(payload)
43  }
44}