wascc_host/
dispatch.rs

1use crate::bus::MessageBus;
2use crate::inthost::{Invocation, WasccEntity};
3use std::{error::Error, sync::Arc};
4
5use wascap::prelude::KeyPair;
6use wascc_codec::capabilities::Dispatcher;
7
8/// A dispatcher is given to each capability provider, allowing it to send
9/// commands in to the guest module and await replies. This dispatch
10/// is one way, and is _not_ used for the guest module to send commands to capabilities
11#[derive(Clone)]
12pub(crate) struct WasccNativeDispatcher {
13    bus: Arc<MessageBus>,
14    capid: String,
15    binding: String,
16    hk: Arc<KeyPair>,
17}
18
19impl WasccNativeDispatcher {
20    pub fn new(hk: Arc<KeyPair>, bus: Arc<MessageBus>, capid: &str, binding: &str) -> Self {
21        WasccNativeDispatcher {
22            bus,
23            capid: capid.to_string(),
24            binding: binding.to_string(),
25            hk,
26        }
27    }
28}
29
30impl Dispatcher for WasccNativeDispatcher {
31    /// Called by a capability provider to invoke a function on an actor
32    fn dispatch(
33        &self,
34        actor: &str,
35        op: &str,
36        msg: &[u8],
37    ) -> Result<Vec<u8>, Box<dyn Error + Sync + Send>> {
38        trace!(
39            "Dispatching operation '{}' ({} bytes) to actor",
40            op,
41            msg.len()
42        );
43        let inv = Invocation::new(
44            &self.hk,
45            WasccEntity::Capability {
46                capid: self.capid.to_string(),
47                binding: self.binding.to_string(),
48            },
49            WasccEntity::Actor(actor.to_string()),
50            op,
51            msg.to_vec(),
52        );
53        let tgt_sub = self.bus.actor_subject(actor);
54        let resp = self.bus.invoke(&tgt_sub, inv);
55
56        match resp {
57            Ok(r) => match r.error {
58                Some(e) => Err(format!("Invocation failure: {}", e).into()),
59                None => Ok(r.msg),
60            },
61            Err(e) => Err(Box::new(e)),
62        }
63    }
64}