1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
pub mod notification;
use crate::imports::*;
pub use notification::*;

/// Collection of server-side notification handlers
pub struct Interface<Ops>
where
    Ops: OpsT,
{
    notifications: AHashMap<Ops, Box<dyn NotificationTrait>>,
}

impl<Ops> Default for Interface<Ops>
where
    Ops: OpsT,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<Ops> Interface<Ops>
where
    Ops: OpsT,
{
    pub fn new() -> Interface<Ops> {
        Interface {
            notifications: AHashMap::new(),
        }
    }

    pub fn notification<Msg>(&mut self, op: Ops, method: Notification<Msg>)
    where
        Ops: OpsT,
        Msg: BorshDeserialize + DeserializeOwned + Send + Sync + 'static,
    {
        let method: Box<dyn NotificationTrait> = Box::new(method);
        if self.notifications.insert(op.clone(), method).is_some() {
            panic!("RPC notification {op:?} is declared multiple times")
        }
    }

    pub async fn call_notification_with_borsh(&self, op: &Ops, payload: &[u8]) -> ServerResult<()> {
        if let Some(notification) = self.notifications.get(op) {
            notification.call_with_borsh(payload).await
        } else {
            Err(ServerError::NotFound)
        }
    }

    pub async fn call_notification_with_serde_json(
        &self,
        op: &Ops,
        payload: Value,
    ) -> ServerResult<()> {
        if let Some(notification) = self.notifications.get(op) {
            notification.call_with_serde_json(payload).await
        } else {
            Err(ServerError::NotFound)
        }
    }
}

impl<Ops> From<Interface<Ops>> for Option<Arc<Interface<Ops>>>
where
    Ops: OpsT,
{
    fn from(interface: Interface<Ops>) -> Self {
        Some(Arc::new(interface))
    }
}