mechutil 0.8.1

Utility structures and functions for mechatronics applications.
Documentation
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
//
// Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
// Created Date: 2024-09-03 11:24:02
// -----
// Last Modified: 2024-09-05 15:09:08
// -----
//
//

//! # MechActor: The MechUtil Actor
//!
//! The `MechActor` is an opinionated actor model for managing asynchronous tasks and routing commands
//! in a decoupled and efficient way, primarily using `tokio` channels. This actor provides both synchronous
//! and asynchronous tick handling, as well as routing functionality for commands.
//!
//! ## Motivation
//!
//! In mechatronics and automation, often the same resource (e.g., a connection to a controller) needs
//! to be shared across multiple asynchronous tasks performing unrelated functions. The `MechActor` solves
//! the following problems:
//! - Avoids repetitive code for spawning async tasks.
//! - Routes commands easily throughout a decoupled application.
//! - Works well in the context of a structured implementation without the complexities of lifetimes.
//!
//! ## Design Inspiration
//!
//! The actor's design is inspired by Alice Ryhl’s blog post [Actors with Tokio](https://ryhl.io/blog/actors-with-tokio/).
//! It uses `tokio` channels to avoid lifetime issues common with other actor models such as Actix.
//!
//! ## Features
//! - Regularly scheduled tick events at a specified interval, regardless of active usage.
//! - Support for both synchronous and asynchronous callbacks.
//! - Simple API for registering command routes.
//!
//! ## Usage
//!
//! ```ignore
//! use tokio::time::Duration;
//! use mechutil::MechActor;
//!
//! // Example of using the Actor in a struct
//! struct ActorStructExample {
//!     actor : MechActor
//! }
//!
//! impl ActorStructExample {
//!     pub fn new() -> Self {
//!         Self {
//!             actor : MechActor::new(std::time::Duration::from_millis(1000))            
//!         }
//!     }
//!
//!
//!     pub async fn start(&mut self) {
//!         let _ = self.actor.register_tick( move || {
//!             println!("actor 2 tick 1 ");             
//!         }).await;
//!
//!
//!         let _ = self.actor.register_tick( move || {
//!             println!("actor 2 tick 2 ");             
//!         }).await;
//!
//!
//!         if let Err(err) = self.actor.register_async_tick( move || {
//!             Box::pin (async move {
//!                 println!("async actor 2 TICKING ASYNC, BABY!");
//!             })
//!         }).await {
//!             println!("Failed to register async tick: {}", err);
//!         }
//!
//!         println!("SpawnTest registered tick callback");
//!     }
//!
//!     pub async fn stop(&mut self) {
//!         let _ = self.actor.shutdown().await;
//!         println!("SpawnTest shutdown.");
//!     }
//! }
//!
//!
//! #[tokio::main]
//! async fn main() {
//!     let actor = MechActor::new(Duration::from_secs(1));
//!
//!     // Register a synchronous tick callback
//!     let _ = actor.register_tick(|| {
//!         println!("Sync tick executed!");
//!     }).await;
//!
//!     // Register an asynchronous tick callback
//!     let _ = actor.register_async_tick(|| {
//!         Box::pin(async {
//!             println!("Async tick executed!");
//!         })
//!     }).await;
//!
//!     // Register a command route
//!     let _ = actor.register_route("example", |cmd| {
//!         println!("Processing command: {:?}", cmd);
//!         cmd.clone() // Return a processed command
//!     }).await;
//!
//!     // Simulate shutdown after some time
//!     tokio::time::sleep(Duration::from_secs(5)).await;
//!     let _ = actor.shutdown().await;
//! }
//! ```

use anyhow::anyhow;
use std::{collections::HashMap, pin::Pin, time::Duration};
use tokio::sync::{mpsc, oneshot};

use std::future::Future;

use crate::command::CommandMessage;

type BoxedCallback = Box<dyn FnMut(&CommandMessage) -> CommandMessage + Send + 'static>;
type BoxedTickCallback = Box<dyn FnMut() -> () + Send + 'static>;

type BoxedAsyncCallback = Box<
    dyn FnMut(&CommandMessage) -> Pin<Box<dyn Future<Output = CommandMessage> + Send>>
        + Send
        + 'static,
>;
type BoxedAsyncTickCallback =
    Box<dyn FnMut() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + 'static>;

