summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_core/src/reactor.rs
blob: 2aa1de068df4e3403df3e7ee199a3a117a6b9cb7 (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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::path::Path;
use std::sync::Arc;

use futures::StreamExt;

use itertools::Itertools;
use tedge_api::plugin::BuiltPlugin;
use tedge_api::PluginExt;
use tokio::sync::mpsc::channel;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
use tracing::debug;
use tracing::error;
use tracing::info_span;
use tracing::trace;
use tracing::trace_span;
use tracing::warn;
use tracing::Instrument;

use crate::communication::CorePluginDirectory;
use crate::communication::PluginDirectory;
use crate::communication::PluginInfo;
use crate::configuration::InstanceConfiguration;
use crate::configuration::PluginInstanceConfiguration;
use crate::configuration::PluginKind;
use crate::core_task::CoreInternalMessage;
use crate::core_task::CorePlugin;
use crate::errors::PluginBuilderInstantiationError;

use crate::errors::PluginConfigurationNotFoundError;
use crate::errors::PluginInstantiationError;
use crate::errors::PluginKindUnknownError;

use crate::errors::TedgeApplicationError;
use crate::plugin_task::PluginTask;
use crate::TedgeApplication;

/// Helper type for running a TedgeApplication
///
/// This type is only introduced for more seperation-of-concerns in the codebase
/// `Reactor::run()` is simply `TedgeApplication::run()`.
pub struct Reactor(pub(crate) TedgeApplication);

impl std::fmt::Debug for Reactor {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Helper type for preparing a PluginTask
struct PluginTaskPrep {
    name: String,
    plugin: BuiltPlugin,
    max_concurrency: usize,
    plugin_msg_comms: tedge_api::address::MessageSender,
    cancellation_token: CancellationToken,
}

impl Reactor {
    /// Run the application
    ///
    /// This function implements running the application. That includes the complete lifecycle of
    /// the application, the plugins that need to be started and stopped accordingly as well as
    /// crash safety concerns.
    pub async fn run(self) -> Result<(), TedgeApplicationError> {
        let max_concurrency = self.0.config().max_concurrency().get();

        // find all PluginBuilder objects that are registered and specified in the configuration to
        // be used to build Plugin instances with.
        //
        // This is then collected into a CorePluginDirectory, our "addressbook type" that can be
        // used to retrieve addresses for message passing.
        let mut directory = tracing::debug_span!("core.build_plugin_directory").in_scope(|| {
            let directory_iter = self.0.config().plugins().iter().map(|(pname, pconfig)| {
                // fetch the types the plugin claims to handle from the plugin builder identified
                // by the "kind" in the configuration of the instance
                let handle_types = self
                    .0
                    .plugin_builders()
                    .get(pconfig.kind().as_ref())
                    .map(|(handle_types, _)| handle_types.get_types().to_vec())
                    .ok_or_else(|| {
                        PluginInstantiationError::KindNotFound(PluginKindUnknownError {
                            name: pconfig.kind().as_ref().to_string(),
                            alternatives: None,
                        })
                    })?;

                Ok((
                    pname.to_string(),
                    PluginInfo::new(handle_types, max_concurrency),
                ))
            });

            CorePluginDirectory::collect_from(directory_iter)
        })?;

        // Start preparing the plugin instantiation...
        let plugin_instantiation_prep = tracing::debug_span!("core.plugin_instantiation_prep")
            .in_scope(|| {
                self.0
                    .config()
                    .plugins()
                    .iter()
                    .map(|(pname, pconfig)| {
                        let receiver = match directory
                            .get_mut(pname)
                            .map(|pinfo| pinfo.communicator.clone())
                        {
                            Some(receiver) => receiver,
                            None => unreachable!(
                            "Could not find existing plugin. This is a FATAL bug, please report it"
                        ),
                        };

                        (pname, pconfig, receiver)
                    })
                    .collect::<Vec<_>>()
            });

        let directory = Arc::new(directory);

        // ... and then instantiate the plugins requested by the user
        let (mut instantiated_plugins, failed_instantiations): (Vec<PluginTaskPrep>, Vec<_>) =
            plugin_instantiation_prep
                .into_iter()
                .map(|(pname, pconfig, communicator)| {
                    {
                        self.instantiate_plugin(
                            pname,
                            self.0.config_path(),
                            pconfig,
                            directory.clone(),
                            communicator,
                            self.0.cancellation_token().child_token(),
                        )
                    }
                    .instrument(info_span!("plugin.instantiate", name = %pname))
                })
                .collect::<futures::stream::FuturesUnordered<_>>()
                .collect::<Vec<Result<_, _>>>()
                .instrument(tracing::debug_span!("core.plugin_instantiation"))
                .await
                .into_iter()
                .partition_result();
        trace!("Plugins instantiated");

        if !failed_instantiations.is_empty() {
            return Err(TedgeApplicationError::PluginInstantiationsError {
                errors: failed_instantiations,
            });
        }

        // Now we need to make sure we start the "CoreTask", which is responsible for handling the
        // communication within the core itself.
        let (internal_sender, mut internal_receiver) = channel(10);
        let core_plugin = CorePlugin::new(internal_sender);
        instantiated_plugins.push(PluginTaskPrep {
            name: "core".to_string(),
            plugin: core_plugin.finish(),
            max_concurrency: 10,
            plugin_msg_comms: directory.get_core_communicator(),
            cancellation_token: self.0.cancellation_token.clone(),
        });

        debug!("Core task instantiated");

        let mut all_plugins: Vec<PluginTask> = instantiated_plugins
            .into_iter()
            .map(|prep| {
                let timeout = self.0.config().plugin_shutdown_timeout();
                let plugin = Arc::new(RwLock::new(prep.plugin));
                PluginTask::new(
                    prep.name,
                    plugin,
                    prep.max_concurrency,
                    prep.plugin_msg_comms,
                    prep.cancellation_token,
                    timeout,
                )
            })
            .collect();

        debug!("Running 'start' for plugins");
        let (_start_results_ok, start_results_err): (Vec<_>, Vec<_>) = all_plugins
            .iter_mut()
            .map(|plugin_task| {
                let span =
                    tracing::debug_span!("plugin.start", plugin.name = %plugin_task.plugin_name());
                plugin_task.run_start().instrument(span)
            })
            .collect::<futures::stream::FuturesOrdered<_>>()
            .collect::<Vec<Result<(), _>>>()
            .instrument(tracing::info_span!("core.mainloop.plugins.start"))
            .await
            .into_iter()
            .partition_result();

        if !start_results_err.is_empty() {
            return Err(TedgeApplicationError::PluginLifecycleErrors {
                errors: start_results_err,
            });
        }

        debug!("Enabling communications for plugins");
        all_plugins
            .iter()
            .map(|plugin_task| {
                let span =
                    tracing::debug_span!("plugin.enable_communication", plugin.name = %plugin_task.plugin_name());
                plugin_task.enable_communications().instrument(span)
            })
            .collect::<futures::stream::FuturesOrdered<_>>()
            .collect::<Vec<Result<(), _>>>()
            .instrument(tracing::info_span