Skip to main content

datex_core/runtime/
runner.rs

1use crate::{
2    channel::mpsc::create_unbounded_channel,
3    global::dxb_block::IncomingSection,
4    network::com_hub::ComHub,
5    prelude::*,
6    runtime::{
7        Runtime, RuntimeConfig, RuntimeInternal,
8        cache::shared_references_cache::SharedReferencesCache,
9        pointer_address_provider::SelfOwnedPointerAddressProvider,
10    },
11    time::now_ms,
12    utils::task_manager::TaskManager,
13};
14use async_select::select;
15use core::{cell::RefCell, pin::Pin};
16use futures::channel::oneshot;
17use futures_util::{
18    future,
19    future::{Join, join},
20    join,
21};
22use log::info;
23
24pub struct RuntimeRunner {
25    pub runtime: Runtime,
26    pub task_future: Pin<Box<dyn Future<Output = ()>>>,
27}
28
29impl RuntimeRunner {
30    /// Creates a new runtime instance with the given configuration and global context.
31    /// Note: If the endpoint is not specified in the config, a random endpoint will be generated.
32    pub fn new(config: RuntimeConfig) -> RuntimeRunner {
33        let endpoint = config.endpoint.clone();
34
35        let (task_manager, runtime_task_future) = TaskManager::create();
36
37        let (incoming_sections_sender, incoming_sections_receiver) =
38            create_unbounded_channel::<IncomingSection>();
39
40        let (com_hub, com_hub_task_future) =
41            ComHub::create(endpoint.clone(), incoming_sections_sender);
42        let memory = RefCell::new(SharedReferencesCache::default());
43        let pointer_address_provider = Rc::new(RefCell::new(
44            SelfOwnedPointerAddressProvider::new(endpoint.clone()),
45        ));
46
47        let runtime = Runtime::new(RuntimeInternal::new(
48            endpoint,
49            memory,
50            pointer_address_provider,
51            config,
52            com_hub,
53            task_manager,
54            incoming_sections_receiver,
55        ));
56
57        let runtime_internal = runtime.internal.clone();
58
59        // await all task futures
60        let task_future = async {
61            join!(
62                // com hub task manager
63                com_hub_task_future,
64                // runtime task manager
65                runtime_task_future,
66                // runtime incoming sections handler
67                runtime_internal.handle_incoming_sections_task()
68            );
69        };
70
71        RuntimeRunner {
72            runtime,
73            task_future: Box::pin(task_future),
74        }
75    }
76
77    // Starts the runtime, runs the provided app logic, and returns its result.
78    // The runtime will exit when the app logic completes.
79    pub async fn run<AppReturn, AppFuture>(
80        self,
81        app_logic: impl FnOnce(Runtime) -> AppFuture,
82    ) -> AppReturn
83    where
84        AppFuture: Future<Output = AppReturn>,
85    {
86        let (runtime_future, app_future) =
87            self.create_runtime_and_app_future(app_logic);
88
89        // run until the app logic completes
90        select! {
91            _ = runtime_future => {
92                unreachable!("Runtime task future exited unexpectedly");
93            },
94            exit_value = app_future => {
95                exit_value
96            },
97        }
98    }
99
100    /// Starts the runtime and runs indefinitely, executing the provided app logic.
101    pub async fn run_forever<AppReturn, AppFuture>(
102        self,
103        app_logic: impl FnOnce(Runtime) -> AppFuture,
104    ) -> !
105    where
106        AppFuture: Future<Output = AppReturn>,
107    {
108        let (runtime_future, app_future) =
109            self.create_runtime_and_app_future(app_logic);
110
111        // run indefinitely (runtime future should never exit)
112        future::join(runtime_future, app_future).await;
113        unreachable!("Both runtime and app logic futures exited unexpectedly");
114    }
115
116    /// Creates the runtime future and the app future, ensuring that the app logic starts executing only after the runtime has completed its initialization.
117    fn create_runtime_and_app_future<AppReturn, AppFuture>(
118        self,
119        app_logic: impl FnOnce(Runtime) -> AppFuture,
120    ) -> (
121        Join<impl Future<Output = ()>, impl Future<Output = ()>>,
122        impl Future<Output = AppReturn>,
123    )
124    where
125        AppFuture: Future<Output = AppReturn>,
126    {
127        let (init_ready_sender, init_ready_receiver) = oneshot::channel();
128        let runtime = self.runtime.clone();
129        let version = runtime.version().to_string();
130
131        let runtime_future = join(
132            // initialize the runtime
133            async move {
134                runtime.internal.init_async().await;
135                init_ready_sender.send(()).unwrap();
136            },
137            // run tasks
138            self.task_future,
139        );
140
141        // start the app logic
142        let app_future = async move {
143            // wait for runtime initialization to complete before starting app logic
144            init_ready_receiver.await.unwrap();
145            info!("Runtime initialized - Version {version} Time: {}", now_ms());
146
147            app_logic(self.runtime).await
148        };
149
150        (runtime_future, app_future)
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[tokio::test]
159    async fn runtime_runner() {
160        let runner = RuntimeRunner::new(RuntimeConfig::default());
161        let mut runtime = None;
162        runner
163            .run(async |runtime_inner| {
164                runtime = Some(runtime_inner);
165            })
166            .await;
167
168        assert!(runtime.is_some());
169
170        // check if local loopback interface was fully initialized and is present in the com hub
171        let com_hub = runtime.unwrap().com_hub();
172        let interface_map = com_hub.interfaces_manager().interfaces.borrow();
173        let local_loopback_interface =
174            interface_map.iter().find(|(uuid, interface)| {
175                interface.properties.interface_type == "local"
176            });
177        let (local_loopback_interface_uuid, _) = local_loopback_interface
178            .expect("Local loopback interface not found in com hub");
179
180        // check if socket for the local loopback interface is present in the com hub
181        let socket_map = com_hub.socket_manager().sockets.borrow();
182        let local_loopback_socket = socket_map
183            .values()
184            .find(|socket| {
185                &socket.interface_uuid == local_loopback_interface_uuid
186            })
187            .expect("Local loopback socket not found in com hub");
188    }
189}