/// Messages that can be sent to the `MechActor`.
enum ActorMessage {
    RegisterRoute {
        respond_to: oneshot::Sender<u32>,
        route: String,
        cb: BoxedCallback,
    },
    ProcessRoute {
        respond_to: oneshot::Sender<u32>,
        route: String,
        arg: CommandMessage,
    },
    RegisterAsyncRoute {
        respond_to: oneshot::Sender<u32>,
        route: String,
        cb: BoxedAsyncCallback,
    },
    RegisterTick {
        respond_to: oneshot::Sender<u32>,
        cb: BoxedTickCallback,
    },
    RegisterAsyncTick {
        respond_to: oneshot::Sender<u32>,
        cb: BoxedAsyncTickCallback,
    },
    Shutdown,
}

/// Internal actor processes the messages and contains the registered callbacks.
struct MechActorInternal {
    receiver: mpsc::Receiver<ActorMessage>,

    next_id: u32,
    routes: HashMap<String, BoxedCallback>,
    tick_routes: HashMap<u32, BoxedTickCallback>,
    tick_uid: u32,
    async_routes: HashMap<String, BoxedAsyncCallback>,
    async_tick_routes: HashMap<u32, BoxedAsyncTickCallback>,
}

// Implement the internal actor
impl MechActorInternal {
    fn new(receiver: mpsc::Receiver<ActorMessage>) -> Self {
        MechActorInternal {
            receiver,
            next_id: 0,
            routes: HashMap::new(),
            tick_routes: HashMap::new(),
            tick_uid: 0,
            async_routes: HashMap::new(),
            async_tick_routes: HashMap::new(),
        }
    }

    fn handle_message(&mut self, msg: ActorMessage) {
        match msg {
            ActorMessage::RegisterRoute {
                respond_to,
                route,
                cb,
            } => {
                self.routes.insert(route, cb);
                let _ = respond_to.send(self.next_id);
            }
            ActorMessage::RegisterTick { respond_to, cb } => {
                self.tick_uid += 1;
                self.tick_routes.insert(self.tick_uid, cb);
                let _ = respond_to.send(self.tick_uid);
            }
            ActorMessage::RegisterAsyncRoute {
                respond_to,
                route,
                cb,
            } => {
                self.async_routes.insert(route, cb);
                let _ = respond_to.send(self.next_id);
            }
            ActorMessage::RegisterAsyncTick { respond_to, cb } => {
                self.tick_uid += 1;
                self.async_tick_routes.insert(self.tick_uid, cb);
                let _ = respond_to.send(self.tick_uid);
            }
            _ => {
                // Unknown message. Ignore.
            }
        }
    }

    async fn tick(&mut self) {
        for (_, cb) in &mut self.tick_routes {
            cb();
        }

        for (_, cb) in &mut self.async_tick_routes {
            cb().await;
        }
    }
}

/// Execute the internal actor. Runs the tick interval and pipes messages into the
/// internal actor. This is also where routes are processed.
async fn run_my_actor(mut actor: MechActorInternal, interval: Duration) {
    let mut ticker = tokio::time::interval(interval);

    loop {
        tokio::select! {
            _ = ticker.tick() => {
                actor.tick().await;
            },
            msg = actor.receiver.recv() => {

                if let Some(m) = msg {
                    match m {
                        ActorMessage::Shutdown => {
                            break;
                        },
                        ActorMessage::ProcessRoute { respond_to : _, route, arg} => {
                            let arg_copy = arg.clone();
                            if let Some(cb) = actor.async_routes.get_mut(&route) {
                                cb(&arg_copy).await;
                            }
                            if let Some(cb) = actor.routes.get_mut(&route) {
                                cb(&arg_copy);
                            }
                        },
                        _ => {
                            actor.handle_message(m);
                        }
                    }
                }

            }
        }
    }
}

/// The public API for interacting with a `MechActor`.
#[derive(Clone)]
pub struct MechActor {
    sender: mpsc::Sender<ActorMessage>,
}

impl MechActor {
    /// Creates a new `MechActor` that ticks at the specified `interval`.
    ///
    /// # Arguments
    ///
    /// * `interval` - The time duration between each tick.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mechutil::MechActor;
    /// use std::time::Duration;
    ///
    /// let actor = MechActor::new(Duration::from_secs(1));
    /// ```    
    pub fn new(interval: Duration) -> Self {
        let (sender, receiver) = mpsc::channel(8);
        let actor = MechActorInternal::new(receiver);
        tokio::spawn(run_my_actor(actor, interval));

        Self { sender: sender }
    }

