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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Компонент для добавления сообщений из побочного потока

use async_trait::async_trait;
use tokio::task::JoinSet;

use rsiot_component_core::{
    Cache, Component, ComponentError, ComponentInput, ComponentOutput, IComponentProcess,
};
use rsiot_messages_core::IMessage;

async fn task_subscription<TMessage>(
    mut input: ComponentInput<TMessage>,
    output: ComponentOutput<TMessage>,
) -> Result<(), ComponentError>
where
    TMessage: IMessage,
{
    while let Ok(msg) = input.recv().await {
        output
            .send(msg)
            .await
            .map_err(|err| ComponentError::Execution(err.to_string()))?;
    }
    Ok(())
}

/// Настройки
#[derive(Debug)]
pub struct Cfg<TMessage> {
    pub channel: ComponentInput<TMessage>,
}

/// Компонент для добавления сообщений из побочного потока
#[cfg(not(feature = "single-thread"))]
#[async_trait()]
impl<TMsg> IComponentProcess<Cfg<TMsg>, TMsg> for Component<Cfg<TMsg>, TMsg>
where
    TMsg: IMessage + 'static,
{
    async fn process(
        &self,
        config: Cfg<TMsg>,
        input: ComponentInput<TMsg>,
        output: ComponentOutput<TMsg>,
        _cache: Cache<TMsg>,
    ) -> Result<(), ComponentError> {
        let mut task_set: JoinSet<Result<(), ComponentError>> = JoinSet::new();

        task_set.spawn(task_subscription(input, output.clone()));
        task_set.spawn(task_subscription(config.channel, output.clone()));

        while let Some(res) = task_set.join_next().await {
            res.map_err(|err| ComponentError::Execution(err.to_string()))??;
        }
        Ok(())
    }
}

/// Компонент для добавления сообщений из побочного потока
#[cfg(feature = "single-thread")]
#[async_trait(?Send)]
impl<TMsg> IComponentProcess<Cfg<TMsg>, TMsg> for Component<Cfg<TMsg>, TMsg>
where
    TMsg: IMessage + 'static,
{
    async fn process(
        &self,
        config: Cfg<TMsg>,
        input: ComponentInput<TMsg>,
        output: ComponentOutput<TMsg>,
        _cache: Cache<TMsg>,
    ) -> Result<(), ComponentError> {
        let mut task_set: JoinSet<Result<(), ComponentError>> = JoinSet::new();

        task_set.spawn(task_subscription(input, output.clone()));
        task_set.spawn(task_subscription(config.channel, output.clone()));

        while let Some(res) = task_set.join_next().await {
            res.map_err(|err| ComponentError::Execution(err.to_string()))??;
        }
        Ok(())
    }
}

pub type Cmp<TMsg> = Component<Cfg<TMsg>, TMsg>;