rsiot/components/cmp_external_fn_process/
mod.rs

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! Тестирование документации:
//!
//! ```bash
//! cargo test components::cmp_external_fn_process --features="executor" --target="x86_64-unknown-linux-gnu";
//! cargo test --doc components::cmp_external_fn_process --features="executor" --target="x86_64-unknown-linux-gnu";
//!
//! cargo test components::cmp_external_fn_process --features="executor, single-thread" --target="x86_64-unknown-linux-gnu";
//! cargo test --doc components::cmp_external_fn_process --features="executor, single-thread" --target="x86_64-unknown-linux-gnu";
//! ```

use async_trait::async_trait;

#[cfg(feature = "single-thread")]
pub use futures::future::LocalBoxFuture;

#[cfg(not(feature = "single-thread"))]
pub use futures::future::BoxFuture;

use crate::{
    executor::{CmpInOut, CmpResult, Component, ComponentError, IComponentProcess},
    message::*,
};

#[cfg(feature = "single-thread")]
type FnProcess<TMsg, TService> =
    Box<dyn Fn(CmpInOut<TMsg, TService>) -> LocalBoxFuture<'static, CmpResult>>;

#[cfg(not(feature = "single-thread"))]
type FnProcess<TMsg, TService> =
    Box<dyn Fn(CmpInOut<TMsg, TService>) -> BoxFuture<'static, CmpResult> + Send + Sync>;

/// Настройки cmp_external_fn_process
pub struct Config<TMsg, TService>
where
    TMsg: MsgDataBound,
    TService: ServiceBound,
{
    /// Внешняя функция для выполнения
    ///
    /// Выполняемую асинхронную функцию `fn_external` необходимо обернуть в функцию.
    ///
    /// # Пример
    ///
    /// ```rust
    /// use std::time::Duration;
    ///
    /// use futures::future::LocalBoxFuture;
    /// use tokio::time::sleep;
    /// use tracing::info;
    ///
    /// use rsiot::{
    ///     components::cmp_external_fn_process,
    ///     executor::{CmpInOut, ComponentResult},
    ///     message::{example_message::*, *},
    /// };
    ///
    /// fn fn_process_wrapper<TMsg>(
    ///     in_out: CmpInOut<TMsg>,
    /// ) -> LocalBoxFuture<'static, ComponentResult>
    /// where
    ///     TMsg: MsgDataBound + 'static,
    /// {
    ///     Box::pin(async { fn_process(in_out).await })
    /// }
    /// async fn fn_process<TMsg>(_in_out: CmpInOut<TMsg>) -> ComponentResult {
    ///     loop {
    ///         info!("External fn process");
    ///         sleep(Duration::from_secs(2)).await;
    ///     }
    /// }
    ///
    /// let _config = cmp_external_fn_process::Config {
    ///     fn_process: Box::new(fn_process_wrapper::<Custom>),
    /// };
    /// # // insert-end
    /// ```
    #[cfg(feature = "single-thread")]
    pub fn_process: FnProcess<TMsg, TService>,

    /// Внешняя функция для выполнения
    ///
    /// Выполняемую асинхронную функцию `fn_external` необходимо обернуть в функцию.
    ///
    /// # Пример
    ///
    /// ```rust
    /// # // insert-start test multi_thread
    /// use std::time::Duration;
    ///
    /// use futures::future::BoxFuture;
    /// use tokio::time::sleep;
    /// use tracing::info;
    ///
    /// use rsiot::{
    ///     components::cmp_external_fn_process,
    ///     executor::{CmpInOut, ComponentResult},
    ///     message::{example_message::*, *},
    /// };
    ///
    /// fn fn_process_wrapper<TMsg>(in_out: CmpInOut<TMsg>) -> BoxFuture<'static, ComponentResult>
    /// where
    ///     TMsg: MsgDataBound + 'static,
    /// {
    ///     Box::pin(async { fn_process(in_out).await })
    /// }
    ///
    /// async fn fn_process<TMsg>(_in_out: CmpInOut<TMsg>) -> ComponentResult {
    ///     loop {
    ///         info!("External fn process");
    ///         sleep(Duration::from_secs(2)).await;
    ///     }
    /// }
    ///
    /// let _config = cmp_external_fn_process::Config {
    ///     fn_process: Box::new(fn_process_wrapper::<Custom>),
    /// };
    /// # // insert-end
    /// ```
    #[cfg(not(feature = "single-thread"))]
    pub fn_process: FnProcess<TMsg, TService>,
}

