Skip to main content

datex_core/runtime/
runner.rs

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