Skip to main content

datex_core/runtime/
internal.rs

1use crate::{
2    channel::mpsc::{UnboundedReceiver, create_unbounded_channel},
3    collections::HashMap,
4    core_compiler::{
5        core_compilation_context::DXBWithSharedValues, core_compile,
6        instruction_input::InstructionInput,
7    },
8    datex_registry::{all_datex_types, get_all_modules},
9    dif::dif_interface::DIFInterface,
10    disassembler::{
11        options::DisassemblerOptions, print_disassembled_with_options,
12    },
13    global::{
14        dxb_block::{
15            DXBBlock, IncomingEndpointContextSectionId, IncomingSection,
16            OutgoingContextId,
17        },
18        protocol_structures::{
19            block_header::{BlockHeader, FlagsAndTimestamp},
20            encrypted_header::EncryptedHeader,
21            routing_header::RoutingHeader,
22        },
23    },
24    libs::core::CoreLibrary,
25    network::{
26        block_handler::{
27            IncomingSectionReceiver, create_incoming_sections_channel,
28        },
29        com_hub::{
30            ComHub, ComInterfaceReconnectRequest, InterfacePriority,
31            network_response::ResponseOptions,
32        },
33        com_interfaces::local_loopback_interface::LocalLoopbackInterfaceSetupData,
34    },
35    prelude::*,
36    random::RandomState,
37    runtime::{
38        Runtime, RuntimeConfig, RuntimeConfigInterface,
39        cache::shared_references_cache::SharedReferencesCache,
40        execution::{
41            ExecutionError,
42            context::{
43                ExecutionContext, ExecutionMode,
44                FinalOrPersistedExecutionContext, RemoteExecutionContext,
45                RemoteExecutionTarget, ScriptExecutionError,
46            },
47            execution_input::ExecutionCallerMetadata,
48            remote_execution_options::RemoteExecutionOptions,
49        },
50        pointer_address_provider::SelfOwnedPointerAddressProvider,
51        pointer_availability_lookup::PointerAvailabilityLookup,
52        remote_value_sync::{
53            SubscriberError, synced_value_data::SyncedValueData,
54        },
55    },
56    shared_values::{
57        SharedContainer, base_shared_value_container::observers::TransceiverId,
58    },
59    time::{Instant, now_ms},
60    types::r#type::Type,
61    utils::task_manager::TaskManager,
62    values::{
63        core_values::endpoint::Endpoint, value_container::ValueContainer,
64    },
65};
66use alloc::rc::Rc;
67use core::{
68    cell::{Ref, RefCell, RefMut, UnsafeCell},
69    ops::DerefMut,
70    pin::Pin,
71};
72use datex_macros_internal::Datex;
73use futures_util::future::join_all;
74use indexmap::IndexMap;
75use log::{debug, error, info};
76
77pub type RemoteExecutionResult = Result<Option<ValueContainer>, ExecutionError>;
78
79#[derive(Datex, Debug, Clone, PartialEq, Eq, Hash)]
80#[datex(structural)]
81pub struct HeapStats {
82    /// Total heap size
83    pub total: usize,
84    /// Currently used heap size
85    pub used: usize,
86    /// Maximum used heap size since startup
87    pub max_used: usize,
88}
89
90#[derive(Datex, Debug, Clone, PartialEq, Eq, Hash, Default)]
91#[datex(structural)]
92pub struct RuntimeStats {
93    pub heap: Option<HeapStats>,
94}
95
96#[derive(Datex, Debug, Clone)]
97#[datex(structural)]
98/// General static information about the runtime, e.g. version numbers.
99pub struct RuntimeInfo {
100    datex_version: String,
101    other_versions: IndexMap<String, String, RandomState>,
102    device_type: Option<String>,
103    running_since: u64,
104}
105
106#[derive(Debug, Clone, Default)]
107pub struct CustomRuntimeInfo {
108    pub device_type: Option<String>,
109    pub other_versions: IndexMap<String, String, RandomState>,
110}
111
112#[derive(Debug)]
113pub struct RuntimeInternal {
114    endpoint: UnsafeCell<Endpoint>,
115    info: RefCell<RuntimeInfo>,
116
117    core_library: CoreLibrary,
118
119    shared_references_cache: RefCell<SharedReferencesCache>,
120    pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
121    com_hub: Rc<ComHub>,
122    config: UnsafeCell<RuntimeConfig>,
123
124    /// Public endpoint interface properties
125    endpoint_properties: RefCell<IndexMap<String, ValueContainer, RandomState>>,
126
127    /// counter to keep track of transceiver ids
128    transceiver_counter: RefCell<u8>,
129
130    task_manager: TaskManager,
131
132    /// receiver for incoming sections from com hub
133    incoming_sections_receiver: RefCell<IncomingSectionReceiver>,
134
135    /// receiver for incoming interface reconnect requests from com hub
136    com_interface_reconnect_request_receiver:
137        RefCell<UnboundedReceiver<ComInterfaceReconnectRequest>>,
138
139    /// active execution contexts, stored by context_id
140    execution_contexts:
141        RefCell<HashMap<IncomingEndpointContextSectionId, ExecutionContext>>,
142
143    pointer_availability_lookup: RefCell<PointerAvailabilityLookup>,
144
145    synced_value_data: RefCell<SyncedValueData>,
146
147    stats_provider: RefCell<fn() -> RuntimeStats>,
148}
149
150impl From<Rc<RuntimeInternal>> for Runtime {
151    fn from(value: Rc<RuntimeInternal>) -> Self {
152        Runtime { internal: value }
153    }
154}
155
156impl RuntimeInternal {
157    pub(crate) fn new(
158        endpoint: Endpoint,
159        shared_references_cache: RefCell<SharedReferencesCache>,
160        pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
161        config: RuntimeConfig,
162        com_hub: Rc<ComHub>,
163        task_manager: TaskManager,
164        incoming_sections_receiver: IncomingSectionReceiver,
165        com_interface_reconnect_request_receiver: UnboundedReceiver<
166            ComInterfaceReconnectRequest,
167        >,
168        info: CustomRuntimeInfo,
169    ) -> RuntimeInternal {
170        let pointer_availability_lookup =
171            PointerAvailabilityLookup::new(endpoint.clone());
172        let internal = RuntimeInternal {
173            info: RefCell::new(RuntimeInfo {
174                device_type: info.device_type,
175                other_versions: info.other_versions,
176                datex_version: env!("CARGO_PKG_VERSION").to_string(),
177                running_since: now_ms(),
178            }),
179            endpoint: UnsafeCell::new(endpoint),
180            shared_references_cache,
181            pointer_address_provider,
182            config: UnsafeCell::new(config),
183            com_hub,
184            task_manager,
185            endpoint_properties: RefCell::new(IndexMap::default()),
186            core_library: CoreLibrary::default(),
187            incoming_sections_receiver: RefCell::new(
188                incoming_sections_receiver,
189            ),
190            com_interface_reconnect_request_receiver: RefCell::new(
191                com_interface_reconnect_request_receiver,
192            ),
193            synced_value_data: RefCell::new(SyncedValueData::default()),
194            execution_contexts: RefCell::new(HashMap::new()),
195            transceiver_counter: RefCell::new(0),
196            pointer_availability_lookup: RefCell::new(
197                pointer_availability_lookup,
198            ),
199            stats_provider: RefCell::new(RuntimeStats::default),
200        };
201
202        internal.register_static_data();
203
204        internal
205    }
206
207    /// Registers global modules and types in the cache
208    fn register_static_data(&self) {
209        let mut cache = self.shared_references_cache_mut();
210        let cache = cache.deref_mut();
211
212        // register all registered rust modules as datex endpoint properties
213        let modules = get_all_modules(cache);
214        for (name, value) in modules {
215            self.register_endpoint_property(&name, value.into());
216        }
217
218        // register all types in cache
219        let types = all_datex_types(cache);
220        for ty in types {
221            if let Type::Entity(ty) = ty
222                && let SharedContainer::Owned(container) = ty.shared_container()
223            {
224                cache.register_owned_shared_container(
225                    &container.derive_with_max_mutability(),
226                )
227            }
228        }
229    }
230
231    pub fn version(&self) -> Ref<'_, String> {
232        Ref::map(self.info.borrow(), |info| &info.datex_version)
233    }
234
235    pub fn info(&self) -> Ref<'_, RuntimeInfo> {
236        self.info.borrow()
237    }
238
239    pub fn config(&self) -> &RuntimeConfig {
240        unsafe { &*self.config.get() }
241    }
242
243    /// Updates the runtime config.
244    /// This might not have the expected effect when the runtime is already running.
245    ///
246    /// # Safety
247    /// The caller should only call this on an uninitialized runtime.
248    pub unsafe fn set_config(&self, config: RuntimeConfig) {
249        unsafe {
250            *self.config.get() = config;
251        }
252        // also update endpoint
253        unsafe {
254            let endpoint = self.config().endpoint.clone();
255            *self.endpoint.get() = endpoint.clone();
256            *self.com_hub.endpoint.get() = endpoint;
257        }
258    }
259
260    /// Updates the running_since timestamp in the runtime info to the current time.
261    pub fn reset_running_since(&self) {
262        self.info.borrow_mut().running_since = now_ms();
263    }
264
265    /// Registers a new callback that provides [RuntimeStats]
266    pub fn set_stats_provider(&self, stats_provider: fn() -> RuntimeStats) {
267        *self.stats_provider.borrow_mut() = stats_provider;
268    }
269
270    pub fn get_stats(&self) -> RuntimeStats {
271        self.stats_provider.borrow()()
272    }
273
274    pub fn com_hub(&self) -> Rc<ComHub> {
275        self.com_hub.clone()
276    }
277    pub fn endpoint(&self) -> &Endpoint {
278        unsafe { &*self.endpoint.get() }
279    }
280    pub fn endpoint_properties(
281        &self,
282    ) -> Ref<'_, IndexMap<String, ValueContainer, RandomState>> {
283        self.endpoint_properties.borrow()
284    }
285    pub fn endpoint_properties_mut(
286        &self,
287    ) -> RefMut<'_, IndexMap<String, ValueContainer, RandomState>> {
288        self.endpoint_properties.borrow_mut()
289    }
290    pub fn get_endpoint_property_by_name(
291        &'_ self,
292        key: &str,
293    ) -> Option<Ref<'_, ValueContainer>> {
294        Ref::filter_map(self.endpoint_properties.borrow(), |props| {
295            props.get(key)
296        })
297        .ok()
298    }
299    pub fn get_endpoint_property_by_name_mut(
300        &'_ self,
301        key: &str,
302    ) -> Option<RefMut<'_, ValueContainer>> {
303        RefMut::filter_map(self.endpoint_properties.borrow_mut(), |props| {
304            props.get_mut(key)
305        })
306        .ok()
307    }
308
309    pub fn register_endpoint_property(
310        &self,
311        name: &str,
312        value: ValueContainer,
313    ) {
314        self.endpoint_properties_mut()
315            .insert(name.to_string(), value);
316    }
317
318    pub fn pointer_availability_lookup(
319        &self,
320    ) -> Ref<'_, PointerAvailabilityLookup> {
321        self.pointer_availability_lookup.borrow()
322    }
323    pub fn pointer_availability_lookup_mut(
324        &self,
325    ) -> RefMut<'_, PointerAvailabilityLookup> {
326        self.pointer_availability_lookup.borrow_mut()
327    }
328    pub fn synced_value_data(&self) -> Ref<'_, SyncedValueData> {
329        self.synced_value_data.borrow()
330    }
331    pub fn synced_value_data_mut(&self) -> RefMut<'_, SyncedValueData> {
332        self.synced_value_data.borrow_mut()
333    }
334
335    pub fn shared_references_cache_refcell(
336        &self,
337    ) -> &RefCell<SharedReferencesCache> {
338        &self.shared_references_cache
339    }
340
341    pub fn shared_references_cache(&self) -> Ref<'_, SharedReferencesCache> {
342        self.shared_references_cache.borrow()
343    }
344
345    pub fn shared_references_cache_mut(
346        &self,
347    ) -> RefMut<'_, SharedReferencesCache> {
348        self.shared_references_cache.borrow_mut()
349    }
350
351    pub fn core_library(&self) -> &CoreLibrary {
352        &self.core_library
353    }
354
355    pub fn pointer_address_provider_mut(
356        &self,
357    ) -> RefMut<'_, SelfOwnedPointerAddressProvider> {
358        self.pointer_address_provider.borrow_mut()
359    }
360    pub fn incoming_sections_receiver_mut(
361        &self,
362    ) -> RefMut<'_, IncomingSectionReceiver> {
363        self.incoming_sections_receiver.borrow_mut()
364    }
365    pub fn com_interface_reconnect_request_receiver_mut(
366        &self,
367    ) -> RefMut<'_, UnboundedReceiver<ComInterfaceReconnectRequest>> {
368        self.com_interface_reconnect_request_receiver.borrow_mut()
369    }
370    pub fn task_manager(&self) -> &TaskManager {
371        &self.task_manager
372    }
373
374    pub fn stub() -> RuntimeInternal {
375        let (incoming_sections_sender, incoming_sections_receiver) =
376            create_incoming_sections_channel();
377        let (reconnect_request_sender, reconnect_request_receiver) =
378            create_unbounded_channel();
379
380        RuntimeInternal::new(
381            Endpoint::default(),
382            RefCell::new(SharedReferencesCache::default()),
383            Rc::new(RefCell::new(SelfOwnedPointerAddressProvider::new(
384                Endpoint::default(),
385            ))),
386            RuntimeConfig::default(),
387            ComHub::create(
388                Endpoint::default(),
389                incoming_sections_sender,
390                reconnect_request_sender,
391                0,
392            )
393            .0,
394            TaskManager::create().0,
395            incoming_sections_receiver,
396            reconnect_request_receiver,
397            CustomRuntimeInfo::default(),
398        )
399    }
400
401    /// Creates all interfaces configured in the runtime config
402    async fn create_configured_interfaces(&self) {
403        if let Some(interfaces) = &self.config().interfaces {
404            for RuntimeConfigInterface {
405                interface_type,
406                config,
407                priority,
408            } in interfaces.iter()
409            {
410                let create_future = self
411                    .com_hub
412                    .clone()
413                    .create_interface(interface_type, config.clone(), *priority)
414                    .await;
415                match create_future {
416                    Err(err) => {
417                        error!(
418                            "Failed to create interface \"{interface_type}\": {err}"
419                        );
420                        // request reconnect attempts in background
421                        self.com_hub
422                            .reconnect_interface_sender
423                            .borrow_mut()
424                            .start_send(ComInterfaceReconnectRequest::new(
425                                interface_type.clone(),
426                                config.clone(),
427                                *priority,
428                            ))
429                            .unwrap();
430                    }
431                    Ok((_, ready_receiver)) => {
432                        if let Some(ready_receiver) = ready_receiver {
433                            let _ = ready_receiver.await;
434                        }
435                    }
436                }
437            }
438        }
439    }
440
441    async fn init_local_loopback_interface(&self) {
442        // add default local loopback interface
443        let local_interface_setup_data =
444            LocalLoopbackInterfaceSetupData.create_interface().unwrap();
445
446        let ready_signal = self
447            .com_hub
448            .clone()
449            .add_interface_from_configuration(
450                local_interface_setup_data,
451                InterfacePriority::None,
452            )
453            .expect("Failed to add local loopback interface");
454        // local loopback interface is single socket interface and should always return a ready signal
455        // which should always resolve to Ok
456        ready_signal.unwrap().await.unwrap()
457    }
458
459    /// Performs asynchronous initialization of the runtime
460    pub(crate) async fn init_async(&self) {
461        // create local loopback interface and other configured interfaces
462        self.init_local_loopback_interface().await;
463        self.create_configured_interfaces().await;
464    }
465
466    #[cfg(feature = "compiler")]
467    pub async fn execute<'a>(
468        self: Rc<RuntimeInternal>,
469        script: &'a str,
470        inserted_values: &'a [ValueContainer],
471        execution_context: Option<
472            impl Into<FinalOrPersistedExecutionContext<'a>>,
473        >,
474        mark_as_debug: bool,
475    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
476        let mut execution_context = Runtime::from(self.clone())
477            .get_or_create_execution_context(execution_context);
478        let compile_start = Instant::now();
479        let execution_context_mut = execution_context.as_mut();
480        let dxb = execution_context_mut.compile(
481            script,
482            inserted_values,
483            execution_context_mut.receivers(),
484        )?;
485        debug!(
486            "[Compilation took {} ms]",
487            compile_start.elapsed().as_millis()
488        );
489        let execute_start = Instant::now();
490        let result = RuntimeInternal::execute_dxb(
491            self,
492            dxb,
493            None,
494            Some(execution_context),
495            mark_as_debug,
496        )
497        .await
498        .map_err(ScriptExecutionError::from);
499        debug!(
500            "[Execution took {} ms]",
501            execute_start.elapsed().as_millis()
502        );
503        result
504    }
505
506    #[cfg(feature = "compiler")]
507    pub fn execute_sync<'a>(
508        self: Rc<RuntimeInternal>,
509        script: &'a str,
510        inserted_values: &'a [ValueContainer],
511        execution_context: Option<
512            impl Into<FinalOrPersistedExecutionContext<'a>>,
513        >,
514    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
515        let mut execution_context = Runtime::from(self.clone())
516            .get_or_create_execution_context(execution_context);
517        let execution_context_mut = execution_context.as_mut();
518
519        let compile_start = Instant::now();
520        let dxb = execution_context_mut.compile(
521            script,
522            inserted_values,
523            execution_context_mut.receivers(),
524        )?;
525        debug!(
526            "[Compilation took {} ms]",
527            compile_start.elapsed().as_millis()
528        );
529        let execute_start = Instant::now();
530        let result = RuntimeInternal::execute_dxb_sync(
531            self,
532            dxb,
533            None,
534            Some(execution_context),
535        )
536        .map_err(ScriptExecutionError::from);
537        debug!(
538            "[Execution took {} ms]",
539            execute_start.elapsed().as_millis()
540        );
541        result
542    }
543
544    pub fn execute_dxb<'a>(
545        self: Rc<RuntimeInternal>,
546        input: DXBWithSharedValues,
547        initial_stack_values: Option<Vec<ValueContainer>>,
548        execution_context: Option<
549            impl Into<FinalOrPersistedExecutionContext<'a>> + 'a,
550        >,
551        mark_as_debug: bool,
552    ) -> Pin<
553        Box<
554            dyn Future<Output = Result<Option<ValueContainer>, ExecutionError>>
555                + 'a,
556        >,
557    > {
558        Box::pin(async move {
559            let mut execution_context = Runtime::from(self.clone())
560                .get_or_create_execution_context(execution_context);
561            let is_end_of_context = execution_context.is_end_of_context();
562            let execution_context_mut = execution_context.as_mut();
563
564            match execution_context_mut {
565                ExecutionContext::Remote(context) => {
566                    // initial stack values are not (yet) supported for remote execution
567                    if initial_stack_values.is_some() {
568                        return Err(ExecutionError::InvalidExecutionState);
569                    }
570                    RuntimeInternal::execute_remote_single_receiver(
571                        self,
572                        &context.target,
573                        input,
574                        RemoteExecutionOptions {
575                            is_end_of_context,
576                            mark_as_debug,
577                        },
578                    )
579                    .await
580                }
581                ExecutionContext::Local(_) => {
582                    execution_context_mut
583                        .execute_dxb(input, initial_stack_values)
584                        .await
585                }
586            }
587        })
588    }
589
590    pub fn execute_dxb_sync<'a>(
591        self: Rc<RuntimeInternal>,
592        dxb: DXBWithSharedValues,
593        initial_stack_values: Option<Vec<ValueContainer>>,
594        execution_context: Option<
595            impl Into<FinalOrPersistedExecutionContext<'a>>,
596        >,
597    ) -> Result<Option<ValueContainer>, ExecutionError> {
598        let mut execution_context = Runtime::from(self.clone())
599            .get_or_create_execution_context(execution_context);
600        // TODO: pass is_end_of_context to local execution?
601        // let is_end_of_context = execution_context.is_end_of_context();
602        let execution_context_mut = execution_context.as_mut();
603
604        match execution_context_mut {
605            ExecutionContext::Remote(_) => {
606                Err(ExecutionError::RequiresAsyncExecution)
607            }
608            ExecutionContext::Local(_) => execution_context_mut
609                .execute_dxb_sync(dxb, initial_stack_values),
610        }
611    }
612
613    /// Returns the existing execution context for the given context_id,
614    /// or creates a new one if it doesn't exist.
615    /// To reuse the context later, the caller must store it back in the map after use.
616    fn take_or_create_execution_context(
617        self: Rc<RuntimeInternal>,
618        context_id: &IncomingEndpointContextSectionId,
619        incoming_section: &IncomingSection,
620    ) -> ExecutionContext {
621        let runtime = Runtime::from(self.clone());
622        let mut execution_contexts = self.execution_contexts.borrow_mut();
623        // get execution context by context_id or create a new one if it doesn't exist
624        let execution_context = execution_contexts.remove(context_id);
625        if let Some(context) = execution_context {
626            context
627        } else {
628            let caller_metadata = ExecutionCallerMetadata {
629                endpoint: incoming_section.get_sender(),
630            };
631            ExecutionContext::local(
632                ExecutionMode::unbounded(),
633                runtime,
634                caller_metadata,
635            )
636        }
637    }
638
639    /// Executes a remote block expecting a single receiver.
640    /// # Safety
641    /// The caller must ensure, to pass an remote execution context with a single receiver.
642    pub async fn execute_remote_single_receiver(
643        self: Rc<RuntimeInternal>,
644        remote_execution_target: &RemoteExecutionTarget,
645        input: DXBWithSharedValues,
646        options: RemoteExecutionOptions,
647    ) -> RemoteExecutionResult {
648        if remote_execution_target.endpoints().len() != 1 {
649            panic!(
650                "execute_remote_single_receiver called with remote_execution_context that has more than one endpoint"
651            );
652        }
653        self.execute_remote(remote_execution_target, input, options)
654            .await?
655            .remove(0)
656            .0
657    }
658
659    /// Execute a remote block, waiting for all the peers to send their response.
660    /// It might be, that a subset of the responses are errors
661    pub async fn execute_remote(
662        self: Rc<RuntimeInternal>,
663        remote_execution_target: &RemoteExecutionTarget,
664        input: DXBWithSharedValues,
665        options: RemoteExecutionOptions,
666    ) -> Result<Vec<(RemoteExecutionResult, Endpoint)>, SubscriberError> {
667        let routing_header: RoutingHeader = RoutingHeader::default()
668            .with_sender(self.endpoint().clone())
669            .to_owned();
670
671        // get existing context_id for context, or create a new one
672        let context_id = {
673            let mut context_ref =
674                remote_execution_target.context_id.borrow_mut();
675            context_ref.unwrap_or_else(|| {
676                let id = self.com_hub.block_handler.get_new_context_id();
677                // if the context_id is not set, we create a new one
678                *context_ref = Some(id);
679                id
680            })
681        };
682        let block_header = BlockHeader {
683            context_id,
684            flags_and_timestamp: FlagsAndTimestamp::default()
685                .with_is_end_of_context(options.is_end_of_context)
686                .with_is_debug_block(options.mark_as_debug),
687            ..BlockHeader::default()
688        };
689        let encrypted_header = EncryptedHeader::default();
690
691        let mut block = DXBBlock::new(
692            routing_header,
693            block_header,
694            encrypted_header,
695            input.dxb,
696        );
697
698        block.set_receivers(remote_execution_target.endpoints());
699        // TODO: ensure in remote_execution_context that endpoints are never empty
700        unsafe {
701            self.clone().register_shared_containers_for_endpoints(
702                &(remote_execution_target
703                    .endpoints()
704                    .iter()
705                    .collect::<Vec<_>>()),
706                input.shared_values,
707            )?;
708        }
709
710        let responses = self
711            .com_hub
712            .send_own_block_await_response(block, ResponseOptions::default())
713            .await;
714
715        let self_clone = self.clone();
716
717        let futures_with_endpoint = responses
718            .into_iter()
719            .filter(|response| {
720                // pipe trought all response errors, and the ones with an specified endpoint
721                // to skip the [Response::Unspecified] cases to be executed
722                response.is_err()
723                    || matches!(response, Ok(re) if re.endpoint().is_some())
724            })
725            .map(|response| {
726                let self_clone = self_clone.clone();
727                let endpoint = response
728                    .as_ref()
729                    .map(|r| {
730                        r.endpoint()
731                            .cloned()
732                            .expect("Expected endpoint to be present")
733                    })
734                    .unwrap_or_else(|e| e.endpoint().clone());
735                (
736                    async move {
737                        let response = response?;
738                        let incoming_section = response.take_incoming_section();
739                        RuntimeInternal::execute_incoming_section(
740                            self_clone,
741                            incoming_section,
742                            None,
743                        )
744                        .await
745                        .0
746                    },
747                    endpoint,
748                )
749            });
750
751        let (future, endpoint) = futures_with_endpoint
752            .into_iter()
753            .unzip::<_, _, Vec<_>, Vec<_>>();
754
755        Ok(join_all(future)
756            .await
757            .into_iter()
758            .zip(endpoint)
759            .collect::<Vec<_>>())
760    }
761
762    pub async fn execute_instructions_remote(
763        self: Rc<RuntimeInternal>,
764        endpoints: Vec<Endpoint>,
765        instructions_input: Vec<InstructionInput>,
766        mark_as_debug: bool,
767    ) -> Result<Vec<(RemoteExecutionResult, Endpoint)>, SubscriberError> {
768        let dxb = core_compile(
769            &self.pointer_availability_lookup(),
770            &endpoints,
771            instructions_input,
772            self.shared_references_cache_mut().deref_mut(),
773        );
774
775        let remote_execution_context = RemoteExecutionContext::new(
776            endpoints,
777            ExecutionMode::Static,
778            Runtime::from(self.clone()),
779        );
780        self.execute_remote(
781            &remote_execution_context.target,
782            dxb,
783            RemoteExecutionOptions {
784                mark_as_debug,
785                is_end_of_context: true,
786            },
787        )
788        .await
789    }
790
791    pub async fn execute_instructions_remote_single_receiver(
792        self: Rc<RuntimeInternal>,
793        endpoint: Endpoint,
794        instructions_input: Vec<InstructionInput>,
795        mark_as_debug: bool,
796    ) -> RemoteExecutionResult {
797        RuntimeInternal::execute_instructions_remote(
798            self,
799            vec![endpoint],
800            instructions_input,
801            mark_as_debug,
802        )
803        .await?
804        .remove(0)
805        .0
806    }
807
808    pub(crate) async fn execute_incoming_section(
809        self: Rc<RuntimeInternal>,
810        mut incoming_section: IncomingSection,
811        shared_values: Option<Vec<SharedContainer>>,
812    ) -> (
813        Result<Option<ValueContainer>, ExecutionError>,
814        Endpoint,
815        OutgoingContextId,
816        bool,
817    ) {
818        let section_context_id =
819            incoming_section.get_section_context_id().clone();
820        let mut context = Self::take_or_create_execution_context(
821            self.clone(),
822            &section_context_id,
823            &incoming_section,
824        );
825        info!(
826            "Executing incoming section with index: {}",
827            incoming_section.get_section_index()
828        );
829
830        let mut result = None;
831        let mut last_block = None;
832
833        // iterate over the blocks in the incoming section
834        loop {
835            let block = incoming_section.next().await;
836            if let Some(block) = block {
837                let res = RuntimeInternal::execute_dxb_block_local(
838                    self.clone(),
839                    block.clone(),
840                    Some(&mut context),
841                    // NOTE: this assumes that all shared values are only needed as references, not as owned values
842                    shared_values.clone(),
843                )
844                .await;
845                if let Err(err) = res {
846                    return (
847                        Err(err),
848                        block.sender().clone(),
849                        block.block_header.context_id,
850                        block.block_header.flags_and_timestamp.is_debug_block(),
851                    );
852                }
853                result = res.unwrap();
854                last_block = Some(block);
855            } else {
856                break;
857            }
858        }
859
860        if last_block.is_none() {
861            unreachable!("Incoming section must contain at least one block");
862        }
863        let last_block = last_block.unwrap();
864        let sender_endpoint = last_block.sender().clone();
865        let context_id = last_block.block_header.context_id;
866        let is_end_of_context = last_block
867            .block_header
868            .flags_and_timestamp
869            .is_end_of_context();
870        let is_debug =
871            last_block.block_header.flags_and_timestamp.is_debug_block();
872
873        // insert the context back into the map for future use if not end of context
874        if !is_end_of_context {
875            self.execution_contexts
876                .borrow_mut()
877                .insert(section_context_id, context);
878        }
879
880        (Ok(result), sender_endpoint, context_id, is_debug)
881    }
882
883    async fn execute_dxb_block_local(
884        self: Rc<RuntimeInternal>,
885        block: DXBBlock,
886        execution_context: Option<&mut ExecutionContext>,
887        shared_values: Option<Vec<SharedContainer>>,
888    ) -> Result<Option<ValueContainer>, ExecutionError> {
889        let mut execution_context = Runtime::from(self.clone())
890            .get_or_create_execution_context(execution_context);
891        let execution_context_mut = execution_context.as_mut();
892
893        // assert that the execution context is local
894        if !core::matches!(execution_context_mut, ExecutionContext::Local(_)) {
895            unreachable!(
896                "Execution context must be local for executing a DXB block"
897            );
898        }
899        let dxb = block.body;
900        info!("executing on {}:\n", self.endpoint());
901
902        print_disassembled_with_options(&dxb, DisassemblerOptions::default());
903
904        let _end_execution =
905            block.block_header.flags_and_timestamp.is_end_of_section();
906
907        RuntimeInternal::execute_dxb(
908            self,
909            DXBWithSharedValues::new(dxb, shared_values.unwrap_or_default()),
910            None,
911            Some(execution_context),
912            false,
913        )
914        .await
915    }
916
917    /// Registers a list of shared containers for a single endpoint.
918    pub fn register_shared_containers_for_single_endpoint(
919        self: Rc<Self>,
920        endpoint: &Endpoint,
921        shared_containers: Vec<SharedContainer>,
922    ) {
923        unsafe {
924            self.register_shared_containers_for_endpoints(
925                &[endpoint],
926                shared_containers,
927            )
928            .unwrap()
929        }
930    }
931
932    /// Registers a list of shared containers for a list of endpoints to subscribe.
933    /// Note: only self owned pointers are registered, others are skipped
934    ///
935    /// # Safety
936    /// The caller must ensure that endpoints is not empty.
937    pub unsafe fn register_shared_containers_for_endpoints(
938        self: Rc<Self>,
939        endpoints: &[&Endpoint],
940        shared_containers: Vec<SharedContainer>,
941    ) -> Result<(), SubscriberError> {
942        if endpoints.is_empty() {
943            panic!("endpoints must not be empty");
944        }
945
946        for shared_container in shared_containers {
947            // subscribe (remote) endpoints to own container
948            if shared_container.is_self_owned() {
949                for endpoint in endpoints {
950                    // SAFETY: We checked that the shared container is self-owned
951                    unsafe {
952                        self.clone()
953                            .subscribe_endpoint_to_owned_value(
954                                &shared_container,
955                                endpoint,
956                                shared_container
957                                    .derive_reference_with_max_mutability()
958                                    .reference_mutability(),
959                            )
960                            .map_err(SubscriberError::Observer)?
961                    }
962                    // also store the subscribed pointer in cache so that we can handle incoming
963                    // pointer updates from the subscribers
964                    self.shared_references_cache
965                        .borrow_mut()
966                        .register_owned_shared_container(
967                            &shared_container
968                                .derive_reference_with_max_mutability(),
969                        );
970                }
971            }
972        }
973
974        Ok(())
975    }
976
977    pub fn get_env(&self) -> IndexMap<String, String, RandomState> {
978        self.config().env.clone().unwrap_or_default()
979    }
980
981    /// Get the human-readable name of the endpoint (can be provided in config)
982    pub fn get_name(&self) -> Option<String> {
983        self.config().name.clone()
984    }
985
986    /// Creates a new [DIFInterface] with a unique transceiver id and the runtime's pointer address provider
987    pub fn create_dif_interface(&self) -> DIFInterface {
988        let count = *self.transceiver_counter.borrow();
989        let id = TransceiverId::Dif(count);
990        self.transceiver_counter.replace(count + 1);
991        DIFInterface::new(id, self.pointer_address_provider.clone())
992    }
993}