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};
15use alloc::rc::Weak;
16
17use crate::{disassembler::print_disassembled, prelude::*};
18use core::{cell::RefCell, fmt::Debug};
19use log::{info, warn};
20use ringmap::RingMap;
21
22#[derive(Debug)]
24pub struct ScopeContext {
25 pub next_section_index: IncomingSectionIndex,
26 pub next_block_number: IncomingBlockNumber,
27 pub keep_alive_timestamp: u64,
31 pub current_queue_sender: Option<UnboundedSender<DXBBlock>>,
33 pub cached_blocks: BTreeMap<IncomingBlockNumber, DXBBlock>,
35}
36
37impl Default for ScopeContext {
39 fn default() -> Self {
40 ScopeContext {
41 next_section_index: 0,
42 next_block_number: 0,
43 keep_alive_timestamp: crate::time::now_ms(),
44 current_queue_sender: None,
45 cached_blocks: BTreeMap::new(),
46 }
47 }
48}
49
50type SectionObserver = Box<dyn FnMut(IncomingSection)>;
52
53pub type IncomingSectionSender = UnboundedSender<IncomingSection>;
65pub type IncomingSectionReceiver = UnboundedReceiver<IncomingSection>;
66pub fn create_incoming_sections_channel()
67-> (IncomingSectionSender, IncomingSectionReceiver) {
68 create_unbounded_channel()
69}
70
71pub struct IncomingSectionReceiverWrapper {
73 rx: IncomingSectionReceiver,
74 key: (OutgoingContextId, OutgoingSectionIndex),
75 observers: Weak<
76 RefCell<
77 HashMap<
78 (OutgoingContextId, OutgoingSectionIndex),
79 Box<dyn FnMut(IncomingSection)>,
80 >,
81 >,
82 >,
83}
84
85impl IncomingSectionReceiverWrapper {
86 pub async fn next(&mut self) -> Option<IncomingSection> {
87 self.rx.next().await
88 }
89}
90
91impl Drop for IncomingSectionReceiverWrapper {
92 fn drop(&mut self) {
93 if let Some(observers) = self.observers.upgrade() {
94 observers.borrow_mut().remove(&self.key);
95 }
96 }
97}
98
99#[derive(Clone, Debug)]
100pub struct BlockHistoryData {
101 pub original_socket_uuid: Option<ComInterfaceSocketUUID>,
104}
105
106pub struct BlockHandler {
107 pub current_context_id: RefCell<OutgoingContextId>,
108
109 pub block_cache: RefCell<HashMap<IncomingEndpointContextId, ScopeContext>>,
111
112 pub incoming_sections_sender: RefCell<IncomingSectionSender>,
115
116 pub section_observers: Rc<
119 RefCell<
120 HashMap<(IncomingContextId, IncomingSectionIndex), SectionObserver>,
121 >,
122 >,
123
124 pub incoming_blocks_history:
126 RefCell<RingMap<BlockId, BlockHistoryData, RandomState>>,
127}
128
129impl Debug for BlockHandler {
130 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
131 f.debug_struct("BlockHandler")
132 .field("current_context_id", &self.current_context_id)
133 .field("incoming_blocks_history", &self.incoming_blocks_history)
135 .finish()
136 }
137}
138
139impl BlockHandler {
140 pub const DEFAULT_HISTORY_CAPACITY: usize = 200; pub fn init(
143 incoming_sections_sender: IncomingSectionSender,
144 history_capacity: usize,
145 ) -> BlockHandler {
146 BlockHandler {
147 current_context_id: RefCell::new(0),
148 block_cache: RefCell::new(HashMap::new()),
149 incoming_sections_sender: RefCell::new(incoming_sections_sender),
150 section_observers: Rc::new(RefCell::new(HashMap::new())),
151 incoming_blocks_history: RefCell::new(
152 RingMap::with_capacity_and_hasher(
153 history_capacity,
154 RandomState::default(),
155 ),
156 ),
157 }
158 }
159
160 pub fn add_block_id_to_history(
164 &self,
165 block_id: BlockId,
166 original_socket_uuid: Option<ComInterfaceSocketUUID>,
167 ) {
168 let mut history = self.incoming_blocks_history.borrow_mut();
169 if !history.contains_key(&block_id) {
171 let block_data = BlockHistoryData {
172 original_socket_uuid,
173 };
174 history.insert(block_id, block_data);
175 }
176 }
177
178 pub fn is_block_in_history(&self, block: &DXBBlock) -> bool {
180 let history = self.incoming_blocks_history.borrow();
181 let block_id = block.get_block_id();
182 history.contains_key(&block_id)
183 }
184
185 pub fn get_block_data_from_history(
186 &self,
187 block: &DXBBlock,
188 ) -> Option<BlockHistoryData> {
189 let history = self.incoming_blocks_history.borrow();
190 let block_id = block.get_block_id();
191 history.get(&block_id).cloned()
192 }
193
194 pub fn handle_incoming_block(&self, block: DXBBlock) {
197 info!("Handling incoming block...");
198 let context_id = block.block_header.context_id;
199 let section_index = block.block_header.section_index;
200 let block_number = block.block_header.block_number;
201 let is_response = block
202 .block_header
203 .flags_and_timestamp
204 .block_type()
205 .is_response();
206
207 info!(
208 "Received block (context={context_id}, section={section_index}, block_nr={block_number})"
209 );
210 print_disassembled(&block.body);
211
212 if is_response {
214 self.handle_incoming_response_block(block);
215 } else {
216 self.handle_incoming_request_block(block);
217 }
218 }
219
220 fn handle_incoming_request_block(&self, block: DXBBlock) {
222 let new_sections =
223 self.extract_complete_sections_with_new_incoming_block(block);
224 let sender = &self.incoming_sections_sender;
226 for section in new_sections {
227 sender.borrow_mut().start_send(section).unwrap();
228 }
229 }
230
231 fn handle_incoming_response_block(&self, block: DXBBlock) {
234 let context_id = block.block_header.context_id;
235 let endpoint_context_id = IncomingEndpointContextId {
236 sender: block.routing_header.sender.clone(),
237 context_id,
238 };
239 let new_sections =
240 self.extract_complete_sections_with_new_incoming_block(block);
241 for section in new_sections {
243 let section_index = section.get_section_index();
244
245 if let Some(observer) = self
246 .section_observers
247 .borrow_mut()
248 .get_mut(&(context_id, section_index))
249 {
250 observer(section);
252 } else {
253 log::warn!(
255 "No observer for incoming response block (scope={endpoint_context_id:?}, block={section_index}), dropping block"
256 );
257 };
258 }
259 }
260
261 fn extract_complete_sections_with_new_incoming_block(
264 &self,
265 block: DXBBlock,
266 ) -> Vec<IncomingSection> {
267 let section_index = block.block_header.section_index;
268 let block_number = block.block_header.block_number;
269 let skip_after_block = block.block_header.skip_after_block;
270 let is_end_of_section =
271 block.block_header.flags_and_timestamp.is_end_of_section();
272 let is_end_of_context =
273 block.block_header.flags_and_timestamp.is_end_of_context();
274 let endpoint_context_id = IncomingEndpointContextId {
275 sender: block.routing_header.sender.clone(),
276 context_id: block.block_header.context_id,
277 };
278 let section_context_id = IncomingEndpointContextSectionId::new(
279 endpoint_context_id.clone(),
280 section_index,
281 );
282
283 let has_scope_context =
285 { self.block_cache.borrow().contains_key(&endpoint_context_id) };
286
287 if !has_scope_context
289 && block_number == 0
290 && (is_end_of_section || is_end_of_context)
291 {
292 return vec![IncomingSection::SingleBlock((
293 Some(block),
294 section_context_id.clone(),
295 ))];
296 }
297
298 let mut request_scopes = self.block_cache.borrow_mut();
300 let scope_context = request_scopes
301 .entry(endpoint_context_id.clone())
302 .or_default();
303
304 if let Some(skip_after_block) = skip_after_block {
309 if scope_context.next_block_number == skip_after_block + 1 {
312 scope_context.next_block_number = block_number;
313 }
314 else if scope_context.next_block_number <= skip_after_block {
317 todo!()
318 }
319 else {
322 log::warn!(
323 "Received block with skip_after_block={} but next_block_number is {}.",
324 skip_after_block,
325 scope_context.next_block_number
326 );
327 scope_context.next_block_number = block_number;
328 }
329 }
330
331 if block_number == scope_context.next_block_number {
334 let mut new_blocks = vec![];
336
337 let mut is_end_of_context = is_end_of_context;
339 let mut is_end_of_section = is_end_of_section;
340 let mut next_block = block;
341 let mut section_index = section_index;
342
343 loop {
346 if let Some(sender) = &mut scope_context.current_queue_sender {
347 sender.start_send(next_block).expect(
349 "Failed to send block to current section queue",
350 );
351 } else {
352 let (mut sender, receiver) = create_unbounded_channel();
354
355 new_blocks.push(IncomingSection::BlockStream((
357 Some(receiver),
358 IncomingEndpointContextSectionId::new(
359 endpoint_context_id.clone(),
360 section_index,
361 ),
362 )));
363
364 sender.start_send(next_block).expect(
366 "Failed to send first block to current section queue",
367 );
368
369 scope_context.current_queue_sender = Some(sender);
370 }
371
372 scope_context.next_block_number += 1;
375
376 if is_end_of_context {
378 request_scopes.remove(&endpoint_context_id);
379 break;
380 }
381 else if is_end_of_section {
383 scope_context.next_section_index += 1;
385 if let Some(sender) =
387 scope_context.current_queue_sender.take()
388 {
389 sender.close_channel();
390 }
391 }
392 if let Some(next_cached_block) = scope_context
396 .cached_blocks
397 .remove(&scope_context.next_block_number)
398 {
399 is_end_of_section = next_cached_block
401 .block_header
402 .flags_and_timestamp
403 .is_end_of_section();
404 is_end_of_context = next_cached_block
406 .block_header
407 .flags_and_timestamp
408 .is_end_of_context();
409 next_block = next_cached_block;
411
412 section_index = next_block.block_header.section_index;
414 }
415 else {
417 break;
418 }
419 }
420
421 new_blocks
422 }
423 else {
426 if scope_context.cached_blocks.contains_key(&block_number) {
429 log::warn!(
430 "Block {block_number} already in cache, dropping block"
431 );
432 }
433
434 scope_context.cached_blocks.insert(block_number, block);
436
437 vec![]
438 }
439 }
440
441 pub fn get_new_context_id(&self) -> OutgoingContextId {
442 *self.current_context_id.borrow_mut() += 1;
443 *self.current_context_id.borrow()
444 }
445
446 pub fn register_incoming_block_observer(
449 &self,
450 context_id: OutgoingContextId,
451 section_index: OutgoingSectionIndex,
452 ) -> IncomingSectionReceiverWrapper {
453 let (tx, rx) = create_incoming_sections_channel();
454 let tx = Rc::new(RefCell::new(tx));
455
456 let observer = move |blocks: IncomingSection| {
458 if let Err(_e) = tx.borrow_mut().start_send(blocks) {
459 warn!(
460 "Failed to send incoming section to observer, receiver was dropped"
461 );
462 }
463 };
464
465 if self
467 .section_observers
468 .borrow()
469 .contains_key(&(context_id, section_index))
470 {
471 panic!(
472 "Observer for incoming response block (scope={context_id}, block={section_index}) already exists"
473 );
474 }
475
476 self.section_observers
478 .borrow_mut()
479 .insert((context_id, section_index), Box::new(observer));
480
481 IncomingSectionReceiverWrapper {
482 rx,
483 key: (context_id, section_index),
484 observers: Rc::downgrade(&self.section_observers),
485 }
486 }
487
488 pub async fn wait_for_incoming_response_block(
490 &self,
491 context_id: OutgoingContextId,
492 section_index: OutgoingSectionIndex,
493 ) -> Option<IncomingSection> {
494 let _rx =
495 self.register_incoming_block_observer(context_id, section_index);
496 None
499 }
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506 use crate::{
507 global::{
508 dxb_block::{DXBBlock, IncomingSection},
509 protocol_structures::{
510 block_header::{BlockHeader, FlagsAndTimestamp},
511 routing_header::{Receivers, RoutingHeader},
512 },
513 },
514 values::core_values::endpoint::Endpoint,
515 };
516 use core::str::FromStr;
517 #[cfg(feature = "std")]
518 use ntest_timeout::timeout;
519
520 lazy_static::lazy_static! {
521 pub static ref TEST_ENDPOINT_ORIGIN: Endpoint = Endpoint::from_str("@origin").unwrap();
522 pub static ref TEST_ENDPOINT_A: Endpoint = Endpoint::from_str("@test-a").unwrap();
523 pub static ref TEST_ENDPOINT_B: Endpoint = Endpoint::from_str("@test-b").unwrap();
524 }
525
526 #[tokio::test]
527 async fn receive_single_block() {
528 let (incoming_sections_sender, mut incoming_sections_receiver) =
529 create_incoming_sections_channel();
530
531 let block_handler = BlockHandler::init(
532 incoming_sections_sender,
533 BlockHandler::DEFAULT_HISTORY_CAPACITY,
534 );
535 let context_id = block_handler.get_new_context_id();
536
537 let block = DXBBlock {
539 block_header: BlockHeader {
540 context_id,
541 flags_and_timestamp: FlagsAndTimestamp::new()
542 .with_is_end_of_section(true)
543 .with_is_end_of_context(true),
544 ..BlockHeader::default()
545 },
546 routing_header: RoutingHeader::default()
547 .with_sender(TEST_ENDPOINT_A.clone())
548 .with_receivers(Receivers::Endpoints(vec![
549 TEST_ENDPOINT_ORIGIN.clone(),
550 ]))
551 .to_owned(),
552 ..DXBBlock::default()
553 };
554 let block_endpoint_context_id = block.get_endpoint_context_id();
555
556 block_handler.handle_incoming_block(block);
558
559 let incoming_block = incoming_sections_receiver.next().await.unwrap();
561 match &incoming_block {
562 IncomingSection::SingleBlock((Some(received_block), ..)) => {
563 assert_eq!(
564 received_block.get_endpoint_context_id(),
565 block_endpoint_context_id
566 );
567 }
568 _ => panic!("Expected a SingleBlock section"),
569 }
570 }
571
572 #[tokio::test]
573 async fn receive_multiple_blocks() {
574 let (incoming_sections_sender, mut incoming_sections_receiver) =
575 create_incoming_sections_channel();
576
577 let block_handler = BlockHandler::init(
578 incoming_sections_sender,
579 BlockHandler::DEFAULT_HISTORY_CAPACITY,
580 );
581
582 let context_id = block_handler.get_new_context_id();
583 let section_index = 42;
584
585 let mut blocks = gen move {
587 yield DXBBlock {
588 block_header: BlockHeader {
589 context_id,
590 section_index,
591 block_number: 0,
592 flags_and_timestamp: FlagsAndTimestamp::new()
593 .with_is_end_of_section(false)
594 .with_is_end_of_context(false),
595 ..BlockHeader::default()
596 },
597 routing_header: RoutingHeader::default()
598 .with_sender(TEST_ENDPOINT_A.clone())
599 .with_receivers(Receivers::Endpoints(vec![
600 TEST_ENDPOINT_ORIGIN.clone(),
601 ]))
602 .to_owned(),
603 ..DXBBlock::default()
604 };
605
606 yield DXBBlock {
607 block_header: BlockHeader {
608 context_id,
609 section_index,
610 block_number: 1,
611 flags_and_timestamp: FlagsAndTimestamp::new()
612 .with_is_end_of_section(true)
613 .with_is_end_of_context(true),
614 ..BlockHeader::default()
615 },
616 routing_header: RoutingHeader::default()
617 .with_sender(TEST_ENDPOINT_A.clone())
618 .with_receivers(Receivers::Endpoints(vec![
619 TEST_ENDPOINT_ORIGIN.clone(),
620 ]))
621 .to_owned(),
622 ..DXBBlock::default()
623 };
624 };
625
626 block_handler.handle_incoming_block(blocks.next().unwrap());
628
629 info!("Checking incoming sections...");
630
631 let mut section = incoming_sections_receiver.next().await.unwrap();
633 match §ion {
634 IncomingSection::BlockStream((
635 Some(_),
636 incoming_context_section_id,
637 )) => {
638 assert_eq!(
640 incoming_context_section_id.section_index,
641 section_index
642 );
643
644 assert!(section.next().await.is_some());
646 }
647 _ => panic!("Expected a BlockStream section"),
648 }
649
650 block_handler.handle_incoming_block(blocks.next().unwrap());
652
653 match §ion {
656 IncomingSection::BlockStream((
657 Some(_),
658 incoming_context_section_id,
659 )) => {
660 assert_eq!(
662 incoming_context_section_id.section_index,
663 section_index
664 );
665 assert_eq!(section.drain().await.len(), 1);
667 }
668 _ => panic!("Expected a BlockStream section"),
669 }
670 }
671
672 #[tokio::test]
673 async fn receive_multiple_blocks_wrong_order() {
674 let (incoming_sections_sender, mut incoming_sections_receiver) =
675 create_unbounded_channel::<IncomingSection>();
676
677 let block_handler = BlockHandler::init(
678 incoming_sections_sender,
679 BlockHandler::DEFAULT_HISTORY_CAPACITY,
680 );
681
682 let context_id = block_handler.get_new_context_id();
683 let section_index = 42;
684
685 let mut blocks = gen move {
687 yield DXBBlock {
688 block_header: BlockHeader {
689 context_id,
690 section_index,
691 block_number: 1,
692 flags_and_timestamp: FlagsAndTimestamp::new()
693 .with_is_end_of_section(true)
694 .with_is_end_of_context(true),
695 ..BlockHeader::default()
696 },
697 routing_header: RoutingHeader::default()
698 .with_sender(TEST_ENDPOINT_A.clone())
699 .with_receivers(Receivers::Endpoints(vec![
700 TEST_ENDPOINT_ORIGIN.clone(),
701 ]))
702 .to_owned(),
703 ..DXBBlock::default()
704 };
705
706 yield DXBBlock {
707 block_header: BlockHeader {
708 context_id,
709 section_index,
710 block_number: 0,
711 flags_and_timestamp: FlagsAndTimestamp::new()
712 .with_is_end_of_section(false)
713 .with_is_end_of_context(false),
714 ..BlockHeader::default()
715 },
716 routing_header: RoutingHeader::default()
717 .with_sender(TEST_ENDPOINT_A.clone())
718 .with_receivers(Receivers::Endpoints(vec![
719 TEST_ENDPOINT_ORIGIN.clone(),
720 ]))
721 .to_owned(),
722 ..DXBBlock::default()
723 };
724 };
725
726 block_handler.handle_incoming_block(blocks.next().unwrap());
728
729 block_handler.handle_incoming_block(blocks.next().unwrap());
731
732 let mut section = incoming_sections_receiver.next().await.unwrap();
734 match §ion {
736 IncomingSection::BlockStream((
737 Some(_),
738 incoming_context_section_id,
739 )) => {
740 assert_eq!(
742 incoming_context_section_id.section_index.clone(),
743 section_index
744 );
745 let blocks = section.drain().await;
747 assert_eq!(blocks.len(), 2);
748
749 let block = blocks.first().unwrap();
752 assert_eq!(block.block_header.block_number, 0);
753 let block = blocks.get(1).unwrap();
755 assert_eq!(block.block_header.block_number, 1);
756 }
757 _ => panic!("Expected a BlockStream section"),
758 }
759 }
760
761 #[tokio::test]
762 async fn receive_multiple_sections() {
763 let (incoming_sections_sender, mut incoming_sections_receiver) =
764 create_incoming_sections_channel();
765
766 let block_handler = BlockHandler::init(
767 incoming_sections_sender,
768 BlockHandler::DEFAULT_HISTORY_CAPACITY,
769 );
770
771 let context_id = block_handler.get_new_context_id();
772 let section_index_1 = 42;
773 let section_index_2 = 43;
774
775 let mut blocks = gen move {
777 yield DXBBlock {
779 block_header: BlockHeader {
780 context_id,
781 section_index: section_index_1,
782 block_number: 0,
783 flags_and_timestamp: FlagsAndTimestamp::new()
784 .with_is_end_of_section(false)
785 .with_is_end_of_context(false),
786 ..BlockHeader::default()
787 },
788 routing_header: RoutingHeader::default()
789 .with_sender(TEST_ENDPOINT_A.clone())
790 .with_receivers(Receivers::Endpoints(vec![
791 TEST_ENDPOINT_ORIGIN.clone(),
792 ]))
793 .to_owned(),
794 ..DXBBlock::default()
795 };
796
797 yield DXBBlock {
798 block_header: BlockHeader {
799 context_id,
800 section_index: section_index_1,
801 block_number: 1,
802 flags_and_timestamp: FlagsAndTimestamp::new()
803 .with_is_end_of_section(true)
804 .with_is_end_of_context(false),
805 ..BlockHeader::default()
806 },
807 routing_header: RoutingHeader::default()
808 .with_sender(TEST_ENDPOINT_A.clone())
809 .with_receivers(Receivers::Endpoints(vec![
810 TEST_ENDPOINT_ORIGIN.clone(),
811 ]))
812 .to_owned(),
813 ..DXBBlock::default()
814 };
815
816 yield DXBBlock {
818 block_header: BlockHeader {
819 context_id,
820 section_index: section_index_2,
821 block_number: 2,
822 flags_and_timestamp: FlagsAndTimestamp::new()
823 .with_is_end_of_section(false)
824 .with_is_end_of_context(false),
825 ..BlockHeader::default()
826 },
827 routing_header: RoutingHeader::default()
828 .with_sender(TEST_ENDPOINT_A.clone())
829 .with_receivers(Receivers::Endpoints(vec![
830 TEST_ENDPOINT_ORIGIN.clone(),
831 ]))
832 .to_owned(),
833 ..DXBBlock::default()
834 };
835
836 yield DXBBlock {
837 block_header: BlockHeader {
838 context_id,
839 section_index: section_index_2,
840 block_number: 3,
841 flags_and_timestamp: FlagsAndTimestamp::new()
842 .with_is_end_of_section(true)
843 .with_is_end_of_context(true),
844 ..BlockHeader::default()
845 },
846 routing_header: RoutingHeader::default()
847 .with_sender(TEST_ENDPOINT_A.clone())
848 .with_receivers(Receivers::Endpoints(vec![
849 TEST_ENDPOINT_ORIGIN.clone(),
850 ]))
851 .to_owned(),
852 ..DXBBlock::default()
853 };
854 };
855
856 block_handler.handle_incoming_block(blocks.next().unwrap());
858
859 let mut section = incoming_sections_receiver.next().await.unwrap();
861 match §ion {
863 IncomingSection::BlockStream((
864 Some(_),
865 incoming_context_section_id,
866 )) => {
867 assert_eq!(
869 incoming_context_section_id.section_index,
870 section_index_1
871 );
872 assert!(section.next().await.is_some());
874 }
875 _ => panic!("Expected a BlockStream section"),
876 }
877
878 block_handler.handle_incoming_block(blocks.next().unwrap());
880
881 match §ion {
883 IncomingSection::BlockStream((
884 Some(_),
885 incoming_context_section_id,
886 )) => {
887 assert_eq!(
889 incoming_context_section_id.section_index,
890 section_index_1
891 );
892
893 assert_eq!(section.drain().await.len(), 1);
895 }
896 _ => panic!("Expected a BlockStream section"),
897 }
898
899 block_handler.handle_incoming_block(blocks.next().unwrap());
901
902 let mut section = incoming_sections_receiver.next().await.unwrap();
904 match §ion {
906 IncomingSection::BlockStream((
907 Some(_),
908 incoming_context_section_id,
909 )) => {
910 assert_eq!(
912 incoming_context_section_id.section_index,
913 section_index_2
914 );
915 assert!(section.next().await.is_some());
917 }
918 _ => panic!("Expected a BlockStream section"),
919 }
920
921 block_handler.handle_incoming_block(blocks.next().unwrap());
923
924 match §ion {
927 IncomingSection::BlockStream((
928 Some(_),
929 incoming_context_section_id,
930 )) => {
931 assert_eq!(
933 incoming_context_section_id.section_index,
934 section_index_2
935 );
936 assert_eq!(section.drain().await.len(), 1);
938 }
939 _ => panic!("Expected a BlockStream section"),
940 }
941 }
942
943 #[tokio::test]
944 #[timeout(2000)]
945 #[cfg(feature = "std")]
946 async fn await_response_block() {
947 use crate::global::protocol_structures::block_header::BlockType;
948 let (incoming_sections_sender, _incoming_sections_receiver) =
949 create_incoming_sections_channel();
950
951 let block_handler = BlockHandler::init(
952 incoming_sections_sender,
953 BlockHandler::DEFAULT_HISTORY_CAPACITY,
954 );
955
956 let context_id = block_handler.get_new_context_id();
957 let section_index = 42;
958
959 let block = DXBBlock {
961 block_header: BlockHeader {
962 context_id,
963 section_index,
964 flags_and_timestamp: FlagsAndTimestamp::new()
965 .with_block_type(BlockType::Response)
966 .with_is_end_of_section(true)
967 .with_is_end_of_context(true),
968 ..BlockHeader::default()
969 },
970 routing_header: RoutingHeader::default()
971 .with_sender(TEST_ENDPOINT_A.clone())
972 .with_receivers(Receivers::Endpoints(vec![
973 TEST_ENDPOINT_ORIGIN.clone(),
974 ]))
975 .to_owned(),
976 ..DXBBlock::default()
977 };
978
979 let mut rx = block_handler
981 .register_incoming_block_observer(context_id, section_index);
982
983 block_handler.handle_incoming_block(block);
985
986 let response = rx.next().await.unwrap();
988
989 match response {
991 IncomingSection::SingleBlock((Some(block), _)) => {
992 info!("section: {block:?}");
993 assert_eq!(block.block_header.context_id, context_id);
994 assert_eq!(block.block_header.section_index, section_index);
995 }
996 _ => panic!("Expected a SingleBlock section"),
997 }
998 }
999}