datex-core 0.0.14

The DATEX Core Rust implementation
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
use crate::{
    channel::mpsc::{UnboundedReceiver, create_unbounded_channel},
    collections::HashMap,
    core_compiler::{
        core_compilation_context::DXBWithSharedValues, core_compile,
        instruction_input::InstructionInput,
    },
    datex_registry::{all_datex_types, get_all_modules},
    dif::dif_interface::DIFInterface,
    disassembler::{
        options::DisassemblerOptions, print_disassembled_with_options,
    },
    global::{
        dxb_block::{
            DXBBlock, IncomingEndpointContextSectionId, IncomingSection,
            OutgoingContextId,
        },
        protocol_structures::{
            block_header::{BlockHeader, FlagsAndTimestamp},
            encrypted_header::EncryptedHeader,
            routing_header::RoutingHeader,
        },
    },
    libs::core::CoreLibrary,
    network::{
        block_handler::{
            IncomingSectionReceiver, create_incoming_sections_channel,
        },
        com_hub::{
            ComHub, ComInterfaceReconnectRequest, InterfacePriority,
            network_response::ResponseOptions,
        },
        com_interfaces::local_loopback_interface::LocalLoopbackInterfaceSetupData,
    },
    prelude::*,
    random::RandomState,
    runtime::{
        Runtime, RuntimeConfig, RuntimeConfigInterface,
        cache::shared_references_cache::SharedReferencesCache,
        execution::{
            ExecutionError,
            context::{
                ExecutionContext, ExecutionMode,
                FinalOrPersistedExecutionContext, RemoteExecutionContext,
                RemoteExecutionTarget, ScriptExecutionError,
            },
            execution_input::ExecutionCallerMetadata,
            remote_execution_options::RemoteExecutionOptions,
        },
        pointer_address_provider::SelfOwnedPointerAddressProvider,
        pointer_availability_lookup::PointerAvailabilityLookup,
        remote_value_sync::{
            SubscriberError, synced_value_data::SyncedValueData,
        },
    },
    shared_values::{
        SharedContainer, base_shared_value_container::observers::TransceiverId,
    },
    time::{Instant, now_ms},
    types::r#type::Type,
    utils::task_manager::TaskManager,
    values::{
        core_values::endpoint::Endpoint, value_container::ValueContainer,
    },
};
use alloc::rc::Rc;
use core::{
    cell::{Ref, RefCell, RefMut, UnsafeCell},
    ops::DerefMut,
    pin::Pin,
};
use datex_macros_internal::Datex;
use futures_util::future::join_all;
use indexmap::IndexMap;
use log::{debug, error, info};

pub type RemoteExecutionResult = Result<Option<ValueContainer>, ExecutionError>;

#[derive(Datex, Debug, Clone, PartialEq, Eq, Hash)]
#[datex(structural)]
pub struct HeapStats {
    /// Total heap size
    pub total: usize,
    /// Currently used heap size
    pub used: usize,
    /// Maximum used heap size since startup
    pub max_used: usize,
}

#[derive(Datex, Debug, Clone, PartialEq, Eq, Hash, Default)]
#[datex(structural)]
pub struct RuntimeStats {
    pub heap: Option<HeapStats>,
}

#[derive(Datex, Debug, Clone)]
#[datex(structural)]
/// General static information about the runtime, e.g. version numbers.
pub struct RuntimeInfo {
    datex_version: String,
    other_versions: IndexMap<String, String, RandomState>,
    device_type: Option<String>,
    running_since: u64,
}

#[derive(Debug, Clone, Default)]
pub struct CustomRuntimeInfo {
    pub device_type: Option<String>,
    pub other_versions: IndexMap<String, String, RandomState>,
}

#[derive(Debug)]
pub struct RuntimeInternal {
    endpoint: UnsafeCell<Endpoint>,
    info: RefCell<RuntimeInfo>,

    core_library: CoreLibrary,

    shared_references_cache: RefCell<SharedReferencesCache>,
    pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
    com_hub: Rc<ComHub>,
    config: UnsafeCell<RuntimeConfig>,

    /// Public endpoint interface properties
    endpoint_properties: RefCell<IndexMap<String, ValueContainer, RandomState>>,

    /// counter to keep track of transceiver ids
    transceiver_counter: RefCell<u8>,

    task_manager: TaskManager,

    /// receiver for incoming sections from com hub
    incoming_sections_receiver: RefCell<IncomingSectionReceiver>,