#[cfg_attr(not(feature = "single-thread"), async_trait)]
#[cfg_attr(feature = "single-thread", async_trait(?Send))]
#[async_trait(?Send)]
impl<TMsg, TService> IComponentProcess<Config<TMsg, TService>, TMsg, TService>
    for Component<Config<TMsg, TService>, TMsg, TService>
where
    TMsg: MsgDataBound,
    TService: ServiceBound,
{
    async fn process(
        &self,
        config: Config<TMsg, TService>,
        in_out: CmpInOut<TMsg, TService>,
    ) -> Result<(), ComponentError> {
        (config.fn_process)(
            in_out.clone_with_new_id("cmp_extrenal_fn_process", AuthPermissions::FullAccess),
        )
        .await
    }
}

/// Компонент cmp_external_fn_process
pub type Cmp<TMsg, TService> = Component<Config<TMsg, TService>, TMsg, TService>;

#[cfg(test)]
mod tests {

    #[cfg(feature = "single-thread")]
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn single_thread() {
        use std::time::Duration;

        use example_service::Service;
        use futures::future::LocalBoxFuture;

        #[cfg(target_arch = "wasm32")]
        use gloo::timers::future::sleep;
        #[cfg(not(target_arch = "wasm32"))]
        use tokio::time::sleep;

        use tracing::info;

        use crate::{
            components::cmp_external_fn_process,
            executor::{CmpInOut, CmpResult},
            message::{example_message::*, *},
        };

        fn fn_process_wrapper<TMsg, TService>(
            in_out: CmpInOut<TMsg, TService>,
        ) -> LocalBoxFuture<'static, CmpResult>
        where
            TMsg: MsgDataBound + 'static,
            TService: ServiceBound + 'static,
        {
            Box::pin(async { fn_process(in_out).await })
        }
        async fn fn_process<TMsg, TService>(_in_out: CmpInOut<TMsg, TService>) -> CmpResult
        where
            TMsg: MsgDataBound,
            TService: ServiceBound,
        {
            loop {
                info!("External fn process");
                sleep(Duration::from_secs(2)).await;
            }
        }

        let _config = cmp_external_fn_process::Config {
            fn_process: Box::new(fn_process_wrapper::<Custom, Service>),
        };
    }

    #[cfg(not(feature = "single-thread"))]
    #[test]
    fn multi_thread() {
        use std::time::Duration;

        use example_service::Service;
        use futures::future::BoxFuture;
        use tokio::time::sleep;
        use tracing::info;

        use crate::{
            components::cmp_external_fn_process,
            executor::{CmpInOut, CmpResult},
            message::{example_message::*, *},
        };

        fn fn_process_wrapper<TMsg, TService>(
            in_out: CmpInOut<TMsg, TService>,
        ) -> BoxFuture<'static, CmpResult>
        where
            TMsg: MsgDataBound + 'static,
            TService: ServiceBound + 'static,
        {
            Box::pin(async { fn_process(in_out).await })
        }

        async fn fn_process<TMsg, TService>(_in_out: CmpInOut<TMsg, TService>) -> CmpResult
        where
            TMsg: MsgDataBound + 'static,
            TService: ServiceBound + 'static,
        {
            loop {
                info!("External fn process");
                sleep(Duration::from_secs(2)).await;
            }
        }

        let _config = cmp_external_fn_process::Config {
            fn_process: Box::new(fn_process_wrapper::<Custom, Service>),
        };
    }
}