crb_runtime/runtime.rs
1//! A runtime for composable blocks.
2
3use crate::context::ReachableContext;
4use crate::interruptor::{InterruptionLevel, Interruptor};
5use async_trait::async_trait;
6use std::ops::DerefMut;
7
8/// The `Runtime` trait implements an asynchronous task that can be interrupted.
9///
10/// Consequently, this trait must implement the `Send` marker trait, allowing the runtime
11/// to move between different threads of the asynchronous reactor, as well as the `'static` lifetime,
12/// which enables encapsulating the runtime in a `Box`.
13#[async_trait]
14pub trait Runtime: Send + 'static {
15 /// The `get_interruptor` method returns an instance of an interruptor.
16 ///
17 /// The reutrned value implements the `Interruptor` trait and can be used by any system
18 /// launching the agent's runtime to interrupt its execution. The implementation of the `Interruptor`
19 /// depends on the entity implementing the `Runtime`.
20 fn get_interruptor(&mut self) -> Box<dyn Interruptor>;
21
22 /// The `interruption_level` method returns the default level at which the runtime
23 /// should be interrupted.
24 ///
25 /// Since the interruption system has different levels to allow for a graceful termination
26 /// of the runtime, even if it is deeply nested in coroutines, this enables a smooth shutdown
27 /// starting from the deepest level.
28 fn interruption_level(&self) -> InterruptionLevel {
29 InterruptionLevel::EVENT
30 }
31
32 /// The asynchronous `routine` method is the primary execution method of the `Runtime`.
33 ///
34 /// It is called by the activity that runs (owns) the `Runtime`.
35 async fn routine(&mut self);
36}
37
38pub trait InteractiveRuntime: Runtime {
39 /// Type of the composable block's contenxt.
40 type Context: ReachableContext;
41
42 fn address(&self) -> <Self::Context as ReachableContext>::Address;
43}
44
45#[async_trait]
46impl Runtime for Box<dyn Runtime> {
47 fn get_interruptor(&mut self) -> Box<dyn Interruptor> {
48 self.deref_mut().get_interruptor()
49 }
50
51 async fn routine(&mut self) {
52 self.deref_mut().routine().await
53 }
54}