    /// receiver for incoming interface reconnect requests from com hub
    com_interface_reconnect_request_receiver:
        RefCell<UnboundedReceiver<ComInterfaceReconnectRequest>>,

    /// active execution contexts, stored by context_id
    execution_contexts:
        RefCell<HashMap<IncomingEndpointContextSectionId, ExecutionContext>>,

    pointer_availability_lookup: RefCell<PointerAvailabilityLookup>,

    synced_value_data: RefCell<SyncedValueData>,

    stats_provider: RefCell<fn() -> RuntimeStats>,
}

impl From<Rc<RuntimeInternal>> for Runtime {
    fn from(value: Rc<RuntimeInternal>) -> Self {
        Runtime { internal: value }
    }
}

impl RuntimeInternal {
    pub(crate) fn new(
        endpoint: Endpoint,
        shared_references_cache: RefCell<SharedReferencesCache>,
        pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
        config: RuntimeConfig,
        com_hub: Rc<ComHub>,
        task_manager: TaskManager,
        incoming_sections_receiver: IncomingSectionReceiver,
        com_interface_reconnect_request_receiver: UnboundedReceiver<
            ComInterfaceReconnectRequest,
        >,
        info: CustomRuntimeInfo,
    ) -> RuntimeInternal {
        let pointer_availability_lookup =
            PointerAvailabilityLookup::new(endpoint.clone());
        let internal = RuntimeInternal {
            info: RefCell::new(RuntimeInfo {
                device_type: info.device_type,
                other_versions: info.other_versions,
                datex_version: env!("CARGO_PKG_VERSION").to_string(),
                running_since: now_ms(),
            }),
            endpoint: UnsafeCell::new(endpoint),
            shared_references_cache,
            pointer_address_provider,
            config: UnsafeCell::new(config),
            com_hub,
            task_manager,
            endpoint_properties: RefCell::new(IndexMap::default()),
            core_library: CoreLibrary::default(),
            incoming_sections_receiver: RefCell::new(
                incoming_sections_receiver,
            ),
            com_interface_reconnect_request_receiver: RefCell::new(
                com_interface_reconnect_request_receiver,
            ),
            synced_value_data: RefCell::new(SyncedValueData::default()),
            execution_contexts: RefCell::new(HashMap::new()),
            transceiver_counter: RefCell::new(0),
            pointer_availability_lookup: RefCell::new(
                pointer_availability_lookup,
            ),
            stats_provider: RefCell::new(RuntimeStats::default),
        };

        internal.register_static_data();

        internal
    }

    /// Registers global modules and types in the cache
    fn register_static_data(&self) {
        let mut cache = self.shared_references_cache_mut();
        let cache = cache.deref_mut();

        // register all registered rust modules as datex endpoint properties
        let modules = get_all_modules(cache);
        for (name, value) in modules {
            self.register_endpoint_property(&name, value.into());
        }

        // register all types in cache
        let types = all_datex_types(cache);
        for ty in types {
            if let Type::Entity(ty) = ty
                && let SharedContainer::Owned(container) = ty.shared_container()
            {
                cache.register_owned_shared_container(
                    &container.derive_with_max_mutability(),
                )
            }
        }
    }

