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};
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// TODO #170: store scope memory
23#[derive(Debug)]
24pub struct ScopeContext {
25    pub next_section_index: IncomingSectionIndex,
26    pub next_block_number: IncomingBlockNumber,
27    /// timestamp of the last keep alive block
28    /// when a specific time has passed since the timestamp, the scope context is disposed
29    /// TODO #171: implement dispose of scope context
30    pub keep_alive_timestamp: u64,
31    // a reference to the sender for the current section
32    pub current_queue_sender: Option<UnboundedSender<DXBBlock>>,
33    // a cache for all blocks indexed by their block number
34    pub cached_blocks: BTreeMap<IncomingBlockNumber, DXBBlock>,
35}
36
37/// A scope context storing scopes of incoming DXB blocks
38impl 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
50// fn that gets a scope context as callback
51type SectionObserver = Box<dyn FnMut(IncomingSection)>;
52
53// FIXME: handle backpressure for incoming sections in block handler with optional bounded senders/receivers
54
55// pub type IncomingSectionSender = Sender<IncomingSection>;
56// pub type IncomingSectionReceiver = Receiver<IncomingSection>;
57//
58// const INCOMING_SECTIONS_CHANNEL_CAPACITY: usize = 2;
59//
60// pub fn create_incoming_sections_channel() -> (IncomingSectionSender, IncomingSectionReceiver) {
61//     create_bounded_channel(INCOMING_SECTIONS_CHANNEL_CAPACITY)
62// }
63
64pub type IncomingSectionSender = UnboundedSender<IncomingSection>;
65pub type IncomingSectionReceiver = UnboundedReceiver<IncomingSection>;
66pub fn create_incoming_sections_channel()
67-> (IncomingSectionSender, IncomingSectionReceiver) {
68    create_unbounded_channel()
69}
70
71/// A wrapper for the incoming section receiver that removes the observer from the block handler when dropped
72pub 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    /// if block originated from local endpoint, the socket uuid is None,
102    /// otherwise it is the uuid of the incoming socket
103    pub original_socket_uuid: Option<ComInterfaceSocketUUID>,
104}
105
106pub struct BlockHandler {
107    pub current_context_id: RefCell<OutgoingContextId>,
108
109    /// a map of active request scopes for incoming blocks
110    pub block_cache: RefCell<HashMap<IncomingEndpointContextId, ScopeContext>>,
111
112    /// a queue of incoming request scopes
113    /// the scopes can be retrieved from the request_scopes map
114    pub incoming_sections_sender: RefCell<IncomingSectionSender>,
115
116    /// a map of observers for incoming response blocks (by context_id + block_index)
117    /// contains an observer callback and an optional queue of blocks if the response block is a multi-block stream
118    pub section_observers: Rc<
119        RefCell<
120            HashMap<(IncomingContextId, IncomingSectionIndex), SectionObserver>,
121        >,
122    >,
123
124    /// history of all incoming blocks
125    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("block_cache", &self.block_cache)
134            .field("incoming_blocks_history", &self.incoming_blocks_history)
135            .finish()
136    }
137}
138
139impl BlockHandler {
140    pub const DEFAULT_HISTORY_CAPACITY: usize = 200; // TODO: adjust for different targets;
141
142    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    /// Adds a block to the history of incoming blocks
161    /// if the block is not already in the history
162    /// returns true if the block was added and not already in the history
163    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        // only add if original block
170        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    /// Checks if a block is already in the history
179    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    /// Handles an incoming block by either putting it into the request queue
195    /// or calling the observer for the block if it is a response block
196    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        // handle observers if response block
213        if is_response {
214            self.handle_incoming_response_block(block);
215        } else {
216            self.handle_incoming_request_block(block);
217        }
218    }
219
220    // Handles incoming request blocks by putting them into the request queue
221    fn handle_incoming_request_block(&self, block: DXBBlock) {
222        let new_sections =
223            self.extract_complete_sections_with_new_incoming_block(block);
224        // put into request queue
225        let sender = &self.incoming_sections_sender;
226        for section in new_sections {
227            sender.borrow_mut().start_send(section).unwrap();
228        }
229    }
230
231    /// Handles incoming response blocks by calling the observer if an observer is registered
232    /// Returns true when the observer has consumed all blocks and should be removed
233    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        // try to call the observer for the incoming response block
242        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                // call the observer with the new section
251                observer(section);
252            } else {
253                // no observer for this scope id + block index
254                log::warn!(
255                    "No observer for incoming response block (scope={endpoint_context_id:?}, block={section_index}), dropping block"
256                );
257            };
258        }
259    }
260
261    /// Takes a new incoming block and returns a vector of all new available incoming sections
262    /// for the block's scope
263    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        // get scope context if it already exists
284        let has_scope_context =
285            { self.block_cache.borrow().contains_key(&endpoint_context_id) };
286
287        // Case 1: shortcut if no scope context exists and the block is a single block
288        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        // make sure a scope context exists from here on
299        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        // TODO #172: what happens if the endpoint has not received all blocks starting with block_number 0?
305        // we should still potentially process those blocks
306
307        // special handling of skipped blocks:
308        if let Some(skip_after_block) = skip_after_block {
309            // if skip_after_block is set and is next_block_number is skip_after_block + 1
310            // set next_block_number to current block (skip all blocks up to the current block)
311            if scope_context.next_block_number == skip_after_block + 1 {
312                scope_context.next_block_number = block_number;
313            }
314            // if skip_after_block is set and next_block_number is less than or
315            // equal to skip_after_block, we still need to wait for some blocks
316            else if scope_context.next_block_number <= skip_after_block {
317                todo!()
318            }
319            // if skip_after_block is set and next_block_number is greater than skip_after_block + 1,
320            // we accidentally already received and handled blocks that should have been skipped.
321            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        // Case 2: if the block is the next expected block in the current section, put it into the
332        // section block queue and try to drain blocks from the cache
333        if block_number == scope_context.next_block_number {
334            // list of IncomingSections that is returned at the end
335            let mut new_blocks = vec![];
336
337            // initial values for loop variables from input block
338            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 over the input block and potential blocks from the cache until the next block cannot be found
344            // or the end of the scope is reached
345            loop {
346                if let Some(sender) = &mut scope_context.current_queue_sender {
347                    // send the next block to the section queue receiver
348                    sender.start_send(next_block).expect(
349                        "Failed to send block to current section queue",
350                    );
351                } else {
352                    // create a new block queue for the current section
353                    let (mut sender, receiver) = create_unbounded_channel();
354
355                    // add the first block to the queue
356                    new_blocks.push(IncomingSection::BlockStream((
357                        Some(receiver),
358                        IncomingEndpointContextSectionId::new(
359                            endpoint_context_id.clone(),
360                            section_index,
361                        ),
362                    )));
363
364                    // send the next block to the section queue receiver
365                    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                // cleanup / prepare for next block =======================
373                // increment next block number
374                scope_context.next_block_number += 1;
375
376                // if end of scope, remove the scope context
377                if is_end_of_context {
378                    request_scopes.remove(&endpoint_context_id);
379                    break;
380                }
381                // cleanup if section is finished
382                else if is_end_of_section {
383                    // increment section index
384                    scope_context.next_section_index += 1;
385                    // close and remove the current section queue sender
386                    if let Some(sender) =
387                        scope_context.current_queue_sender.take()
388                    {
389                        sender.close_channel();
390                    }
391                }
392                // ========================================================
393
394                // check if next block is in cache for next iteration
395                if let Some(next_cached_block) = scope_context
396                    .cached_blocks
397                    .remove(&scope_context.next_block_number)
398                {
399                    // check if block is end of section
400                    is_end_of_section = next_cached_block
401                        .block_header
402                        .flags_and_timestamp
403                        .is_end_of_section();
404                    // check if block is end of scope
405                    is_end_of_context = next_cached_block
406                        .block_header
407                        .flags_and_timestamp
408                        .is_end_of_context();
409                    // set next block
410                    next_block = next_cached_block;
411
412                    // update section index from next block
413                    section_index = next_block.block_header.section_index;
414                }
415                // no more blocks in cache, break
416                else {
417                    break;
418                }
419            }
420
421            new_blocks
422        }
423        // Case 3: if the block is not the next expected block in the current section,
424        // put it into the block cache
425        else {
426            // check if block is already in cache
427            // TODO #173: this should not happen, we should make sure duplicate blocks are dropped before
428            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            // add block to cache
435            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    /// Adds a new observer for incoming blocks with a specific scope id and block index
447    /// Returns a receiver that can be awaited to get the incoming sections
448    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        // create observer callback for scope id + block index
457        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        // TODO: are multiple observers allowed?
466        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        // add new scope observer
477        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    /// Waits for incoming response block with a specific scope id and block index
489    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        // Await the result from the callback
497        // FIXME #174
498        None
499        // rx.next().await
500    }
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        // Create a single DXB block
538        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        // Send incoming block to block handler
557        block_handler.handle_incoming_block(block);
558
559        // block must be in incoming_sections_receiver
560        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        // Create multiple DXB blocks for the same context and section
586        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        // 1. Send first block
627        block_handler.handle_incoming_block(blocks.next().unwrap());
628
629        info!("Checking incoming sections...");
630
631        // block must be in incoming_sections_queue
632        let mut section = incoming_sections_receiver.next().await.unwrap();
633        match &section {
634            IncomingSection::BlockStream((
635                Some(_),
636                incoming_context_section_id,
637            )) => {
638                // section must match
639                assert_eq!(
640                    incoming_context_section_id.section_index,
641                    section_index
642                );
643
644                // blocks queue must contain the first block
645                assert!(section.next().await.is_some());
646            }
647            _ => panic!("Expected a BlockStream section"),
648        }
649
650        // 2. Send second block
651        block_handler.handle_incoming_block(blocks.next().unwrap());
652
653        // no new incoming sections, old section receives new blocks
654        // block must be a block stream
655        match &section {
656            IncomingSection::BlockStream((
657                Some(_),
658                incoming_context_section_id,
659            )) => {
660                // section must match
661                assert_eq!(
662                    incoming_context_section_id.section_index,
663                    section_index
664                );
665                // blocks queue length must be 2 (was not yet drained)
666                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        // Create multiple DXB blocks for the same context and section in wrong order
686        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        // 1. Send first block
727        block_handler.handle_incoming_block(blocks.next().unwrap());
728
729        // 2. Send second block
730        block_handler.handle_incoming_block(blocks.next().unwrap());
731
732        // block must be in incoming_sections_queue
733        let mut section = incoming_sections_receiver.next().await.unwrap();
734        // block must be a block stream
735        match &section {
736            IncomingSection::BlockStream((
737                Some(_),
738                incoming_context_section_id,
739            )) => {
740                // section must match
741                assert_eq!(
742                    incoming_context_section_id.section_index.clone(),
743                    section_index
744                );
745                // blocks queue length must be 2
746                let blocks = section.drain().await;
747                assert_eq!(blocks.len(), 2);
748
749                // check order:
750                // first block must have block number 0
751                let block = blocks.first().unwrap();
752                assert_eq!(block.block_header.block_number, 0);
753                // second block must have block number 1
754                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        // Create multiple DXB blocks for two sections
776        let mut blocks = gen move {
777            // first section
778            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            // second section, end of context
817            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        // 1. Send first block
857        block_handler.handle_incoming_block(blocks.next().unwrap());
858
859        // block must be in incoming_sections_queue
860        let mut section = incoming_sections_receiver.next().await.unwrap();
861        // block must be a block stream
862        match &section {
863            IncomingSection::BlockStream((
864                Some(_),
865                incoming_context_section_id,
866            )) => {
867                // section must match
868                assert_eq!(
869                    incoming_context_section_id.section_index,
870                    section_index_1
871                );
872                // block queue must contain the first block
873                assert!(section.next().await.is_some());
874            }
875            _ => panic!("Expected a BlockStream section"),
876        }
877
878        // 2. Send second block
879        block_handler.handle_incoming_block(blocks.next().unwrap());
880
881        // block must be a block stream
882        match &section {
883            IncomingSection::BlockStream((
884                Some(_),
885                incoming_context_section_id,
886            )) => {
887                // section must match
888                assert_eq!(
889                    incoming_context_section_id.section_index,
890                    section_index_1
891                );
892
893                // blocks queue length must be 1
894                assert_eq!(section.drain().await.len(), 1);
895            }
896            _ => panic!("Expected a BlockStream section"),
897        }
898
899        // 3. Send third block
900        block_handler.handle_incoming_block(blocks.next().unwrap());
901
902        // block must be in incoming_sections_queue
903        let mut section = incoming_sections_receiver.next().await.unwrap();
904        // block must be a block stream
905        match &section {
906            IncomingSection::BlockStream((
907                Some(_),
908                incoming_context_section_id,
909            )) => {
910                // section must match
911                assert_eq!(
912                    incoming_context_section_id.section_index,
913                    section_index_2
914                );
915                // block queue must contain the first block
916                assert!(section.next().await.is_some());
917            }
918            _ => panic!("Expected a BlockStream section"),
919        }
920
921        // 4. Send fourth block
922        block_handler.handle_incoming_block(blocks.next().unwrap());
923
924        // block must not be in incoming_sections_queue
925        // block must be a block stream
926        match &section {
927            IncomingSection::BlockStream((
928                Some(_),
929                incoming_context_section_id,
930            )) => {
931                // section must match
932                assert_eq!(
933                    incoming_context_section_id.section_index,
934                    section_index_2
935                );
936                // blocks queue length must be 1
937                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        // Create a single DXB block
960        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        // set observer for the block
980        let mut rx = block_handler
981            .register_incoming_block_observer(context_id, section_index);
982
983        // Put into incoming queue of mock interface
984        block_handler.handle_incoming_block(block);
985
986        // await receiver
987        let response = rx.next().await.unwrap();
988
989        // IncomingSection must be a SingleBlock
990        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}