1use crate::{
2 channel::mpsc::{
3 UnboundedReceiver, UnboundedSender, create_unbounded_channel,
4 },
5 collections::HashMap,
6 global::dxb_block::{
7 BlockId, DXBBlock, IncomingBlockNumber, IncomingContextId,
8 IncomingEndpointContextId, IncomingEndpointContextSectionId,
9 IncomingSection, IncomingSectionIndex, OutgoingContextId,
10 OutgoingSectionIndex,
11 },
12 network::com_interfaces::com_interface::socket::ComInterfaceSocketUUID,
13 random::RandomState,
14};
15
16use crate::{disassembler::print_disassembled, prelude::*};
17use core::{cell::RefCell, fmt::Debug, prelude::rust_2024::*};
18use log::info;
19use ringmap::RingMap;
20
21#[derive(Debug)]
23pub struct ScopeContext {
24 pub next_section_index: IncomingSectionIndex,
25 pub next_block_number: IncomingBlockNumber,
26 pub keep_alive_timestamp: u64,
30 pub current_queue_sender: Option<UnboundedSender<DXBBlock>>,
32 pub cached_blocks: BTreeMap<IncomingBlockNumber, DXBBlock>,
34}
35
36impl Default for ScopeContext {
38 fn default() -> Self {
39 ScopeContext {
40 next_section_index: 0,
41 next_block_number: 0,
42 keep_alive_timestamp: crate::time::now_ms(),
43 current_queue_sender: None,
44 cached_blocks: BTreeMap::new(),
45 }
46 }
47}
48
49type SectionObserver = Box<dyn FnMut(IncomingSection)>;
51
52#[derive(Clone, Debug)]
53pub struct BlockHistoryData {
54 pub original_socket_uuid: Option<ComInterfaceSocketUUID>,
57}
58
59pub struct BlockHandler {
60 pub current_context_id: RefCell<OutgoingContextId>,
61
62 pub block_cache: RefCell<HashMap<IncomingEndpointContextId, ScopeContext>>,
64
65 pub incoming_sections_sender: RefCell<UnboundedSender<IncomingSection>>,
68
69 pub section_observers: RefCell<
72 HashMap<(IncomingContextId, IncomingSectionIndex), SectionObserver>,
73 >,
74
75 pub incoming_blocks_history:
77 RefCell<RingMap<BlockId, BlockHistoryData, RandomState>>,
78}
79
80impl Debug for BlockHandler {
81 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
82 f.debug_struct("BlockHandler")
83 .field("current_context_id", &self.current_context_id)
84 .field("incoming_blocks_history", &self.incoming_blocks_history)
86 .finish()
87 }
88}
89
90const RING_MAP_CAPACITY: usize = 500;
91
92impl BlockHandler {
93 pub fn init(
94 incoming_sections_sender: UnboundedSender<IncomingSection>,
95 ) -> BlockHandler {
96 BlockHandler {
97 current_context_id: RefCell::new(0),
98 block_cache: RefCell::new(HashMap::new()),
99 incoming_sections_sender: RefCell::new(incoming_sections_sender),
100 section_observers: RefCell::new(HashMap::new()),
101 incoming_blocks_history: RefCell::new(
102 RingMap::with_capacity_and_hasher(
103 RING_MAP_CAPACITY,
104 RandomState::default(),
105 ),
106 ),
107 }
108 }
109
110 pub fn add_block_id_to_history(
114 &self,
115 block_id: BlockId,
116 original_socket_uuid: Option<ComInterfaceSocketUUID>,
117 ) {
118 let mut history = self.incoming_blocks_history.borrow_mut();
119 if !history.contains_key(&block_id) {
121 let block_data = BlockHistoryData {
122 original_socket_uuid,
123 };
124 history.insert(block_id, block_data);
125 }
126 }
127
128 pub fn is_block_in_history(&self, block: &DXBBlock) -> bool {
130 let history = self.incoming_blocks_history.borrow();
131 let block_id = block.get_block_id();
132 history.contains_key(&block_id)
133 }
134
135 pub fn get_block_data_from_history(
136 &self,
137 block: &DXBBlock,
138 ) -> Option<BlockHistoryData> {
139 let history = self.incoming_blocks_history.borrow();
140 let block_id = block.get_block_id();
141 history.get(&block_id).cloned()
142 }
143
144 pub fn handle_incoming_block(&self, block: DXBBlock) {
147 info!("Handling incoming block...");
148 let context_id = block.block_header.context_id;
149 let section_index = block.block_header.section_index;
150 let block_number = block.block_header.block_number;
151 let is_response = block
152 .block_header
153 .flags_and_timestamp
154 .block_type()
155 .is_response();
156
157 info!(
158 "Received block (context={context_id}, section={section_index}, block_nr={block_number})"
159 );
160 print_disassembled(&block.body);
161
162 if is_response {
164 self.handle_incoming_response_block(block);
165 } else {
166 self.handle_incoming_request_block(block);
167 }
168 }
169
170 fn handle_incoming_request_block(&self, block: DXBBlock) {
172 let new_sections =
173 self.extract_complete_sections_with_new_incoming_block(block);
174 let sender = &self.incoming_sections_sender;
176 for section in new_sections {
177 sender.borrow_mut().start_send(section).unwrap();
178 }
179 }
180
181 fn handle_incoming_response_block(&self, block: DXBBlock) {
184 let context_id = block.block_header.context_id;
185 let endpoint_context_id = IncomingEndpointContextId {
186 sender: block.routing_header.sender.clone(),
187 context_id,
188 };
189 let new_sections =
190 self.extract_complete_sections_with_new_incoming_block(block);
191 for section in new_sections {
193 let section_index = section.get_section_index();
194
195 if let Some(observer) = self
196 .section_observers
197 .borrow_mut()
198 .get_mut(&(context_id, section_index))
199 {
200 observer(section);
202 } else {
203 log::warn!(
205 "No observer for incoming response block (scope={endpoint_context_id:?}, block={section_index}), dropping block"
206 );
207 };
208 }
209 }
210
211 fn extract_complete_sections_with_new_incoming_block(
214 &self,
215 block: DXBBlock,
216 ) -> Vec<IncomingSection> {
217 let section_index = block.block_header.section_index;
218 let block_number = block.block_header.block_number;
219 let is_end_of_section =
220 block.block_header.flags_and_timestamp.is_end_of_section();
221 let is_end_of_context =
222 block.block_header.flags_and_timestamp.is_end_of_context();
223 let endpoint_context_id = IncomingEndpointContextId {
224 sender: block.routing_header.sender.clone(),
225 context_id: block.block_header.context_id,
226 };
227 let section_context_id = IncomingEndpointContextSectionId::new(
228 endpoint_context_id.clone(),
229 section_index,
230 );
231
232 let has_scope_context =
234 { self.block_cache.borrow().contains_key(&endpoint_context_id) };
235
236 if !has_scope_context
238 && block_number == 0
239 && (is_end_of_section || is_end_of_context)
240 {
241 return vec![IncomingSection::SingleBlock((
242 Some(block),
243 section_context_id.clone(),
244 ))];
245 }
246
247 let mut request_scopes = self.block_cache.borrow_mut();
249 let scope_context = request_scopes
250 .entry(endpoint_context_id.clone())
251 .or_default();
252
253 if block_number == scope_context.next_block_number {
259 let mut new_blocks = vec![];
261
262 let mut is_end_of_context = is_end_of_context;
264 let mut is_end_of_section = is_end_of_section;
265 let mut next_block = block;
266 let mut section_index = section_index;
267
268 loop {
271 if let Some(sender) = &mut scope_context.current_queue_sender {
272 sender.start_send(next_block).expect(
274 "Failed to send block to current section queue",
275 );
276 } else {
277 let (mut sender, receiver) = create_unbounded_channel();
279
280 new_blocks.push(IncomingSection::BlockStream((
282 Some(receiver),
283 IncomingEndpointContextSectionId::new(
284 endpoint_context_id.clone(),
285 section_index,
286 ),
287 )));
288
289 sender.start_send(next_block).expect(
291 "Failed to send first block to current section queue",
292 );
293
294 scope_context.current_queue_sender = Some(sender);
295 }
296
297 scope_context.next_block_number += 1;
300
301 if is_end_of_context {
303 request_scopes.remove(&endpoint_context_id);
304 break;
305 }
306 else if is_end_of_section {
308 scope_context.next_section_index += 1;
310 if let Some(sender) =
312 scope_context.current_queue_sender.take()
313 {
314 sender.close_channel();
315 }
316 }
317 if let Some(next_cached_block) = scope_context
321 .cached_blocks
322 .remove(&scope_context.next_block_number)
323 {
324 is_end_of_section = next_cached_block
326 .block_header
327 .flags_and_timestamp
328 .is_end_of_section();
329 is_end_of_context = next_cached_block
331 .block_header
332 .flags_and_timestamp
333 .is_end_of_context();
334 next_block = next_cached_block;
336
337 section_index = next_block.block_header.section_index;
339 }
340 else {
342 break;
343 }
344 }
345
346 new_blocks
347 }
348 else {
351 if scope_context.cached_blocks.contains_key(&block_number) {
354 log::warn!(
355 "Block {block_number} already in cache, dropping block"
356 );
357 }
358
359 scope_context.cached_blocks.insert(block_number, block);
361
362 vec![]
363 }
364 }
365
366 pub fn get_new_context_id(&self) -> OutgoingContextId {
367 *self.current_context_id.borrow_mut() += 1;
368 *self.current_context_id.borrow()
369 }
370
371 pub fn register_incoming_block_observer(
374 &self,
375 context_id: OutgoingContextId,
376 section_index: OutgoingSectionIndex,
377 ) -> UnboundedReceiver<IncomingSection> {
378 let (tx, rx) = create_unbounded_channel::<IncomingSection>();
379 let tx = Rc::new(RefCell::new(tx));
380
381 let observer = move |blocks: IncomingSection| {
383 tx.clone().borrow_mut().start_send(blocks).unwrap();
384 };
385
386 self.section_observers
388 .borrow_mut()
389 .insert((context_id, section_index), Box::new(observer));
390
391 rx
392 }
393
394 pub async fn wait_for_incoming_response_block(
396 &self,
397 context_id: OutgoingContextId,
398 section_index: OutgoingSectionIndex,
399 ) -> Option<IncomingSection> {
400 let _rx =
401 self.register_incoming_block_observer(context_id, section_index);
402 None
405 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412 use crate::{
413 global::{
414 dxb_block::{DXBBlock, IncomingSection},
415 protocol_structures::{
416 block_header::{BlockHeader, BlockType, FlagsAndTimestamp},
417 routing_header::{Receivers, RoutingHeader},
418 },
419 },
420 values::core_values::endpoint::Endpoint,
421 };
422 use core::str::FromStr;
423 use ntest_timeout::timeout;
424
425 lazy_static::lazy_static! {
426 pub static ref TEST_ENDPOINT_ORIGIN: Endpoint = Endpoint::from_str("@origin").unwrap();
427 pub static ref TEST_ENDPOINT_A: Endpoint = Endpoint::from_str("@test-a").unwrap();
428 pub static ref TEST_ENDPOINT_B: Endpoint = Endpoint::from_str("@test-b").unwrap();
429 }
430
431 #[tokio::test]
432 async fn receive_single_block() {
433 let (incoming_sections_sender, mut incoming_sections_receiver) =
434 create_unbounded_channel::<IncomingSection>();
435
436 let block_handler = BlockHandler::init(incoming_sections_sender);
437 let context_id = block_handler.get_new_context_id();
438
439 let mut block = DXBBlock {
441 block_header: BlockHeader {
442 context_id,
443 flags_and_timestamp: FlagsAndTimestamp::new()
444 .with_is_end_of_section(true)
445 .with_is_end_of_context(true),
446 ..BlockHeader::default()
447 },
448 routing_header: RoutingHeader::default()
449 .with_sender(TEST_ENDPOINT_A.clone())
450 .with_receivers(Receivers::Endpoints(vec![
451 TEST_ENDPOINT_ORIGIN.clone(),
452 ]))
453 .to_owned(),
454 ..DXBBlock::default()
455 };
456 let block_endpoint_context_id = block.get_endpoint_context_id();
457
458 block_handler.handle_incoming_block(block);
460
461 let incoming_block = incoming_sections_receiver.next().await.unwrap();
463 match &incoming_block {
464 IncomingSection::SingleBlock((Some(received_block), ..)) => {
465 assert_eq!(
466 received_block.get_endpoint_context_id(),
467 block_endpoint_context_id
468 );
469 }
470 _ => panic!("Expected a SingleBlock section"),
471 }
472 }
473
474 #[tokio::test]
475 async fn receive_multiple_blocks() {
476 let (incoming_sections_sender, mut incoming_sections_receiver) =
477 create_unbounded_channel::<IncomingSection>();
478
479 let block_handler = BlockHandler::init(incoming_sections_sender);
480
481 let context_id = block_handler.get_new_context_id();
482 let section_index = 42;
483
484 let mut blocks = gen move {
486 yield DXBBlock {
487 block_header: BlockHeader {
488 context_id,
489 section_index,
490 block_number: 0,
491 flags_and_timestamp: FlagsAndTimestamp::new()
492 .with_is_end_of_section(false)
493 .with_is_end_of_context(false),
494 ..BlockHeader::default()
495 },
496 routing_header: RoutingHeader::default()
497 .with_sender(TEST_ENDPOINT_A.clone())
498 .with_receivers(Receivers::Endpoints(vec![
499 TEST_ENDPOINT_ORIGIN.clone(),
500 ]))
501 .to_owned(),
502 ..DXBBlock::default()
503 };
504
505 yield DXBBlock {
506 block_header: BlockHeader {
507 context_id,
508 section_index,
509 block_number: 1,
510 flags_and_timestamp: FlagsAndTimestamp::new()
511 .with_is_end_of_section(true)
512 .with_is_end_of_context(true),
513 ..BlockHeader::default()
514 },
515 routing_header: RoutingHeader::default()
516 .with_sender(TEST_ENDPOINT_A.clone())
517 .with_receivers(Receivers::Endpoints(vec![
518 TEST_ENDPOINT_ORIGIN.clone(),
519 ]))
520 .to_owned(),
521 ..DXBBlock::default()
522 };
523 };
524
525 block_handler.handle_incoming_block(blocks.next().unwrap());
527
528 info!("Checking incoming sections...");
529
530 let mut section = incoming_sections_receiver.next().await.unwrap();
532 match §ion {
533 IncomingSection::BlockStream((
534 Some(blocks),
535 incoming_context_section_id,
536 )) => {
537 assert_eq!(
539 incoming_context_section_id.section_index,
540 section_index
541 );
542
543 assert!(section.next().await.is_some());
545 }
546 _ => core::panic!("Expected a BlockStream section"),
547 }
548
549 block_handler.handle_incoming_block(blocks.next().unwrap());
551
552 match §ion {
555 IncomingSection::BlockStream((
556 Some(blocks),
557 incoming_context_section_id,
558 )) => {
559 assert_eq!(
561 incoming_context_section_id.section_index,
562 section_index
563 );
564 assert_eq!(section.drain().await.len(), 1);
566 }
567 _ => core::panic!("Expected a BlockStream section"),
568 }
569 }
570
571 #[tokio::test]
572 async fn receive_multiple_blocks_wrong_order() {
573 let (incoming_sections_sender, mut incoming_sections_receiver) =
574 create_unbounded_channel::<IncomingSection>();
575
576 let block_handler = BlockHandler::init(incoming_sections_sender);
577
578 let context_id = block_handler.get_new_context_id();
579 let section_index = 42;
580
581 let mut blocks = gen move {
583 yield DXBBlock {
584 block_header: BlockHeader {
585 context_id,
586 section_index,
587 block_number: 1,
588 flags_and_timestamp: FlagsAndTimestamp::new()
589 .with_is_end_of_section(true)
590 .with_is_end_of_context(true),
591 ..BlockHeader::default()
592 },
593 routing_header: RoutingHeader::default()
594 .with_sender(TEST_ENDPOINT_A.clone())
595 .with_receivers(Receivers::Endpoints(vec![
596 TEST_ENDPOINT_ORIGIN.clone(),
597 ]))
598 .to_owned(),
599 ..DXBBlock::default()
600 };
601
602 yield DXBBlock {
603 block_header: BlockHeader {
604 context_id,
605 section_index,
606 block_number: 0,
607 flags_and_timestamp: FlagsAndTimestamp::new()
608 .with_is_end_of_section(false)
609 .with_is_end_of_context(false),
610 ..BlockHeader::default()
611 },
612 routing_header: RoutingHeader::default()
613 .with_sender(TEST_ENDPOINT_A.clone())
614 .with_receivers(Receivers::Endpoints(vec![
615 TEST_ENDPOINT_ORIGIN.clone(),
616 ]))
617 .to_owned(),
618 ..DXBBlock::default()
619 };
620 };
621
622 block_handler.handle_incoming_block(blocks.next().unwrap());
624
625 block_handler.handle_incoming_block(blocks.next().unwrap());
627
628 let mut section = incoming_sections_receiver.next().await.unwrap();
630 match §ion {
632 IncomingSection::BlockStream((
633 Some(blocks),
634 incoming_context_section_id,
635 )) => {
636 assert_eq!(
638 incoming_context_section_id.section_index.clone(),
639 section_index
640 );
641 let blocks = section.drain().await;
643 assert_eq!(blocks.len(), 2);
644
645 let block = blocks.first().unwrap();
648 assert_eq!(block.block_header.block_number, 0);
649 let block = blocks.get(1).unwrap();
651 assert_eq!(block.block_header.block_number, 1);
652 }
653 _ => core::panic!("Expected a BlockStream section"),
654 }
655 }
656
657 #[tokio::test]
658 async fn receive_multiple_sections() {
659 let (incoming_sections_sender, mut incoming_sections_receiver) =
660 create_unbounded_channel::<IncomingSection>();
661
662 let block_handler = BlockHandler::init(incoming_sections_sender);
663
664 let context_id = block_handler.get_new_context_id();
665 let section_index_1 = 42;
666 let section_index_2 = 43;
667
668 let mut blocks = gen move {
670 yield DXBBlock {
672 block_header: BlockHeader {
673 context_id,
674 section_index: section_index_1,
675 block_number: 0,
676 flags_and_timestamp: FlagsAndTimestamp::new()
677 .with_is_end_of_section(false)
678 .with_is_end_of_context(false),
679 ..BlockHeader::default()
680 },
681 routing_header: RoutingHeader::default()
682 .with_sender(TEST_ENDPOINT_A.clone())
683 .with_receivers(Receivers::Endpoints(vec![
684 TEST_ENDPOINT_ORIGIN.clone(),
685 ]))
686 .to_owned(),
687 ..DXBBlock::default()
688 };
689
690 yield DXBBlock {
691 block_header: BlockHeader {
692 context_id,
693 section_index: section_index_1,
694 block_number: 1,
695 flags_and_timestamp: FlagsAndTimestamp::new()
696 .with_is_end_of_section(true)
697 .with_is_end_of_context(false),
698 ..BlockHeader::default()
699 },
700 routing_header: RoutingHeader::default()
701 .with_sender(TEST_ENDPOINT_A.clone())
702 .with_receivers(Receivers::Endpoints(vec![
703 TEST_ENDPOINT_ORIGIN.clone(),
704 ]))
705 .to_owned(),
706 ..DXBBlock::default()
707 };
708
709 yield DXBBlock {
711 block_header: BlockHeader {
712 context_id,
713 section_index: section_index_2,
714 block_number: 2,
715 flags_and_timestamp: FlagsAndTimestamp::new()
716 .with_is_end_of_section(false)
717 .with_is_end_of_context(false),
718 ..BlockHeader::default()
719 },
720 routing_header: RoutingHeader::default()
721 .with_sender(TEST_ENDPOINT_A.clone())
722 .with_receivers(Receivers::Endpoints(vec![
723 TEST_ENDPOINT_ORIGIN.clone(),
724 ]))
725 .to_owned(),
726 ..DXBBlock::default()
727 };
728
729 yield DXBBlock {
730 block_header: BlockHeader {
731 context_id,
732 section_index: section_index_2,
733 block_number: 3,
734 flags_and_timestamp: FlagsAndTimestamp::new()
735 .with_is_end_of_section(true)
736 .with_is_end_of_context(true),
737 ..BlockHeader::default()
738 },
739 routing_header: RoutingHeader::default()
740 .with_sender(TEST_ENDPOINT_A.clone())
741 .with_receivers(Receivers::Endpoints(vec![
742 TEST_ENDPOINT_ORIGIN.clone(),
743 ]))
744 .to_owned(),
745 ..DXBBlock::default()
746 };
747 };
748
749 block_handler.handle_incoming_block(blocks.next().unwrap());
751
752 let mut section = incoming_sections_receiver.next().await.unwrap();
754 match §ion {
756 IncomingSection::BlockStream((
757 Some(blocks),
758 incoming_context_section_id,
759 )) => {
760 assert_eq!(
762 incoming_context_section_id.section_index,
763 section_index_1
764 );
765 assert!(section.next().await.is_some());
767 }
768 _ => core::panic!("Expected a BlockStream section"),
769 }
770
771 block_handler.handle_incoming_block(blocks.next().unwrap());
773
774 match §ion {
776 IncomingSection::BlockStream((
777 Some(blocks),
778 incoming_context_section_id,
779 )) => {
780 assert_eq!(
782 incoming_context_section_id.section_index,
783 section_index_1
784 );
785
786 assert_eq!(section.drain().await.len(), 1);
788 }
789 _ => core::panic!("Expected a BlockStream section"),
790 }
791
792 block_handler.handle_incoming_block(blocks.next().unwrap());
794
795 let mut section = incoming_sections_receiver.next().await.unwrap();
797 match §ion {
799 IncomingSection::BlockStream((
800 Some(blocks),
801 incoming_context_section_id,
802 )) => {
803 assert_eq!(
805 incoming_context_section_id.section_index,
806 section_index_2
807 );
808 assert!(section.next().await.is_some());
810 }
811 _ => core::panic!("Expected a BlockStream section"),
812 }
813
814 block_handler.handle_incoming_block(blocks.next().unwrap());
816
817 match §ion {
820 IncomingSection::BlockStream((
821 Some(blocks),
822 incoming_context_section_id,
823 )) => {
824 assert_eq!(
826 incoming_context_section_id.section_index,
827 section_index_2
828 );
829 assert_eq!(section.drain().await.len(), 1);
831 }
832 _ => core::panic!("Expected a BlockStream section"),
833 }
834 }
835
836 #[tokio::test]
837 #[timeout(2000)]
838 #[cfg(feature = "std")]
839 async fn await_response_block() {
840 let (incoming_sections_sender, mut incoming_sections_receiver) =
841 create_unbounded_channel::<IncomingSection>();
842
843 let block_handler = BlockHandler::init(incoming_sections_sender);
844
845 let context_id = block_handler.get_new_context_id();
846 let section_index = 42;
847
848 let block = DXBBlock {
850 block_header: BlockHeader {
851 context_id,
852 section_index,
853 flags_and_timestamp: FlagsAndTimestamp::new()
854 .with_block_type(BlockType::Response)
855 .with_is_end_of_section(true)
856 .with_is_end_of_context(true),
857 ..BlockHeader::default()
858 },
859 routing_header: RoutingHeader::default()
860 .with_sender(TEST_ENDPOINT_A.clone())
861 .with_receivers(Receivers::Endpoints(vec![
862 TEST_ENDPOINT_ORIGIN.clone(),
863 ]))
864 .to_owned(),
865 ..DXBBlock::default()
866 };
867
868 let mut rx = block_handler
870 .register_incoming_block_observer(context_id, section_index);
871
872 block_handler.handle_incoming_block(block);
874
875 let response = rx.next().await.unwrap();
877
878 match response {
880 IncomingSection::SingleBlock((Some(block), _)) => {
881 info!("section: {block:?}");
882 assert_eq!(block.block_header.context_id, context_id);
883 assert_eq!(block.block_header.section_index, section_index);
884 }
885 _ => core::panic!("Expected a SingleBlock section"),
886 }
887 }
888}