    pub fn version(&self) -> Ref<'_, String> {
        Ref::map(self.info.borrow(), |info| &info.datex_version)
    }

    pub fn info(&self) -> Ref<'_, RuntimeInfo> {
        self.info.borrow()
    }

    pub fn config(&self) -> &RuntimeConfig {
        unsafe { &*self.config.get() }
    }

    /// Updates the runtime config.
    /// This might not have the expected effect when the runtime is already running.
    ///
    /// # Safety
    /// The caller should only call this on an uninitialized runtime.
    pub unsafe fn set_config(&self, config: RuntimeConfig) {
        unsafe {
            *self.config.get() = config;
        }
        // also update endpoint
        unsafe {
            let endpoint = self.config().endpoint.clone();
            *self.endpoint.get() = endpoint.clone();
            *self.com_hub.endpoint.get() = endpoint;
        }
    }

    /// Updates the running_since timestamp in the runtime info to the current time.
    pub fn reset_running_since(&self) {
        self.info.borrow_mut().running_since = now_ms();
    }

    /// Registers a new callback that provides [RuntimeStats]
    pub fn set_stats_provider(&self, stats_provider: fn() -> RuntimeStats) {
        *self.stats_provider.borrow_mut() = stats_provider;
    }

    pub fn get_stats(&self) -> RuntimeStats {
        self.stats_provider.borrow()()
    }

    pub fn com_hub(&self) -> Rc<ComHub> {
        self.com_hub.clone()
    }
    pub fn endpoint(&self) -> &Endpoint {
        unsafe { &*self.endpoint.get() }
    }
    pub fn endpoint_properties(
        &self,
    ) -> Ref<'_, IndexMap<String, ValueContainer, RandomState>> {
        self.endpoint_properties.borrow()
    }
    pub fn endpoint_properties_mut(
        &self,
    ) -> RefMut<'_, IndexMap<String, ValueContainer, RandomState>> {
        self.endpoint_properties.borrow_mut()
    }
    pub fn get_endpoint_property_by_name(
        &'_ self,
        key: &str,
    ) -> Option<Ref<'_, ValueContainer>> {
        Ref::filter_map(self.endpoint_properties.borrow(), |props| {
            props.get(key)
        })
        .ok()
    }
    pub fn get_endpoint_property_by_name_mut(
        &'_ self,
        key: &str,
    ) -> Option<RefMut<'_, ValueContainer>> {
        RefMut::filter_map(self.endpoint_properties.borrow_mut(), |props| {
            props.get_mut(key)
        })
        .ok()
    }

    pub fn register_endpoint_property(
        &self,
        name: &str,
        value: ValueContainer,
    ) {
        self.endpoint_properties_mut()
            .insert(name.to_string(), value);
    }

    pub fn pointer_availability_lookup(
        &self,
    ) -> Ref<'_, PointerAvailabilityLookup> {
        self.pointer_availability_lookup.borrow()
    }
    pub fn pointer_availability_lookup_mut(
        &self,
    ) -> RefMut<'_, PointerAvailabilityLookup> {
        self.pointer_availability_lookup.borrow_mut()
    }
    pub fn synced_value_data(&self) -> Ref<'_, SyncedValueData> {
        self.synced_value_data.borrow()
    }
    pub fn synced_value_data_mut(&self) -> RefMut<'_, SyncedValueData> {
        self.synced_value_data.borrow_mut()
    }

    pub fn shared_references_cache_refcell(
        &self,
    ) -> &RefCell<SharedReferencesCache> {
        &self.shared_references_cache
    }

    pub fn shared_references_cache(&self) -> Ref<'_, SharedReferencesCache> {
        self.shared_references_cache.borrow()
    }

    pub fn shared_references_cache_mut(
        &self,
    ) -> RefMut<'_, SharedReferencesCache> {
        self.shared_references_cache.borrow_mut()
    }

    pub fn core_library(&self) -> &CoreLibrary {
        &self.core_library
    }

    pub fn pointer_address_provider_mut(
        &self,
    ) -> RefMut<'_, SelfOwnedPointerAddressProvider> {
        self.pointer_address_provider.borrow_mut()
    }
    pub fn incoming_sections_receiver_mut(
        &self,
    ) -> RefMut<'_, IncomingSectionReceiver> {
        self.incoming_sections_receiver.borrow_mut()
    }
    pub fn com_interface_reconnect_request_receiver_mut(
        &self,
    ) -> RefMut<'_, UnboundedReceiver<ComInterfaceReconnectRequest>> {
        self.com_interface_reconnect_request_receiver.borrow_mut()
    }
    pub fn task_manager(&self) -> &TaskManager {
        &self.task_manager
    }

    pub fn stub() -> RuntimeInternal {
        let (incoming_sections_sender, incoming_sections_receiver) =
            create_incoming_sections_channel();
        let (reconnect_request_sender, reconnect_request_receiver) =
            create_unbounded_channel();

        RuntimeInternal::new(
            Endpoint::default(),
            RefCell::new(SharedReferencesCache::default()),
            Rc::new(RefCell::new(SelfOwnedPointerAddressProvider::new(
                Endpoint::default(),
            ))),
            RuntimeConfig::default(),
            ComHub::create(
                Endpoint::default(),
                incoming_sections_sender,
                reconnect_request_sender,
                0,
            )
            .0,
            TaskManager::create().0,
            incoming_sections_receiver,
            reconnect_request_receiver,
            CustomRuntimeInfo::default(),
        )
    }

    /// Creates all interfaces configured in the runtime config
    async fn create_configured_interfaces(&self) {
        if let Some(interfaces) = &self.config().interfaces {
            for RuntimeConfigInterface {
                interface_type,
                config,
                priority,
            } in interfaces.iter()
            {
                let create_future = self
                    .com_hub
                    .clone()
                    .create_interface(interface_type, config.clone(), *priority)
                    .await;
                match create_future {
                    Err(err) => {
                        error!(
                            "Failed to create interface \"{interface_type}\": {err}"
                        );
                        // request reconnect attempts in background
                        self.com_hub
                            .reconnect_interface_sender
                            .borrow_mut()
                            .start_send(ComInterfaceReconnectRequest::new(
                                interface_type.clone(),
                                config.clone(),
                                *priority,
                            ))
                            .unwrap();
                    }
                    Ok((_, ready_receiver)) => {
                        if let Some(ready_receiver) = ready_receiver {
                            let _ = ready_receiver.await;
                        }
                    }
                }
            }
        }
    }

    async fn init_local_loopback_interface(&self) {
        // add default local loopback interface
        let local_interface_setup_data =
            LocalLoopbackInterfaceSetupData.create_interface().unwrap();

        let ready_signal = self
            .com_hub
            .clone()
            .add_interface_from_configuration(
                local_interface_setup_data,
                InterfacePriority::None,
            )
            .expect("Failed to add local loopback interface");
        // local loopback interface is single socket interface and should always return a ready signal
        // which should always resolve to Ok
        ready_signal.unwrap().await.unwrap()
    }

    /// Performs asynchronous initialization of the runtime
    pub(crate) async fn init_async(&self) {
        // create local loopback interface and other configured interfaces
        self.init_local_loopback_interface().await;
        self.create_configured_interfaces().await;
    }

    #[cfg(feature = "compiler")]
    pub async fn execute<'a>(
        self: Rc<RuntimeInternal>,
        script: &'a str,
        inserted_values: &'a [ValueContainer],
        execution_context: Option<
            impl Into<FinalOrPersistedExecutionContext<'a>>,
        >,
        mark_as_debug: bool,
    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
        let mut execution_context = Runtime::from(self.clone())
            .get_or_create_execution_context(execution_context);
        let compile_start = Instant::now();
        let execution_context_mut = execution_context.as_mut();
        let dxb = execution_context_mut.compile(
            script,
            inserted_values,
            execution_context_mut.receivers(),
        )?;
        debug!(
            "[Compilation took {} ms]",
            compile_start.elapsed().as_millis()
        );
        let execute_start = Instant::now();
        let result = RuntimeInternal::execute_dxb(
            self,
            dxb,
            None,
            Some(execution_context),
            mark_as_debug,
        )
        .await
        .map_err(ScriptExecutionError::from);
        debug!(
            "[Execution took {} ms]",
            execute_start.elapsed().as_millis()
        );
        result
    }

    #[cfg(feature = "compiler")]
    pub fn execute_sync<'a>(
        self: Rc<RuntimeInternal>,
        script: &'a str,
        inserted_values: &'a [ValueContainer],
        execution_context: Option<
            impl Into<FinalOrPersistedExecutionContext<'a>>,
        >,
    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
        let mut execution_context = Runtime::from(self.clone())
            .get_or_create_execution_context(execution_context);
        let execution_context_mut = execution_context.as_mut();

        let compile_start = Instant::now();
        let dxb = execution_context_mut.compile(
            script,
            inserted_values,
            execution_context_mut.receivers(),
        )?;
        debug!(
            "[Compilation took {} ms]",
            compile_start.elapsed().as_millis()
        );
        let execute_start = Instant::now();
        let result = RuntimeInternal::execute_dxb_sync(
            self,
            dxb,
            None,
            Some(execution_context),
        )
        .map_err(ScriptExecutionError::from);
        debug!(
            "[Execution took {} ms]",
            execute_start.elapsed().as_millis()
        );
        result
    }

    pub fn execute_dxb<'a>(
        self: Rc<RuntimeInternal>,
        input: DXBWithSharedValues,
        initial_stack_values: Option<Vec<ValueContainer>>,
        execution_context: Option<
            impl Into<FinalOrPersistedExecutionContext<'a>> + 'a,
        >,
        mark_as_debug: bool,
    ) -> Pin<
        Box<
            dyn Future<Output = Result<Option<ValueContainer>, ExecutionError>>
                + 'a,
        >,
    > {
        Box::pin(async move {
            let mut execution_context = Runtime::from(self.clone())
                .get_or_create_execution_context(execution_context);
            let is_end_of_context = execution_context.is_end_of_context();
            let execution_context_mut = execution_context.as_mut();

            match execution_context_mut {
                ExecutionContext::Remote(context) => {
                    // initial stack values are not (yet) supported for remote execution
                    if initial_stack_values.is_some() {
                        return Err(ExecutionError::InvalidExecutionState);
                    }
                    RuntimeInternal::execute_remote_single_receiver(
                        self,
                        &context.target,
                        input,
                        RemoteExecutionOptions {
                            is_end_of_context,
                            mark_as_debug,
                        },
                    )
                    .await
                }
                ExecutionContext::Local(_) => {
                    execution_context_mut
                        .execute_dxb(input, initial_stack_values)
                        .await
                }
            }
        })
    }

    pub fn execute_dxb_sync<'a>(
        self: Rc<RuntimeInternal>,
        dxb: DXBWithSharedValues,
        initial_stack_values: Option<Vec<ValueContainer>>,
        execution_context: Option<
            impl Into<FinalOrPersistedExecutionContext<'a>>,
        >,
    ) -> Result<Option<ValueContainer>, ExecutionError> {
        let mut execution_context = Runtime::from(self.clone())
            .get_or_create_execution_context(execution_context);
        // TODO: pass is_end_of_context to local execution?
        // let is_end_of_context = execution_context.is_end_of_context();
        let execution_context_mut = execution_context.as_mut();

        match execution_context_mut {
            ExecutionContext::Remote(_) => {
                Err(ExecutionError::RequiresAsyncExecution)
            }
            ExecutionContext::Local(_) => execution_context_mut
                .execute_dxb_sync(dxb, initial_stack_values),
        }
    }

    /// Returns the existing execution context for the given context_id,
    /// or creates a new one if it doesn't exist.
    /// To reuse the context later, the caller must store it back in the map after use.
    fn take_or_create_execution_context(
        self: Rc<RuntimeInternal>,
        context_id: &IncomingEndpointContextSectionId,
        incoming_section: &IncomingSection,
    ) -> ExecutionContext {
        let runtime = Runtime::from(self.clone());
        let mut execution_contexts = self.execution_contexts.borrow_mut();
        // get execution context by context_id or create a new one if it doesn't exist
        let execution_context = execution_contexts.remove(context_id);
        if let Some(context) = execution_context {
            context
        } else {
            let caller_metadata = ExecutionCallerMetadata {
                endpoint: incoming_section.get_sender(),
            };
            ExecutionContext::local(
                ExecutionMode::unbounded(),
                runtime,
                caller_metadata,
            )
        }
    }

    /// Executes a remote block expecting a single receiver.
    /// # Safety
    /// The caller must ensure, to pass an remote execution context with a single receiver.
    pub async fn execute_remote_single_receiver(
        self: Rc<RuntimeInternal>,
        remote_execution_target: &RemoteExecutionTarget,
        input: DXBWithSharedValues,
        options: RemoteExecutionOptions,
    ) -> RemoteExecutionResult {
        if remote_execution_target.endpoints().len() != 1 {
            panic!(
                "execute_remote_single_receiver called with remote_execution_context that has more than one endpoint"
            );
        }
        self.execute_remote(remote_execution_target, input, options)
            .await?
            .remove(0)
            .0
    }

    /// Execute a remote block, waiting for all the peers to send their response.
    /// It might be, that a subset of the responses are errors
    pub async fn execute_remote(
        self: Rc<RuntimeInternal>,
        remote_execution_target: &RemoteExecutionTarget,
        input: DXBWithSharedValues,
        options: RemoteExecutionOptions,
    ) -> Result<Vec<(RemoteExecutionResult, Endpoint)>, SubscriberError> {
        let routing_header: RoutingHeader = RoutingHeader::default()
            .with_sender(self.endpoint().clone())
            .to_owned();

        // get existing context_id for context, or create a new one
        let context_id = {
            let mut context_ref =
                remote_execution_target.context_id.borrow_mut();
            context_ref.unwrap_or_else(|| {
                let id = self.com_hub.block_handler.get_new_context_id();
                // if the context_id is not set, we create a new one
                *context_ref = Some(id);
                id
            })
        };
        let block_header = BlockHeader {
            context_id,
            flags_and_timestamp: FlagsAndTimestamp::default()
                .with_is_end_of_context(options.is_end_of_context)
                .with_is_debug_block(options.mark_as_debug),
            ..BlockHeader::default()
        };
        let encrypted_header = EncryptedHeader::default();

        let mut block = DXBBlock::new(
            routing_header,
            block_header,
            encrypted_header,
            input.dxb,
        );

        block.set_receivers(remote_execution_target.endpoints());
        // TODO: ensure in remote_execution_context that endpoints are never empty
        unsafe {
            self.clone().register_shared_containers_for_endpoints(
                &(remote_execution_target
                    .endpoints()
                    .iter()
                    .collect::<Vec<_>>()),
                input.shared_values,
            )?;
        }

        let responses = self
            .com_hub
            .send_own_block_await_response(block, ResponseOptions::default())
            .await;

        let self_clone = self.clone();

        let futures_with_endpoint = responses
            .into_iter()
            .filter(|response| {
                // pipe trought all response errors, and the ones with an specified endpoint
                // to skip the [Response::Unspecified] cases to be executed
                response.is_err()
                    || matches!(response, Ok(re) if re.endpoint().is_some())
            })
            .map(|response| {
                let self_clone = self_clone.clone();
                let endpoint = response
                    .as_ref()
                    .map(|r| {
                        r.endpoint()
                            .cloned()
                            .expect("Expected endpoint to be present")
                    })
                    .unwrap_or_else(|e| e.endpoint().clone());
                (
                    async move {
                        let response = response?;
                        let incoming_section = response.take_incoming_section();
                        RuntimeInternal::execute_incoming_section(
                            self_clone,
                            incoming_section,
                            None,
                        )
                        .await
                        .0
                    },
                    endpoint,
                )
            });

        let (future, endpoint) = futures_with_endpoint
            .into_iter()
            .unzip::<_, _, Vec<_>, Vec<_>>();

        Ok(join_all(future)
            .await
            .into_iter()
            .zip(endpoint)
            .collect::<Vec<_>>())
    }

    pub async fn execute_instructions_remote(
        self: Rc<RuntimeInternal>,
        endpoints: Vec<Endpoint>,
        instructions_input: Vec<InstructionInput>,
        mark_as_debug: bool,
    ) -> Result<Vec<(RemoteExecutionResult, Endpoint)>, SubscriberError> {
        let dxb = core_compile(
            &self.pointer_availability_lookup(),
            &endpoints,
            instructions_input,
            self.shared_references_cache_mut().deref_mut(),
        );

        let remote_execution_context = RemoteExecutionContext::new(
            endpoints,
            ExecutionMode::Static,
            Runtime::from(self.clone()),
        );
        self.execute_remote(
            &remote_execution_context.target,
            dxb,
            RemoteExecutionOptions {
                mark_as_debug,
                is_end_of_context: true,
            },
        )
        .await
    }

    pub async fn execute_instructions_remote_single_receiver(
        self: Rc<RuntimeInternal>,
        endpoint: Endpoint,
        instructions_input: Vec<InstructionInput>,
        mark_as_debug: bool,
    ) -> RemoteExecutionResult {
        RuntimeInternal::execute_instructions_remote(
            self,
            vec![endpoint],
            instructions_input,
            mark_as_debug,
        )
        .await?
        .remove(0)
        .0
    }

    pub(crate) async fn execute_incoming_section(
        self: Rc<RuntimeInternal>,
        mut incoming_section: IncomingSection,
        shared_values: Option<Vec<SharedContainer>>,
    ) -> (
        Result<Option<ValueContainer>, ExecutionError>,
        Endpoint,
        OutgoingContextId,
        bool,
    ) {
        let section_context_id =
            incoming_section.get_section_context_id().clone();
        let mut context = Self::take_or_create_execution_context(
            self.clone(),
            &section_context_id,
            &incoming_section,
        );
        info!(
            "Executing incoming section with index: {}",
            incoming_section.get_section_index()
        );

        let mut result = None;
        let mut last_block = None;

        // iterate over the blocks in the incoming section
        loop {
            let block = incoming_section.next().await;
            if let Some(block) = block {
                let res = RuntimeInternal::execute_dxb_block_local(
                    self.clone(),
                    block.clone(),
                    Some(&mut context),
                    // NOTE: this assumes that all shared values are only needed as references, not as owned values
                    shared_values.clone(),
                )
                .await;
                if let Err(err) = res {
                    return (
                        Err(err),
                        block.sender().clone(),
                        block.block_header.context_id,
                        block.block_header.flags_and_timestamp.is_debug_block(),
                    );
                }
                result = res.unwrap();
                last_block = Some(block);
            } else {
                break;
            }
        }

        if last_block.is_none() {
            unreachable!("Incoming section must contain at least one block");
        }
        let last_block = last_block.unwrap();
        let sender_endpoint = last_block.sender().clone();
        let context_id = last_block.block_header.context_id;
        let is_end_of_context = last_block
            .block_header
            .flags_and_timestamp
            .is_end_of_context();
        let is_debug =
            last_block.block_header.flags_and_timestamp.is_debug_block();

        // insert the context back into the map for future use if not end of context
        if !is_end_of_context {
            self.execution_contexts
                .borrow_mut()
                .insert(section_context_id, context);
        }

        (Ok(result), sender_endpoint, context_id, is_debug)
    }

    async fn execute_dxb_block_local(
        self: Rc<RuntimeInternal>,
        block: DXBBlock,
        execution_context: Option<&mut ExecutionContext>,
        shared_values: Option<Vec<SharedContainer>>,
    ) -> Result<Option<ValueContainer>, ExecutionError> {
        let mut execution_context = Runtime::from(self.clone())
            .get_or_create_execution_context(execution_context);
        let execution_context_mut = execution_context.as_mut();

        // assert that the execution context is local
        if !core::matches!(execution_context_mut, ExecutionContext::Local(_)) {
            unreachable!(
                "Execution context must be local for executing a DXB block"
            );
        }
        let dxb = block.body;
        info!("executing on {}:\n", self.endpoint());

        print_disassembled_with_options(&dxb, DisassemblerOptions::default());

        let _end_execution =
            block.block_header.flags_and_timestamp.is_end_of_section();

        RuntimeInternal::execute_dxb(
            self,
            DXBWithSharedValues::new(dxb, shared_values.unwrap_or_default()),
            None,
            Some(execution_context),
            false,
        )
        .await
    }

    /// Registers a list of shared containers for a single endpoint.
    pub fn register_shared_containers_for_single_endpoint(
        self: Rc<Self>,
        endpoint: &Endpoint,
        shared_containers: Vec<SharedContainer>,
    ) {
        unsafe {
            self.register_shared_containers_for_endpoints(
                &[endpoint],
                shared_containers,
            )
            .unwrap()
        }
    }

    /// Registers a list of shared containers for a list of endpoints to subscribe.
    /// Note: only self owned pointers are registered, others are skipped
    ///
    /// # Safety
    /// The caller must ensure that endpoints is not empty.
    pub unsafe fn register_shared_containers_for_endpoints(
        self: Rc<Self>,
        endpoints: &[&Endpoint],
        shared_containers: Vec<SharedContainer>,
    ) -> Result<(), SubscriberError> {
        if endpoints.is_empty() {
            panic!("endpoints must not be empty");
        }

        for shared_container in shared_containers {
            // subscribe (remote) endpoints to own container
            if shared_container.is_self_owned() {
                for endpoint in endpoints {
                    // SAFETY: We checked that the shared container is self-owned
                    unsafe {
                        self.clone()
                            .subscribe_endpoint_to_owned_value(
                                &shared_container,
                                endpoint,
                                shared_container
                                    .derive_reference_with_max_mutability()
                                    .reference_mutability(),
                            )
                            .map_err(SubscriberError::Observer)?
                    }
                    // also store the subscribed pointer in cache so that we can handle incoming
                    // pointer updates from the subscribers
                    self.shared_references_cache
                        .borrow_mut()
                        .register_owned_shared_container(
                            &shared_container
                                .derive_reference_with_max_mutability(),
                        );
                }
            }
        }

        Ok(())
    }

    pub fn get_env(&self) -> IndexMap<String, String, RandomState> {
        self.config().env.clone().unwrap_or_default()
    }

    /// Get the human-readable name of the endpoint (can be provided in config)
    pub fn get_name(&self) -> Option<String> {
        self.config().name.clone()
    }

    /// Creates a new [DIFInterface] with a unique transceiver id and the runtime's pointer address provider
    pub fn create_dif_interface(&self) -> DIFInterface {
        let count = *self.transceiver_counter.borrow();
        let id = TransceiverId::Dif(count);
        self.transceiver_counter.replace(count + 1);
        DIFInterface::new(id, self.pointer_address_provider.clone())
    }
}