1use crate::{
2 channel::mpsc::{UnboundedReceiver, create_unbounded_channel},
3 collections::HashMap,
4 core_compiler::core_compilation_context::DXBWithSharedValues,
5 dif::dif_interface::DIFInterface,
6 disassembler::{
7 options::DisassemblerOptions, print_disassembled_with_options,
8 },
9 global::{
10 dxb_block::{
11 DXBBlock, IncomingEndpointContextSectionId, IncomingSection,
12 OutgoingContextId,
13 },
14 protocol_structures::{
15 block_header::BlockHeader, encrypted_header::EncryptedHeader,
16 routing_header::RoutingHeader,
17 },
18 },
19 libs::core::CoreLibrary,
20 network::{
21 com_hub::{
22 ComHub, InterfacePriority, network_response::ResponseOptions,
23 },
24 com_interfaces::local_loopback_interface::LocalLoopbackInterfaceSetupData,
25 },
26 prelude::*,
27 runtime::{
28 Runtime, RuntimeConfig, RuntimeConfigInterface,
29 cache::shared_references_cache::SharedReferencesCache,
30 execution::{
31 ExecutionError, InvalidProgramError,
32 context::{
33 ExecutionContext, ExecutionMode, RemoteExecutionContext,
34 ScriptExecutionError,
35 },
36 execution_input::ExecutionCallerMetadata,
37 },
38 pointer_address_provider::SelfOwnedPointerAddressProvider,
39 pointer_availability_lookup::PointerAvailabilityLookup,
40 request_move::compile_request_move,
41 },
42 shared_values::{
43 OwnedSharedContainer, PointerAddress, RemotePointerAddress,
44 SelfOwnedPointerAddress, SharedContainer, SharedContainerMutability,
45 base_shared_value_container::observers::TransceiverId,
46 },
47 time::Instant,
48 utils::task_manager::TaskManager,
49 values::{
50 core_value::CoreValue, core_values::endpoint::Endpoint, value::Value,
51 value_container::ValueContainer,
52 },
53};
54use alloc::rc::Rc;
55use core::{
56 cell::{Ref, RefCell, RefMut},
57 pin::Pin,
58 slice,
59};
60use log::{debug, error, info};
61
62#[derive(Debug)]
63pub struct RuntimeInternal {
64 version: String,
65 endpoint: Endpoint,
66
67 core_library: CoreLibrary,
68
69 memory: RefCell<SharedReferencesCache>,
70 pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
71 com_hub: Rc<ComHub>,
72 config: RuntimeConfig,
73
74 transceiver_counter: RefCell<u32>,
76
77 task_manager: TaskManager,
78
79 incoming_sections_receiver: RefCell<UnboundedReceiver<IncomingSection>>,
81
82 execution_contexts:
84 RefCell<HashMap<IncomingEndpointContextSectionId, ExecutionContext>>,
85
86 moving_pointers: RefCell<
88 HashMap<
89 Endpoint,
90 HashMap<SelfOwnedPointerAddress, OwnedSharedContainer>,
91 >,
92 >,
93
94 pointer_availability_lookup: RefCell<PointerAvailabilityLookup>,
95}
96
97macro_rules! get_execution_context {
98 ($self_rc:expr, $execution_context:expr) => {
100 match $execution_context {
101 Some(context) => {
102 if let &mut ExecutionContext::Local(ref mut local_context) = context {
104 local_context.set_runtime_internal($self_rc.clone());
105 }
106 context
107 },
108 None => {
109 &mut ExecutionContext::local(ExecutionMode::Static, $self_rc.clone(), ExecutionCallerMetadata::local_default())
110 }
111 }
112 };
113}
114
115impl From<Rc<RuntimeInternal>> for Runtime {
116 fn from(value: Rc<RuntimeInternal>) -> Self {
117 Runtime { internal: value }
118 }
119}
120
121impl RuntimeInternal {
122 pub(crate) fn new(
123 endpoint: Endpoint,
124 memory: RefCell<SharedReferencesCache>,
125 pointer_address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
126 config: RuntimeConfig,
127 com_hub: Rc<ComHub>,
128 task_manager: TaskManager,
129 incoming_sections_receiver: UnboundedReceiver<IncomingSection>,
130 ) -> RuntimeInternal {
131 let pointer_availability_lookup =
132 PointerAvailabilityLookup::new(endpoint.clone());
133 RuntimeInternal {
134 version: env!("CARGO_PKG_VERSION").to_string(),
135 endpoint,
136 memory,
137 pointer_address_provider,
138 config,
139 com_hub,
140 task_manager,
141 core_library: CoreLibrary::default(),
142 incoming_sections_receiver: RefCell::new(
143 incoming_sections_receiver,
144 ),
145 execution_contexts: RefCell::new(HashMap::new()),
146 moving_pointers: RefCell::new(HashMap::new()),
147 transceiver_counter: RefCell::new(0),
148 pointer_availability_lookup: RefCell::new(
149 pointer_availability_lookup,
150 ),
151 }
152 }
153 pub fn version(&self) -> &str {
154 &self.version
155 }
156 pub fn config(&self) -> &RuntimeConfig {
157 &self.config
158 }
159 pub fn com_hub(&self) -> Rc<ComHub> {
160 self.com_hub.clone()
161 }
162 pub fn endpoint(&self) -> &Endpoint {
163 &self.endpoint
164 }
165 pub fn pointer_availability_lookup(
166 &self,
167 ) -> Ref<'_, PointerAvailabilityLookup> {
168 self.pointer_availability_lookup.borrow()
169 }
170 pub fn pointer_availability_lookup_mut(
171 &self,
172 ) -> RefMut<'_, PointerAvailabilityLookup> {
173 self.pointer_availability_lookup.borrow_mut()
174 }
175 pub fn memory(&self) -> &RefCell<SharedReferencesCache> {
176 &self.memory
177 }
178 pub fn core_library(&self) -> &CoreLibrary {
179 &self.core_library
180 }
181
182 pub fn pointer_address_provider(
183 &self,
184 ) -> &RefCell<SelfOwnedPointerAddressProvider> {
185 &self.pointer_address_provider
186 }
187 pub fn incoming_sections_receiver_mut(
188 &self,
189 ) -> RefMut<'_, UnboundedReceiver<IncomingSection>> {
190 self.incoming_sections_receiver.borrow_mut()
191 }
192 pub fn incoming_sections_receiver(
193 &self,
194 ) -> Ref<'_, UnboundedReceiver<IncomingSection>> {
195 self.incoming_sections_receiver.borrow()
196 }
197 pub fn task_manager(&self) -> &TaskManager {
198 &self.task_manager
199 }
200
201 pub fn stub() -> RuntimeInternal {
202 let (sender, receiver) = create_unbounded_channel();
203 RuntimeInternal::new(
204 Endpoint::default(),
205 RefCell::new(SharedReferencesCache::default()),
206 Rc::new(RefCell::new(SelfOwnedPointerAddressProvider::new(
207 Endpoint::default(),
208 ))),
209 RuntimeConfig::default(),
210 ComHub::create(Endpoint::default(), sender).0,
211 TaskManager::create().0,
212 receiver,
213 )
214 }
215
216 async fn create_configured_interfaces(&self) {
218 if let Some(interfaces) = &self.config.interfaces {
219 for RuntimeConfigInterface {
220 interface_type,
221 config,
222 priority,
223 } in interfaces.iter()
224 {
225 let create_future = self
226 .com_hub
227 .clone()
228 .create_interface(interface_type, config.clone(), *priority)
229 .await;
230 match create_future {
231 Err(err) => {
232 error!(
233 "Failed to create interface \"{interface_type}\": {err}"
234 )
235 }
236 Ok((_, ready_receiver)) => {
237 if let Some(ready_receiver) = ready_receiver {
238 let _ = ready_receiver.await;
239 }
240 }
241 }
242 }
243 }
244 }
245
246 async fn init_local_loopback_interface(&self) {
247 let local_interface_setup_data =
249 LocalLoopbackInterfaceSetupData.create_interface().unwrap();
250
251 let ready_signal = self
252 .com_hub
253 .clone()
254 .add_interface_from_configuration(
255 local_interface_setup_data,
256 InterfacePriority::None,
257 )
258 .expect("Failed to add local loopback interface");
259 ready_signal.unwrap().await.unwrap()
262 }
263
264 pub(crate) async fn init_async(&self) {
266 self.init_local_loopback_interface().await;
268 self.create_configured_interfaces().await;
269 }
270
271 #[cfg(feature = "compiler")]
272 pub async fn execute(
273 self: Rc<RuntimeInternal>,
274 script: &str,
275 inserted_values: &[ValueContainer],
276 execution_context: Option<&mut ExecutionContext>,
277 ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
278 let execution_context = get_execution_context!(
279 Runtime::from(self.clone()),
280 execution_context
281 );
282 let compile_start = Instant::now();
283 let dxb = execution_context.compile(
284 script,
285 inserted_values,
286 execution_context.receivers(),
287 )?;
288 debug!(
289 "[Compilation took {} ms]",
290 compile_start.elapsed().as_millis()
291 );
292 let execute_start = Instant::now();
293 let result = RuntimeInternal::execute_dxb(
294 self,
295 dxb,
296 Some(execution_context),
297 true,
298 )
299 .await
300 .map_err(ScriptExecutionError::from);
301 debug!(
302 "[Execution took {} ms]",
303 execute_start.elapsed().as_millis()
304 );
305 result
306 }
307
308 #[cfg(feature = "compiler")]
309 pub fn execute_sync(
310 self: Rc<RuntimeInternal>,
311 script: &str,
312 inserted_values: &[ValueContainer],
313 execution_context: Option<&mut ExecutionContext>,
314 ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
315 let execution_context = get_execution_context!(
316 Runtime::from(self.clone()),
317 execution_context
318 );
319 let compile_start = Instant::now();
320 let dxb = execution_context.compile(
321 script,
322 inserted_values,
323 execution_context.receivers(),
324 )?;
325 debug!(
326 "[Compilation took {} ms]",
327 compile_start.elapsed().as_millis()
328 );
329 let execute_start = Instant::now();
330 let result = RuntimeInternal::execute_dxb_sync(
331 self,
332 dxb,
333 Some(execution_context),
334 true,
335 )
336 .map_err(ScriptExecutionError::from);
337 debug!(
338 "[Execution took {} ms]",
339 execute_start.elapsed().as_millis()
340 );
341 result
342 }
343
344 pub fn execute_dxb<'a>(
345 self: Rc<RuntimeInternal>,
346 input: DXBWithSharedValues,
347 execution_context: Option<&'a mut ExecutionContext>,
348 _end_execution: bool,
349 ) -> Pin<
350 Box<
351 dyn Future<Output = Result<Option<ValueContainer>, ExecutionError>>
352 + 'a,
353 >,
354 > {
355 Box::pin(async move {
356 let execution_context = get_execution_context!(
357 Runtime::from(self.clone()),
358 execution_context
359 );
360 match execution_context {
361 ExecutionContext::Remote(context) => {
362 RuntimeInternal::execute_remote(self, context, input).await
363 }
364 ExecutionContext::Local(_) => {
365 execution_context.execute_dxb(input).await
366 }
367 }
368 })
369 }
370
371 pub fn execute_dxb_sync(
372 self: Rc<RuntimeInternal>,
373 dxb: DXBWithSharedValues,
374 execution_context: Option<&mut ExecutionContext>,
375 _end_execution: bool,
376 ) -> Result<Option<ValueContainer>, ExecutionError> {
377 let execution_context =
378 get_execution_context!(Runtime::from(self), execution_context);
379 match execution_context {
380 ExecutionContext::Remote(_) => {
381 Err(ExecutionError::RequiresAsyncExecution)
382 }
383 ExecutionContext::Local(_) => {
384 execution_context.execute_dxb_sync(dxb)
385 }
386 }
387 }
388
389 fn take_execution_context(
393 self: Rc<RuntimeInternal>,
394 context_id: &IncomingEndpointContextSectionId,
395 incoming_section: &IncomingSection,
396 ) -> ExecutionContext {
397 let runtime = Runtime::from(self.clone());
398 let mut execution_contexts = self.execution_contexts.borrow_mut();
399 let execution_context = execution_contexts.remove(context_id);
401 if let Some(context) = execution_context {
402 context
403 } else {
404 let caller_metadata = ExecutionCallerMetadata {
405 endpoint: incoming_section.get_sender(),
406 };
407 ExecutionContext::local(
408 ExecutionMode::unbounded(),
409 runtime,
410 caller_metadata,
411 )
412 }
413 }
414
415 pub async fn execute_remote(
416 self: Rc<RuntimeInternal>,
417 remote_execution_context: &mut RemoteExecutionContext,
418 input: DXBWithSharedValues,
419 ) -> Result<Option<ValueContainer>, ExecutionError> {
420 let routing_header: RoutingHeader = RoutingHeader::default()
421 .with_sender(self.endpoint.clone())
422 .to_owned();
423
424 let context_id =
426 remote_execution_context.context_id.unwrap_or_else(|| {
427 remote_execution_context.context_id =
429 Some(self.com_hub.block_handler.get_new_context_id());
430 remote_execution_context.context_id.unwrap()
431 });
432
433 let block_header = BlockHeader {
434 context_id,
435 ..BlockHeader::default()
436 };
437 let encrypted_header = EncryptedHeader::default();
438
439 let mut block = DXBBlock::new(
440 routing_header,
441 block_header,
442 encrypted_header,
443 input.dxb,
444 );
445
446 block
447 .set_receivers(slice::from_ref(&remote_execution_context.endpoint));
448
449 let response = self
450 .com_hub
451 .send_own_block_await_response(block, ResponseOptions::default())
452 .await
453 .remove(0)?;
454 let incoming_section = response.take_incoming_section();
455
456 RuntimeInternal::execute_incoming_section(
457 self,
458 incoming_section,
459 Some(input.shared_values),
460 )
461 .await
462 .0
463 }
464
465 pub(crate) async fn execute_incoming_section(
466 self: Rc<RuntimeInternal>,
467 mut incoming_section: IncomingSection,
468 shared_values: Option<Vec<SharedContainer>>,
469 ) -> (
470 Result<Option<ValueContainer>, ExecutionError>,
471 Endpoint,
472 OutgoingContextId,
473 ) {
474 let section_context_id =
475 incoming_section.get_section_context_id().clone();
476 let mut context = Self::take_execution_context(
477 self.clone(),
478 §ion_context_id,
479 &incoming_section,
480 );
481 info!(
482 "Executing incoming section with index: {}",
483 incoming_section.get_section_index()
484 );
485
486 let mut result = None;
487 let mut last_block = None;
488
489 loop {
491 let block = incoming_section.next().await;
492 if let Some(block) = block {
493 let res = RuntimeInternal::execute_dxb_block_local(
494 self.clone(),
495 block.clone(),
496 Some(&mut context),
497 shared_values.clone(),
499 )
500 .await;
501 if let Err(err) = res {
502 return (
503 Err(err),
504 block.sender().clone(),
505 block.block_header.context_id,
506 );
507 }
508 result = res.unwrap();
509 last_block = Some(block);
510 } else {
511 break;
512 }
513 }
514
515 if last_block.is_none() {
516 unreachable!("Incoming section must contain at least one block");
517 }
518 let last_block = last_block.unwrap();
519 let sender_endpoint = last_block.sender().clone();
520 let context_id = last_block.block_header.context_id;
521
522 self.execution_contexts
525 .borrow_mut()
526 .insert(section_context_id, context);
527
528 (Ok(result), sender_endpoint, context_id)
529 }
530
531 async fn execute_dxb_block_local(
532 self: Rc<RuntimeInternal>,
533 block: DXBBlock,
534 execution_context: Option<&mut ExecutionContext>,
535 shared_values: Option<Vec<SharedContainer>>,
536 ) -> Result<Option<ValueContainer>, ExecutionError> {
537 let execution_context = get_execution_context!(
538 Runtime::from(self.clone()),
539 execution_context
540 );
541 if !core::matches!(execution_context, ExecutionContext::Local(_)) {
543 unreachable!(
544 "Execution context must be local for executing a DXB block"
545 );
546 }
547 let dxb = block.body;
548 info!("executing on {}:\n", self.endpoint,);
549
550 print_disassembled_with_options(&dxb, DisassemblerOptions::default());
551
552 let end_execution =
553 block.block_header.flags_and_timestamp.is_end_of_section();
554
555 RuntimeInternal::execute_dxb(
556 self,
557 DXBWithSharedValues::new(dxb, shared_values.unwrap_or_default()),
558 Some(execution_context),
559 end_execution,
560 )
561 .await
562 }
563
564 pub fn register_shared_containers_for_single_endpoint(
566 &self,
567 endpoint: &Endpoint,
568 shared_containers: Vec<SharedContainer>,
569 ) {
570 unsafe {
571 self.register_shared_containers_for_endpoints(
572 &[endpoint],
573 shared_containers,
574 )
575 .unwrap()
576 }
577 }
578
579 pub unsafe fn register_shared_containers_for_endpoints(
582 &self,
583 endpoints: &[&Endpoint],
584 shared_containers: Vec<SharedContainer>,
585 ) -> Result<(), ()> {
586 if endpoints.is_empty() {
587 panic!("endpoints must not be empty");
588 }
589
590 for shared_container in shared_containers {
591 match shared_container {
592 SharedContainer::Owned(owned_shared_container) => {
593 if endpoints.len() == 1 {
594 self.add_moving_shared_container(
595 endpoints[0].clone(),
596 owned_shared_container,
597 );
598 } else {
599 return Err(());
600 }
601 }
602 SharedContainer::Referenced(_referenced_shared_container) => {
603 }
605 }
606 }
607
608 Ok(())
609 }
610
611 pub(crate) async fn request_pointer_move(
616 self: Rc<RuntimeInternal>,
617 from_endpoint: &Endpoint,
618 pointers: Vec<(SharedContainerMutability, SelfOwnedPointerAddress)>,
619 ) -> Result<Vec<OwnedSharedContainer>, ExecutionError> {
620 let pointer_mapping = pointers
621 .into_iter()
622 .map(|original| {
623 (
624 original,
625 self.pointer_address_provider
626 .borrow_mut()
627 .get_new_self_owned_address(),
628 )
629 })
630 .collect::<Vec<_>>();
631 let body = compile_request_move(
632 pointer_mapping
633 .iter()
634 .map(|((_, original), new)| (original.clone(), new.clone()))
635 .collect::<Vec<_>>(),
636 );
637 let moved_values = self
638 .clone()
639 .execute_dxb(
640 DXBWithSharedValues::new(body, vec![]),
641 Some(&mut ExecutionContext::Remote(
642 RemoteExecutionContext::new(
643 from_endpoint.clone(),
644 ExecutionMode::Static,
645 Runtime::from(self),
646 ),
647 )),
648 true,
649 )
650 .await?;
651
652 match moved_values {
654 Some(ValueContainer::Local(Value {
655 inner: CoreValue::List(list),
656 ..
657 })) => {
658 let pointer_values = list.into_vec();
659 let owned_values = pointer_values.into_iter()
660 .zip(pointer_mapping)
661 .map(|(value, ((mutability, _), new_address))| {
662 unsafe {
664 OwnedSharedContainer::new_with_inferred_allowed_type_unsafe(
666 value,
667 mutability,
668 new_address,
669 )
670 }
671 }).collect::<Vec<_>>();
672 Ok(owned_values)
673 }
674 _ => Err(ExecutionError::InvalidProgram(
675 InvalidProgramError::ExpectedValue,
676 )),
677 }
678 }
679
680 pub(crate) fn add_moving_shared_container(
683 &self,
684 new_owner: Endpoint,
685 moving_owned_container: OwnedSharedContainer,
686 ) {
687 let address = moving_owned_container.pointer_address().clone();
688
689 self.moving_pointers
690 .borrow_mut()
691 .entry(new_owner)
692 .or_default()
693 .insert(address, moving_owned_container);
694 }
695
696 pub(crate) fn handle_pointer_move_to_remote(
697 self: Rc<RuntimeInternal>,
698 from_endpoint: &Endpoint,
699 pointer_mapping: Vec<(
700 SelfOwnedPointerAddress,
701 SelfOwnedPointerAddress,
702 )>,
703 memory: &SharedReferencesCache,
704 ) -> Result<Vec<ValueContainer>, ExecutionError> {
705 let mut pointer_borrow = self.moving_pointers.borrow_mut();
706 let moving_pointers = pointer_borrow
707 .get_mut(from_endpoint)
708 .ok_or(ExecutionError::UnauthorizedMove)?;
709
710 let values = pointer_mapping
711 .into_iter()
712 .map(|(original_address, new)| {
713 let new_address =
714 RemotePointerAddress::for_endpoint(from_endpoint, &new);
715 let shared_container = moving_pointers
716 .remove(&original_address)
717 .ok_or(ExecutionError::UnauthorizedMove)?;
718
719 let value = shared_container.value_container().clone();
720
721 if memory
723 .has_reference(&PointerAddress::Remote(new_address.clone()))
724 {
725 return Err(ExecutionError::InvalidMove);
726 } else {
727 unsafe {
729 shared_container.move_to_remote(new_address, memory);
730 }
731 }
732
733 Ok(value)
734 })
735 .collect::<Result<Vec<_>, ExecutionError>>()?;
736 Ok(values)
737 }
738
739 pub fn get_env(&self) -> HashMap<String, String> {
740 self.config.env.clone().unwrap_or_default()
741 }
742
743 pub fn create_dif_interface(&self) -> DIFInterface {
745 let id = TransceiverId(*self.transceiver_counter.borrow());
746 self.transceiver_counter.replace(id.0 + 1);
747 DIFInterface::new(id, self.pointer_address_provider.clone())
748 }
749}