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
use std::fmt::Debug;

use tokio::sync::broadcast::{self};
use uuid::Uuid;

use rsiot_messages_core::message_v2::{Message, MsgSource};

use crate::ComponentError;

#[derive(Debug)]
pub struct CmpInput<TMsg> {
    channel: broadcast::Receiver<Message<TMsg>>,
    msg_source: MsgSource,
}

impl<TMsg> CmpInput<TMsg>
where
    TMsg: Clone + Debug,
{
    pub fn new(
        channel: broadcast::Receiver<Message<TMsg>>,
        executor_name: &str,
        executor_id: Uuid,
    ) -> Self {
        let msg_source = MsgSource::new(executor_name, executor_id);
        Self {
            channel,
            msg_source,
        }
    }

    pub(crate) fn set_component_id(&mut self, component_name: &str, component_id: Uuid) {
        self.msg_source.set_component(component_name, component_id);
    }

    pub(crate) fn set_session_id(&mut self, session_name: &str, session_id: Uuid) {
        self.msg_source.set_session(session_name, session_id);
    }

    pub async fn recv(&mut self) -> Result<Option<Message<TMsg>>, ComponentError> {
        let msg = self
            .channel
            .recv()
            .await
            .map_err(|e| ComponentError::CmpInput(e.to_string()))?;
        let msg_cmp_process = match &msg.process {
            Some(cmp_process) => cmp_process,
            None => {
                let err = format!("cmp_process not set for message: {:?}", msg);
                return Err(ComponentError::CmpInput(err));
            }
        };
        if msg_cmp_process == &self.msg_source {
            return Ok(None);
        }
        Ok(Some(msg))
    }
}

impl<TMsg> Clone for CmpInput<TMsg>
where
    TMsg: Clone,
{
    fn clone(&self) -> Self {
        Self {
            channel: self.channel.resubscribe(),
            msg_source: self.msg_source.clone(),
        }
    }
}