workflow_nw/ipc/
method.rs

1//! Module containing IPC [`Method`] closure wrappers
2use crate::ipc::imports::*;
3
4/// Base trait representing an IPC method, used to retain
5/// method structures in IPC map without generics.
6#[async_trait]
7pub(crate) trait MethodTrait: Send + Sync + 'static {
8    async fn call_with_borsh(&self, data: &[u8]) -> ResponseResult<Vec<u8>>;
9}
10
11/// IPC method function type
12pub type MethodFn<Req, Resp> =
13    Arc<Box<dyn Send + Sync + Fn(Req) -> MethodFnReturn<Resp> + 'static>>;
14
15/// IPC method function return type
16pub type MethodFnReturn<T> = Pin<Box<(dyn Send + 'static + Future<Output = ResponseResult<T>>)>>;
17
18/// IPC method wrapper. Contains the method closure function.
19pub struct Method<Req, Resp>
20where
21    Req: MsgT,
22    Resp: MsgT,
23{
24    method: MethodFn<Req, Resp>,
25}
26
27impl<Req, Resp> Method<Req, Resp>
28where
29    Req: MsgT,
30    Resp: MsgT,
31{
32    pub fn new<FN>(method_fn: FN) -> Method<Req, Resp>
33    where
34        FN: Send + Sync + Fn(Req) -> MethodFnReturn<Resp> + 'static,
35    {
36        Method {
37            method: Arc::new(Box::new(method_fn)),
38        }
39    }
40}
41
42#[async_trait]
43impl<Req, Resp> MethodTrait for Method<Req, Resp>
44where
45    Req: MsgT,
46    Resp: MsgT,
47{
48    async fn call_with_borsh(&self, data: &[u8]) -> ResponseResult<Vec<u8>> {
49        let req = Req::try_from_slice(data)?;
50        let resp = (self.method)(req).await;
51        Ok(borsh::to_vec(&resp)?)
52    }
53}