summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_api/examples/heartbeat.rs
blob: 37e9c8ec56cb7809e3914df7f5b0fbc5d4e4df82 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use std::{collections::HashMap, time::Duration};

use async_trait::async_trait;
use futures::FutureExt;
use tedge_api::{
    address::ReplySenderFor,
    message::MessageType,
    plugin::{AcceptsReplies, BuiltPlugin, Handle, Message, PluginDeclaration, PluginExt},
    Address, CancellationToken, Plugin, PluginBuilder, PluginConfiguration, PluginDirectory,
    PluginError,
};

/// A message that represents a heartbeat that gets sent to plugins
#[derive(Debug)]
struct Heartbeat;
impl Message for Heartbeat {}
impl AcceptsReplies for Heartbeat {
    type Reply = HeartbeatStatus;
}

/// The reply for a heartbeat
#[derive(Debug)]
enum HeartbeatStatus {
    Alive,
    Degraded,
}
impl Message for HeartbeatStatus {}

/// A PluginBuilder that gets used to build a HeartbeatService plugin instance
#[derive(Debug)]
struct HeartbeatServiceBuilder;

#[derive(miette::Diagnostic, thiserror::Error, Debug)]
enum HeartbeatBuildError {
    #[error(transparent)]
    TomlParse(#[from] toml::de::Error),
}

#[async_trait]
impl<PD: PluginDirectory> PluginBuilder<PD> for HeartbeatServiceBuilder {
    fn kind_name() -> &'static str {
        todo!()
    }

    fn kind_message_types() -> tedge_api::plugin::HandleTypes
    where
        Self: Sized,
    {
        HeartbeatService::get_handled_types()
    }

    async fn verify_configuration(
        &self,
        _config: &PluginConfiguration,
    ) -> Result<(), tedge_api::error::PluginError> {
        Ok(())
    }

    async fn instantiate(
        &self,
        config: PluginConfiguration,
        cancellation_token: CancellationToken,
        plugin_dir: &PD,
    ) -> Result<BuiltPlugin, PluginError>
    where
        PD: 'async_trait,
    {
        let hb_config: HeartbeatConfig =
            toml::Value::try_into(config).map_err(HeartbeatBuildError::from)?;
        let monitored_services = hb_config
            .plugins
            .iter()
            .map(|name| {
                plugin_dir
                    .get_address_for::<HeartbeatMessages>(name)
                    .map(|addr| (name.clone(), addr))
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(HeartbeatService::new(
            Duration::from_millis(hb_config.interval),
            monitored_services,
            cancellation_token,
        )
        .finish())
    }
}

/// The configuration a HeartbeatServices can receive is represented by this type
#[derive(serde::Deserialize, Debug)]
struct HeartbeatConfig {
    interval: u64,
    plugins: Vec<String>,
}

/// The HeartbeatService type represents the actual plugin
struct HeartbeatService {
    interval_duration: Duration,
    monitored_services: Vec<(String, Address<HeartbeatMessages>)>,
    cancel_token: CancellationToken,
}

impl PluginDeclaration for HeartbeatService {
    type HandledMessages = ();
}

#[async_trait]
impl Plugin for HeartbeatService {
    /// The setup function of the HeartbeatService can be used by the plugin author to setup for
    /// example a connection to an external service. In this example, it is simply used to send the
    /// heartbeat
    ///
    /// Because this example is _simple_, we do not spawn a background task that periodically sends
    /// the heartbeat. In a real world scenario, that background task would be started here.
    async fn start(&mut self) -> Result<(), PluginError> {
        println!(
            "HeartbeatService: Setting up heartbeat service with interval: {:?}!",
            self.interval_duration
        );

        for service in &self.monitored_services {
            let mut interval = tokio::time::interval(self.interval_duration);
            let service = service.clone();
            let cancel_token = self.cancel_token.child_token();
            tokio::spawn(async move {
                loop {
                    tokio::select! {
                        _ = interval.tick() => {}
                        _ = cancel_token.cancelled() => {
                            break
                        }
                    }
                    println!(
                        "HeartbeatService: Sending heartbeat to service: {:?}",
                        service
                    );
                    tokio::select! {
                        reply = service
                        .1
                        .send_and_wait(Heartbeat)
                        .then(|answer| {
                            answer.unwrap()
                            .wait_for_reply(Duration::from_millis(100))}
                        ) => {
                            match reply
                            {
                                Ok(HeartbeatStatus::Alive) => {
                                    println!("HeartbeatService: Received all is well!")
                                }
                                Ok(HeartbeatStatus::Degraded) => {
                                    println!(
                                        "HeartbeatService: Oh-oh! Plugin '{}' is not doing well",
                                        service.0
                                        )
                                }

                                Err(reply_error) => {
                                    println!(
                                        "HeartbeatService: Critical error for '{}'! {reply_error}",
                                        service.0
                                        )
                                }
                            }
                        }

                        _ = cancel_token.cancelled() => {
                            break
                        }
                    }
                }
            });
        }
        Ok(())
    }

    /// A plugin author can use this shutdown function to clean resources when thin-edge shuts down
    async fn shutdown(&mut self) -> Result<(), PluginError> {
        println!("HeartbeatService: Shutting down heartbeat service!");
        Ok(())
    }
}

impl HeartbeatService {
    fn new(
        interval_duration: Duration,
        monitored_services: Vec<(String, Address<HeartbeatMessages>)>,
        cancel_token: CancellationToken,
    ) -> Self {
        Self {
            interval_duration,
            monitored_services,
            cancel_token,
        }
    }
}

/// A plugin that receives heartbeats
struct CriticalServiceBuilder;

// declare a set of messages that the CriticalService can receive.
// In this example, it can only receive a Heartbeat.
tedge_api::make_receiver_bundle!(struct HeartbeatMessages(Heartbeat));

#[async_trait]
impl<PD: PluginDirectory> PluginBuilder<PD> for CriticalServiceBuilder {
    fn kind_name() -> &'static str {
        todo!()
    }

    fn kind_message_types() -> tedge_api::plugin::HandleTypes
    where
        Self: Sized,
    {
        CriticalService::get_handled_types()
    }

    async fn verify_configuration(
        &self,
        _config: &PluginConfiguration,
    ) -> Result<(), tedge_api::error::PluginError> {
        Ok(())
    }

    async fn instantiate(
        &self,
        _config: PluginConfiguration,
        _cancellation_token: CancellationToken,
        _plugin_dir: &PD,
    ) -> Result<BuiltPlugin, PluginError>
    where
        PD: 'async_trait,
    {
        Ok(CriticalService {
            status: tokio::sync::Mutex::new(true),
        }
        .finish())
    }
}

/// The actual "critical" plugin implementation
struct CriticalService {
    status: tokio::sync::Mutex<bool>,
}

/// The CriticalService can receive Heartbeat objects, thus it needs a Handle<Heartbeat>
/// implementation
#[async_trait]
impl Handle<Heartbeat> for CriticalService {
    async fn handle_message(
        &self,
        _message: Heartbeat,
        sender: ReplySenderFor<Heartbeat>,
    ) -> Result<(), PluginError> {
        println!("CriticalService: Received Heartbeat!");
        let mut status = self.status.lock().await;

        let _ = sender.