    /// Registers a synchronous callback to be invoked on a matching route.
    ///
    /// # Arguments
    ///
    /// * `cb` - The callback function to be invoked on each tick.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let actor = MechActor::new(Duration::from_secs(1));
    /// let _ = actor.register_route( "MyRoute".to_string(), || {
    ///     println!("Tick happened!");
    /// }).await;
    /// ```        
    pub async fn register_route<C>(&self, route: &str, cb: C) -> Result<(), anyhow::Error>
    where
        C: Fn(&CommandMessage) -> CommandMessage + Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let msg = ActorMessage::RegisterRoute {
            respond_to: send,
            route: route.to_string(),
            cb: Box::new(cb),
        };

        // Ignore send errors. If this send fails, so does the
        // recv.await below. There's no reason to check for the
        // same failure twice.
        let _ = self.sender.send(msg).await;
        match recv.await {
            Ok(_) => Ok(()),
            Err(err) => return Err(anyhow!("Error registering route: {}", err)),
        }
    }

    /// Registers a synchronous callback to be invoked on each tick.
    ///
    /// # Arguments
    ///
    /// * `cb` - The callback function to be invoked on each tick.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let actor = MechActor::new(Duration::from_secs(1));
    /// let _ = actor.register_tick(|| {
    ///     println!("Tick happened!");
    /// }).await;
    /// ```    
    pub async fn register_tick<C>(&self, mut cb: C) -> Result<(), anyhow::Error>
    where
        C: FnMut() -> () + Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let msg = ActorMessage::RegisterTick {
            respond_to: send,
            cb: Box::new(move || cb()),
        };

        // Ignore send errors. If this send fails, so does the
        // recv.await below. There's no reason to check for the
        // same failure twice.
        let _ = self.sender.send(msg).await;
        match recv.await {
            Ok(_) => Ok(()),
            Err(err) => return Err(anyhow!("Error registering tick: {}", err)),
        }
    }

    /// Registers an asynchronous callback to be invoked on a matching route.
    ///
    /// # Arguments
    ///
    /// * `route` - String identifying the route.
    /// * `cb` - The async callback function to be invoked on each tick.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let actor = MechActor::new(Duration::from_secs(1));
    /// let _ = actor.register_async_route( "MyRoute".to_string(), || {
    ///     Box::pin(async {
    ///         println!("Async tick happened!");
    ///     })
    /// }).await;
    /// ```        
    pub async fn register_async_route<C, Fut>(
        &self,
        route: &str,
        cb: C,
    ) -> Result<(), anyhow::Error>
    where
        C: Fn(&CommandMessage) -> Fut + Send + 'static,
        Fut: Future<Output = CommandMessage> + Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let msg = ActorMessage::RegisterAsyncRoute {
            respond_to: send,
            route: route.to_string(),
            cb: Box::new(move |cmd| Box::pin(cb(cmd))),
        };

        let _ = self.sender.send(msg).await;
        match recv.await {
            Ok(_) => Ok(()),
            Err(err) => return Err(anyhow!("Error registering route: {}", err)),
        }
    }

    /// Registers an asynchronous callback to be invoked on each tick.
    ///
    /// # Arguments
    ///
    /// * `cb` - The async callback function to be invoked on each tick.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let actor = MechActor::new(Duration::from_secs(1));
    /// let _ = actor.register_async_tick(|| {
    ///     Box::pin(async {
    ///         println!("Async tick happened!");
    ///     })
    /// }).await;
    /// ```    
    pub async fn register_async_tick<C, Fut>(&self, mut cb: C) -> Result<(), anyhow::Error>
    where
        C: FnMut() -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let msg = ActorMessage::RegisterAsyncTick {
            respond_to: send,
            cb: Box::new(move || Box::pin(cb())),
        };

        let _ = self.sender.send(msg).await;
        match recv.await {
            Ok(_) => Ok(()),
            Err(err) => return Err(anyhow!("Error registering tick: {}", err)),
        }
    }

    /// Shuts down the `MechActor`.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let _ = actor.shutdown().await;
    /// ```    
    pub async fn shutdown(&self) -> Result<(), anyhow::Error> {
        let (_, recv) = oneshot::channel::<u32>();
        let msg = ActorMessage::Shutdown;

        // Ignore send errors. If this send fails, so does the
        // recv.await below. There's no reason to check for the
        // same failure twice.
        let _ = self.sender.send(msg).await;

        match recv.await {
            Ok(_) => Ok(()),
            Err(err) => return Err(anyhow!("Error shutting down Actor: {}", err)),
        }
    }
}