summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_mapper/src/core/mapper.rs
blob: d4f0da2309f9bf8d131c3829787f6520482b8239 (plain)
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use crate::c8y::dynamic_discovery::*;
use crate::core::{converter::*, error::*};
use mqtt_channel::{
    Connection, Message, MqttError, SinkExt, StreamExt, Topic, TopicFilter, UnboundedReceiver,
    UnboundedSender,
};
use serde_json::json;
use std::path::PathBuf;
use std::{process, time::Duration};
use time::OffsetDateTime;
use tracing::{error, info, instrument, warn};
const SYNC_WINDOW: Duration = Duration::from_secs(3);
use std::result::Result::Ok;

pub async fn create_mapper(
    app_name: &str,
    mqtt_host: String,
    mqtt_port: u16,
    converter: Box<dyn Converter<Error = ConversionError>>,
) -> Result<Mapper, anyhow::Error> {
    info!("{} starting", app_name);

    let health_check_topics: TopicFilter = vec![
        "tedge/health-check",
        format!("tedge/health-check/{}", app_name).as_str(),
    ]
    .try_into()
    .expect("health check topics must be valid");

    let health_status_topic = Topic::new_unchecked(format!("tedge/health/{}", app_name).as_str());

    let mapper_config = converter.get_mapper_config();
    let mut topic_filter = mapper_config.in_topic_filter.clone();
    topic_filter.add_all(health_check_topics.clone());

    let mqtt_client =
        Connection::new(&mqtt_config(app_name, &mqtt_host, mqtt_port, topic_filter)?).await?;

    Mapper::subscribe_errors(mqtt_client.errors);

    Ok(Mapper::new(
        mqtt_client.received,
        mqtt_client.published,
        converter,
        health_check_topics,
        health_status_topic,
    ))
}

pub fn mqtt_config(
    name: &str,
    host: &str,
    port: u16,
    topic_filter: TopicFilter,
) -> Result<mqtt_channel::Config, anyhow::Error> {
    Ok(mqtt_channel::Config::default()
        .with_host(host)
        .with_port(port)
        .with_session_name(name)
        .with_subscriptions(topic_filter)
        .with_max_packet_size(10 * 1024 * 1024))
}

pub struct Mapper {
    input: UnboundedReceiver<Message>,
    output: UnboundedSender<Message>,
    converter: Box<dyn Converter<Error = ConversionError>>,
    health_check_topics: TopicFilter,
    health_status_topic: Topic,
}

impl Mapper {
    pub fn new(
        input: UnboundedReceiver<Message>,
        output: UnboundedSender<Message>,
        converter: Box<dyn Converter<Error = ConversionError>>,
        health_check_topics: TopicFilter,
        health_status_topic: Topic,
    ) -> Self {
        Self {
            input,
            output,
            converter,
            health_check_topics,
            health_status_topic,
        }
    }

    pub(crate) async fn run(&mut self, ops_dir: Option<PathBuf>) -> Result<(), MqttError> {
        info!("Running");
        self.process_messages(ops_dir).await?;
        Ok(())
    }

    #[instrument(skip(errors), name = "errors")]
    fn subscribe_errors(mut errors: UnboundedReceiver<MqttError>) {
        tokio::spawn(async move {
            while let Some(error) = errors.next().await {
                error!("{}", error);
            }
        });
    }

    #[instrument(skip(self), name = "messages")]
    async fn process_messages(&mut self, ops_dir: Option<PathBuf>) -> Result<(), MqttError> {
        let init_messages = self.converter.init_messages();
        for init_message in init_messages.into_iter() {
            let _ = self.output.send(init_message).await;
        }

        // Start the sync phase here and process messages until the sync window times out
        let _ = tokio::time::timeout(SYNC_WINDOW, async {
            while let Some(message) = self.input.next().await {
                self.process_message(message).await;
            }
        })
        .await;

        // Once the sync phase is complete, retrieve all sync messages from the converter and process them
        let sync_messages = self.converter.sync_messages();
        for message in sync_messages {
            self.process_message(message).await;
        }

        match ops_dir {
            // Create inotify steam for capturing the inotify events.
            Some(dir) => {
                process_inotify_and_mqtt_messages(self, dir).await?;
            }
            None => {
                // If there is no operation directory to watch, then continue processing only the mqtt messages
                let _ = process_mqtt_messages(self).await;
            }
        }
        Ok(())
    }

    async fn process_message(&mut self, message: Message) {
        if self.health_check_topics.accept(&message) {
            let health_status = json!({
                "status": "up",
                "pid": process::id(),
                "time": OffsetDateTime::now_utc().unix_timestamp(),
            })
            .to_string();
            let health_message = Message::new(&self.health_status_topic, health_status);
            let _ = self.output.send(health_message).await;
        } else {
            let converted_messages = self.converter.convert(&message).await;

            for converted_message in converted_messages.into_iter() {
                let _ = self.output.send(converted_message).await;
            }
        }
    }
}

async fn process_inotify_and_mqtt_messages(
    mapper: &mut Mapper,
    dir: PathBuf,
) -> Result<(), MqttError> {
    match create_inofity_event_stream(dir.clone()) {
        Ok(mut inotify_events) => loop {
            tokio::select! {
                msg =  mapper.input.next() => {
                    match msg {
                        Some(message) => {
                            mapper.process_message(message).await;
                        } None => {
                            break Ok(());
                        }
                    }
                }
                event = inotify_events.next() => {
                    match event {
                        Some(ev) => {
                            match ev {
                                Ok(ev_string) => {

                                            match  process_inotify_events(dir.clone(), ev_string) {
                                                Ok(Some(discovered_ops)) => {
                                                    let _ = mapper.output.send(mapper.converter.process_operation_update_message(discovered_ops)).await;
                                                }
                                                Ok(None) => {}
                                                Err(e) => {eprintln!("Processing inotify event failed due to {}", e);}
                                            }


                                } Err(e) => {eprintln!("Failed to extract event {}", e);}
                            }
                        }
                        None => {}
                    }
                }
            }
        }, // On error continue to process only mqtt messages.
        Err(e) => {
            eprintln!("Failed to create the inotify stream due to {:?}. So, dynamic operation discovery not supported, please restart the mapper on Add/Removal of an operation", e);
            process_mqtt_messages(mapper).await
        }
    }
}

async fn process_mqtt_messages(mapper: &mut Mapper) -> Result<(), MqttError> {
    while let Some(message) = mapper.input.