Skip to main content

datex_core/network/
block_handler.rs

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// TODO #170: store scope memory
22#[derive(Debug)]
23pub struct ScopeContext {
24    pub next_section_index: IncomingSectionIndex,
25    pub next_block_number: IncomingBlockNumber,
26    /// timestamp of the last keep alive block
27    /// when a specific time has passed since the timestamp, the scope context is disposed
28    /// TODO #171: implement dispose of scope context
29    pub keep_alive_timestamp: u64,
30    // a reference to the sender for the current section
31    pub current_queue_sender: Option<UnboundedSender<DXBBlock>>,
32    // a cache for all blocks indexed by their block number
33    pub cached_blocks: BTreeMap<IncomingBlockNumber, DXBBlock>,
34}
35
36/// A scope context storing scopes of incoming DXB blocks
37impl 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
49// fn that gets a scope context as callback
50type SectionObserver = Box<dyn FnMut(IncomingSection)>;
51
52#[derive(Clone, Debug)]
53pub struct BlockHistoryData {
54    /// if block originated from local endpoint, the socket uuid is None,
55    /// otherwise it is the uuid of the incoming socket
56    pub original_socket_uuid: Option<ComInterfaceSocketUUID>,
57}
58
59pub struct BlockHandler {
60    pub current_context_id: RefCell<OutgoingContextId>,
61
62    /// a map of active request scopes for incoming blocks
63    pub block_cache: RefCell<HashMap<IncomingEndpointContextId, ScopeContext>>,
64
65    /// a queue of incoming request scopes
66    /// the scopes can be retrieved from the request_scopes map
67    pub incoming_sections_sender: RefCell<UnboundedSender<IncomingSection>>,
68
69    /// a map of observers for incoming response blocks (by context_id + block_index)
70    /// contains an observer callback and an optional queue of blocks if the response block is a multi-block stream
71    pub section_observers: RefCell<
72        HashMap<(IncomingContextId, IncomingSectionIndex), SectionObserver>,
73    >,
74
75    /// history of all incoming blocks
76    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("block_cache", &self.block_cache)
85            .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    /// Adds a block to the history of incoming blocks
111    /// if the block is not already in the history
112    /// returns true if the block was added and not already in the history
113    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        // only add if original block
120        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    /// Checks if a block is already in the history
129    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    /// Handles an incoming block by either putting it into the request queue
145    /// or calling the observer for the block if it is a response block
146    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        // handle observers if response block
163        if is_response {
164            self.handle_incoming_response_block(block);
165        } else {
166            self.handle_incoming_request_block(block);
167        }
168    }
169
170    // Handles incoming request blocks by putting them into the request queue
171    fn handle_incoming_request_block(&self, block: DXBBlock) {
172        let new_sections =
173            self.extract_complete_sections_with_new_incoming_block(block);
174        // put into request queue
175        let sender = &self.incoming_sections_sender;
176        for section in new_sections {
177            sender.borrow_mut().start_send(section).unwrap();
178        }
179    }
180
181    /// Handles incoming response blocks by calling the observer if an observer is registered
182    /// Returns true when the observer has consumed all blocks and should be removed
183    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        // try to call the observer for the incoming response block
192        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                // call the observer with the new section
201                observer(section);
202            } else {
203                // no observer for this scope id + block index
204                log::warn!(
205                    "No observer for incoming response block (scope={endpoint_context_id:?}, block={section_index}), dropping block"
206                );
207            };
208        }
209    }
210
211    /// Takes a new incoming block and returns a vector of all new available incoming sections
212    /// for the block's scope
213    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        // get scope context if it already exists
233        let has_scope_context =
234            { self.block_cache.borrow().contains_key(&endpoint_context_id) };
235
236        // Case 1: shortcut if no scope context exists and the block is a single block
237        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        // make sure a scope context exists from here on
248        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        // TODO #172: what happens if the endpoint has not received all blocks starting with block_number 0?
254        // we should still potentially process those blocks
255
256        // Case 2: if the block is the next expected block in the current section, put it into the
257        // section block queue and try to drain blocks from the cache
258        if block_number == scope_context.next_block_number {
259            // list of IncomingSections that is returned at the end
260            let mut new_blocks = vec![];
261
262            // initial values for loop variables from input block
263            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 over the input block and potential blocks from the cache until the next block cannot be found
269            // or the end of the scope is reached
270            loop {
271                if let Some(sender) = &mut scope_context.current_queue_sender {
272                    // send the next block to the section queue receiver
273                    sender.start_send(next_block).expect(
274                        "Failed to send block to current section queue",
275                    );
276                } else {
277                    // create a new block queue for the current section
278                    let (mut sender, receiver) = create_unbounded_channel();
279
280                    // add the first block to the queue
281                    new_blocks.push(IncomingSection::BlockStream((
282                        Some(receiver),
283                        IncomingEndpointContextSectionId::new(
284                            endpoint_context_id.clone(),
285                            section_index,
286                        ),
287                    )));
288
289                    // send the next block to the section queue receiver
290                    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                // cleanup / prepare for next block =======================
298                // increment next block number
299                scope_context.next_block_number += 1;
300
301                // if end of scope, remove the scope context
302                if is_end_of_context {
303                    request_scopes.remove(&endpoint_context_id);
304                    break;
305                }
306                // cleanup if section is finished
307                else if is_end_of_section {
308                    // increment section index
309                    scope_context.next_section_index += 1;
310                    // close and remove the current section queue sender
311                    if let Some(sender) =
312                        scope_context.current_queue_sender.take()
313                    {
314                        sender.close_channel();
315                    }
316                }
317                // ========================================================
318
319                // check if next block is in cache for next iteration
320                if let Some(next_cached_block) = scope_context
321                    .cached_blocks
322                    .remove(&scope_context.next_block_number)
323                {
324                    // check if block is end of section
325                    is_end_of_section = next_cached_block
326                        .block_header
327                        .flags_and_timestamp
328                        .is_end_of_section();
329                    // check if block is end of scope
330                    is_end_of_context = next_cached_block
331                        .block_header
332                        .flags_and_timestamp
333                        .is_end_of_context();
334                    // set next block
335                    next_block = next_cached_block;
336
337                    // update section index from next block
338                    section_index = next_block.block_header.section_index;
339                }
340                // no more blocks in cache, break
341                else {
342                    break;
343                }
344            }
345
346            new_blocks
347        }
348        // Case 3: if the block is not the next expected block in the current section,
349        // put it into the block cache
350        else {
351            // check if block is already in cache
352            // TODO #173: this should not happen, we should make sure duplicate blocks are dropped before
353            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            // add block to cache
360            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    /// Adds a new observer for incoming blocks with a specific scope id and block index
372    /// Returns a receiver that can be awaited to get the incoming sections
373    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        // create observer callback for scope id + block index
382        let observer = move |blocks: IncomingSection| {
383            tx.clone().borrow_mut().start_send(blocks).unwrap();
384        };
385
386        // add new scope observer
387        self.section_observers
388            .borrow_mut()
389            .insert((context_id, section_index), Box::new(observer));
390
391        rx
392    }
393
394    /// Waits for incoming response block with a specific scope id and block index
395    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        // Await the result from the callback
403        // FIXME #174
404        None
405        // rx.next().await
406    }
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        // Create a single DXB block
440        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        // Send incoming block to block handler
459        block_handler.handle_incoming_block(block);
460
461        // block must be in incoming_sections_receiver
462        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        // Create multiple DXB blocks for the same context and section
485        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        // 1. Send first block
526        block_handler.handle_incoming_block(blocks.next().unwrap());
527
528        info!("Checking incoming sections...");
529
530        // block must be in incoming_sections_queue
531        let mut section = incoming_sections_receiver.next().await.unwrap();
532        match &section {
533            IncomingSection::BlockStream((
534                Some(blocks),
535                incoming_context_section_id,
536            )) => {
537                // section must match
538                assert_eq!(
539                    incoming_context_section_id.section_index,
540                    section_index
541                );
542
543                // blocks queue must contain the first block
544                assert!(section.next().await.is_some());
545            }
546            _ => core::panic!("Expected a BlockStream section"),
547        }
548
549        // 2. Send second block
550        block_handler.handle_incoming_block(blocks.next().unwrap());
551
552        // no new incoming sections, old section receives new blocks
553        // block must be a block stream
554        match &section {
555            IncomingSection::BlockStream((
556                Some(blocks),
557                incoming_context_section_id,
558            )) => {
559                // section must match
560                assert_eq!(
561                    incoming_context_section_id.section_index,
562                    section_index
563                );
564                // blocks queue length must be 2 (was not yet drained)
565                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        // Create multiple DXB blocks for the same context and section in wrong order
582        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        // 1. Send first block
623        block_handler.handle_incoming_block(blocks.next().unwrap());
624
625        // 2. Send second block
626        block_handler.handle_incoming_block(blocks.next().unwrap());
627
628        // block must be in incoming_sections_queue
629        let mut section = incoming_sections_receiver.next().await.unwrap();
630        // block must be a block stream
631        match &section {
632            IncomingSection::BlockStream((
633                Some(blocks),
634                incoming_context_section_id,
635            )) => {
636                // section must match
637                assert_eq!(
638                    incoming_context_section_id.section_index.clone(),
639                    section_index
640                );
641                // blocks queue length must be 2
642                let blocks = section.drain().await;
643                assert_eq!(blocks.len(), 2);
644
645                // check order:
646                // first block must have block number 0
647                let block = blocks.first().unwrap();
648                assert_eq!(block.block_header.block_number, 0);
649                // second block must have block number 1
650                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        // Create multiple DXB blocks for two sections
669        let mut blocks = gen move {
670            // first section
671            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            // second section, end of context
710            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        // 1. Send first block
750        block_handler.handle_incoming_block(blocks.next().unwrap());
751
752        // block must be in incoming_sections_queue
753        let mut section = incoming_sections_receiver.next().await.unwrap();
754        // block must be a block stream
755        match &section {
756            IncomingSection::BlockStream((
757                Some(blocks),
758                incoming_context_section_id,
759            )) => {
760                // section must match
761                assert_eq!(
762                    incoming_context_section_id.section_index,
763                    section_index_1
764                );
765                // block queue must contain the first block
766                assert!(section.next().await.is_some());
767            }
768            _ => core::panic!("Expected a BlockStream section"),
769        }
770
771        // 2. Send second block
772        block_handler.handle_incoming_block(blocks.next().unwrap());
773
774        // block must be a block stream
775        match &section {
776            IncomingSection::BlockStream((
777                Some(blocks),
778                incoming_context_section_id,
779            )) => {
780                // section must match
781                assert_eq!(
782                    incoming_context_section_id.section_index,
783                    section_index_1
784                );
785
786                // blocks queue length must be 1
787                assert_eq!(section.drain().await.len(), 1);
788            }
789            _ => core::panic!("Expected a BlockStream section"),
790        }
791
792        // 3. Send third block
793        block_handler.handle_incoming_block(blocks.next().unwrap());
794
795        // block must be in incoming_sections_queue
796        let mut section = incoming_sections_receiver.next().await.unwrap();
797        // block must be a block stream
798        match &section {
799            IncomingSection::BlockStream((
800                Some(blocks),
801                incoming_context_section_id,
802            )) => {
803                // section must match
804                assert_eq!(
805                    incoming_context_section_id.section_index,
806                    section_index_2
807                );
808                // block queue must contain the first block
809                assert!(section.next().await.is_some());
810            }
811            _ => core::panic!("Expected a BlockStream section"),
812        }
813
814        // 4. Send fourth block
815        block_handler.handle_incoming_block(blocks.next().unwrap());
816
817        // block must not be in incoming_sections_queue
818        // block must be a block stream
819        match &section {
820            IncomingSection::BlockStream((
821                Some(blocks),
822                incoming_context_section_id,
823            )) => {
824                // section must match
825                assert_eq!(
826                    incoming_context_section_id.section_index,
827                    section_index_2
828                );
829                // blocks queue length must be 1
830                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        // Create a single DXB block
849        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        // set observer for the block
869        let mut rx = block_handler
870            .register_incoming_block_observer(context_id, section_index);
871
872        // Put into incoming queue of mock interface
873        block_handler.handle_incoming_block(block);
874
875        // await receiver
876        let response = rx.next().await.unwrap();
877
878        // IncomingSection must be a SingleBlock
879        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}