1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use std::{collections::HashMap, marker::PhantomData, ops::Deref, sync::Arc};

use futures::StreamExt;
use log::{debug, error, trace};
use sc_client_api::{Backend, FinalityNotification};
use sc_utils::mpsc::TracingUnboundedReceiver;
use sp_consensus_aura::AuraApi;
use sp_runtime::traits::{Block, Header};
use tokio::sync::{
    oneshot::{Receiver as OneShotReceiver, Sender as OneShotSender},
    RwLock,
};

use crate::{
    phron_primitives::{PhronSessionApi, AuraId, BlockHash, BlockNumber, SessionAuthorityData},
    runtime_api::RuntimeApi,
    session::SessionBoundaryInfo,
    ClientForPhron, SessionId, SessionPeriod,
};
const PRUNING_THRESHOLD: u32 = 10;
const LOG_TARGET: &str = "aleph-session-updater";
type SessionMap = HashMap<SessionId, SessionAuthorityData>;
type SessionSubscribers = HashMap<SessionId, Vec<OneShotSender<SessionAuthorityData>>>;

pub trait AuthorityProvider {
    /// returns authority data for block
    fn authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData>;
    /// returns next session authority data where current session is for block
    fn next_authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData>;
    /// returns list of Aura authorities for a given block number
    fn aura_authorities(&self, block_number: BlockNumber) -> Option<Vec<AuraId>>;
    /// returns list of next session Aura authorities for a given block number
    fn next_aura_authorities(&self, block_number: BlockNumber) -> Option<Vec<AuraId>>;
}

/// Default implementation of authority provider trait.
/// If state pruning is on and set to `n`, will no longer be able to
/// answer for `num < finalized_number - n`.
pub struct AuthorityProviderImpl<C, B, BE, RA>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: crate::phron_primitives::PhronSessionApi<B> + AuraApi<B, AuraId>,
    B: Block<Hash = BlockHash>,
    BE: Backend<B> + 'static,
    RA: RuntimeApi,
{
    client: Arc<C>,
    api: RA,
    _phantom: PhantomData<(B, BE)>,
}

impl<C, B, BE, RA> AuthorityProviderImpl<C, B, BE, RA>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: crate::phron_primitives::PhronSessionApi<B> + AuraApi<B, AuraId>,
    B: Block<Hash = BlockHash>,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B> + 'static,
    RA: RuntimeApi,
{
    pub fn new(client: Arc<C>, api: RA) -> Self {
        Self {
            client,
            api,
            _phantom: PhantomData,
        }
    }

    fn block_hash(&self, block: BlockNumber) -> Option<BlockHash> {
        match self.client.block_hash(block) {
            Ok(r) => r,
            Err(e) => {
                error!(
                    target: LOG_TARGET,
                    "Error while retrieving hash for block #{}. {}", block, e
                );
                None
            }
        }
    }
}

impl<C, B, BE, RA> AuthorityProvider for AuthorityProviderImpl<C, B, BE, RA>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: PhronSessionApi<B> + AuraApi<B, AuraId>,
    B: Block<Hash = BlockHash>,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B> + 'static,
    RA: RuntimeApi,
{
    fn aura_authorities(&self, block_number: BlockNumber) -> Option<Vec<AuraId>> {
        AuraApi::authorities(
            self.client.runtime_api().deref(),
            self.block_hash(block_number)?,
        )
        .ok()
    }

    fn next_aura_authorities(&self, block_number: BlockNumber) -> Option<Vec<AuraId>> {
        self.api
            .next_aura_authorities(self.block_hash(block_number)?)
            .ok()
    }

    fn authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData> {
        let block_hash = self.block_hash(block_number)?;
        match self.client.runtime_api().authority_data(block_hash) {
            Ok(data) => Some(data),
            Err(_) => PhronSessionApi::authorities(self.client.runtime_api().deref(), block_hash)
                .map(|authorities| SessionAuthorityData::new(authorities, None))
                .ok(),
        }
    }

    fn next_authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData> {
        let block_hash = self.block_hash(block_number)?;
        match self
            .client
            .runtime_api()
            .next_session_authority_data(block_hash)
            .map(|r| r.ok())
        {
            Ok(maybe_data) => maybe_data,
            Err(_) => self
                .client
                .runtime_api()
                .next_session_authorities(block_hash)
                .map(|r| {
                    r.map(|authorities| SessionAuthorityData::new(authorities, None))
                        .ok()
                })
                .ok()
                .flatten(),
        }
    }
}

#[async_trait::async_trait]
pub trait FinalityNotifier {
    async fn next(&mut self) -> Option<BlockNumber>;
    fn last_finalized(&self) -> BlockNumber;
}

/// Default implementation of finality notificator trait.
pub struct FinalityNotifierImpl<C, B, BE>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: crate::phron_primitives::PhronSessionApi<B>,
    B: Block,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B> + 'static,
{
    notification_stream: TracingUnboundedReceiver<FinalityNotification<B>>,
    client: Arc<C>,
    _phantom: PhantomData<(B, BE)>,
}

impl<C, B, BE> FinalityNotifierImpl<C, B, BE>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: crate::phron_primitives::PhronSessionApi<B>,
    B: Block,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B> + 'static,
{
    pub fn new(client: Arc<C>) -> Self {
        Self {
            notification_stream: client.finality_notification_stream(),
            client,
            _phantom: PhantomData,
        }
    }
}

#[async_trait::async_trait]
impl<C, B, BE> FinalityNotifier for FinalityNotifierImpl<C, B, BE>
where
    C: ClientForPhron<B, BE> + Send + Sync + 'static,
    C::Api: crate::phron_primitives::PhronSessionApi<B>,
    B: Block,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B> + 'static,
{
    async fn next(&mut self) -> Option<BlockNumber> {
        self.notification_stream
            .next()
            .await
            .map(|block| *block.header.number())
    }

    fn last_finalized(&self) -> BlockNumber {
        self.client.info().finalized_number
    }
}

#[derive(Clone, Debug)]
/// Wrapper around Mapping from sessionId to Vec of AuthorityIds allowing mutation
/// and hiding locking details
pub struct SharedSessionMap(Arc<RwLock<(SessionMap, SessionSubscribers)>>);

#[derive(Clone)]
/// Wrapper around Mapping from sessionId to Vec of AuthorityIds allowing only reads
pub struct ReadOnlySessionMap {
    inner: Arc<RwLock<(SessionMap, SessionSubscribers)>>,
}

impl SharedSessionMap {
    pub fn new() -> Self {
        Self(Arc::new(RwLock::new((HashMap::new(), HashMap::new()))))
    }

    pub async fn update(
        &mut self,
        id: SessionId,
        authority_data: SessionAuthorityData,
    ) -> Option<SessionAuthorityData> {
        let mut guard = self.0.write().await;

        // notify all subscribers about insertion and remove them from subscription
        if let Some(senders) = guard.1.remove(&id) {
            for sender in senders {
                if let Err(e) = sender.send(authority_data.clone()) {
                    error!(
                        target: LOG_TARGET,
                        "Error while sending notification: {:?}", e
                    );
                }
            }
        }

        guard.0.insert(id, authority_data)
    }

    async fn prune_below(&mut self, id: SessionId) {
        let mut guard = self.0.write().await;

        guard.0.retain(|&s, _| s >= id);
        guard.1.retain(|&s, _| s >= id);
    }

    pub fn read_only(&self) -> ReadOnlySessionMap {
        ReadOnlySessionMap {
            inner: self.0.clone(),
        }
    }
}

impl ReadOnlySessionMap {
    /// returns an end of the oneshot channel that fires a message if either authority data is already
    /// known for the session with id = `id` or when the data is inserted for this session.
    pub async fn subscribe_to_insertion(
        &self,
        id: SessionId,
    ) -> OneShotReceiver<SessionAuthorityData> {
        let (sender, receiver) = tokio::sync::oneshot::channel();

        let mut guard = self.inner.write().await;

        if let Some(authority_data) = guard.0.get(&id) {
            // if the value is already present notify immediately
            sender
                .send(authority_data.clone())
                .expect("we control both ends");
        } else {
            guard.1.entry(id).or_insert_with(Vec::new).push(sender);
        }

        receiver
    }
}

/// Struct responsible for updating session map
pub struct SessionMapUpdater<AP, FN>
where
    AP: AuthorityProvider,
    FN: FinalityNotifier,
{
    session_map: SharedSessionMap,
    authority_provider: AP,
    finality_notifier: FN,
    session_info: SessionBoundaryInfo,
}

impl<AP, FN> SessionMapUpdater<AP, FN>
where
    AP: AuthorityProvider,
    FN: FinalityNotifier,
{
    pub fn new(authority_provider: AP, finality_notifier: FN, period: SessionPeriod) -> Self {
        Self {
            session_map: SharedSessionMap::new(),
            authority_provider,
            finality_notifier,
            session_info: SessionBoundaryInfo::new(period),
        }
    }

    /// returns readonly view of the session map
    pub fn readonly_session_map(&self) -> ReadOnlySessionMap {
        self.session_map.read_only()
    }

    /// Puts authority data for the next session into the session map
    async fn handle_first_block_of_session(&mut self, session_id: SessionId) {
        let first_block = self.session_info.first_block_of_session(session_id);
        debug!(
            target: LOG_TARGET,
            "Handling first block #{:?} of session {:?}", first_block, session_id.0
        );

        if let Some(authority_data) = self.authority_provider.next_authority_data(first_block) {
            self.session_map
                .update(SessionId(session_id.0 + 1), authority_data)
                .await;
        } else {
            panic!("Authorities for next session {:?} must be available at first block #{:?} of current session", session_id.0, first_block);
        }

        if session_id.0 > PRUNING_THRESHOLD && session_id.0 % PRUNING_THRESHOLD == 0 {
            debug!(
                target: LOG_TARGET,
                "Pruning session map below session #{:?}",
                session_id.0 - PRUNING_THRESHOLD
            );
            self.session_map
                .prune_below(SessionId(session_id.0 - PRUNING_THRESHOLD))
                .await;
        }
    }

    fn authorities_for_session(&mut self, session_id: SessionId) -> Option<SessionAuthorityData> {
        let first_block = self.session_info.first_block_of_session(session_id);
        self.authority_provider.authority_data(first_block)
    }

    /// Puts current and next session authorities in the session map.
    /// If previous authorities are still available in `AuthorityProvider`, also puts them in the session map.
    async fn catch_up(&mut self) -> SessionId {
        let last_finalized = self.finality_notifier.last_finalized();

        let current_session = self.session_info.session_id_from_block_num(last_finalized);
        let starting_session = SessionId(current_session.0.saturating_sub(PRUNING_THRESHOLD - 1));

        debug!(target: LOG_TARGET,
            "Last finalized is {:?}; Catching up with authorities starting from session {:?} up to next session {:?}",
            last_finalized, starting_session.0, current_session.0 + 1
        );

        // lets catch up with previous sessions
        for session in starting_session.0..current_session.0 {
            let id = SessionId(session);
            if let Some(authority_data) = self.authorities_for_session(id) {
                self.session_map.update(id, authority_data).await;
            } else {
                debug!(
                    target: LOG_TARGET,
                    "No authorities for session {:?} during catch-up. Most likely already pruned.",
                    id.0
                )
            }
        }

        // lets catch up with previous session
        match self.authorities_for_session(current_session) {
            Some(current_authority_data) => {
                self.session_map
                    .update(current_session, current_authority_data)
                    .await
            }
            None => panic!(
                "Authorities for current session {:?} must be available from the beginning",
                current_session.0
            ),
        };

        self.handle_first_block_of_session(current_session).await;

        current_session
    }

    pub async fn run(mut self) {
        let mut last_updated = self.catch_up().await;

        while let Some(last_finalized) = self.finality_notifier.next().await {
            trace!(
                target: LOG_TARGET,
                "got FinalityNotification about #{:?}",
                last_finalized
            );

            let session_id = self.session_info.session_id_from_block_num(last_finalized);

            if last_updated >= session_id {
                continue;
            }

            for session in (last_updated.0 + 1)..=session_id.0 {
                self.handle_first_block_of_session(SessionId(session)).await;
            }

            last_updated = session_id;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use futures_timer::Delay;
    use sc_utils::mpsc::tracing_unbounded;
    use tokio::sync::oneshot::error::TryRecvError;

    use super::*;
    use crate::{phron_primitives::BlockNumber, session::testing::authority_data};

    const FIRST_THRESHOLD: u32 = PRUNING_THRESHOLD + 1;
    const SECOND_THRESHOLD: u32 = 2 * PRUNING_THRESHOLD + 1;

    impl ReadOnlySessionMap {
        async fn get(&self, id: SessionId) -> Option<SessionAuthorityData> {
            self.inner.read().await.0.get(&id).cloned()
        }
    }

    struct MockProvider {
        pub session_map: HashMap<BlockNumber, SessionAuthorityData>,
        pub next_session_map: HashMap<BlockNumber, SessionAuthorityData>,
    }

    impl MockProvider {
        fn new() -> Self {
            Self {
                session_map: HashMap::new(),
                next_session_map: HashMap::new(),
            }
        }

        fn add_session(&mut self, session_id: BlockNumber) {
            self.session_map
                .insert(session_id, authority_data_for_session(session_id));
            self.next_session_map
                .insert(session_id, authority_data_for_session(session_id + 1));
        }
    }
    impl AuthorityProvider for MockProvider {
        fn authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData> {
            self.session_map.get(&block_number).cloned()
        }

        fn next_authority_data(&self, block_number: BlockNumber) -> Option<SessionAuthorityData> {
            self.next_session_map.get(&block_number).cloned()
        }

        fn aura_authorities(&self, _block_number: BlockNumber) -> Option<Vec<AuraId>> {
            None
        }

        fn next_aura_authorities(&self, _block_number: BlockNumber) -> Option<Vec<AuraId>> {
            None
        }
    }

    struct MockNotifier {
        pub last_finalized: BlockNumber,
        pub receiver: TracingUnboundedReceiver<BlockNumber>,
    }

    impl MockNotifier {
        fn new(receiver: TracingUnboundedReceiver<BlockNumber>) -> Self {
            Self {
                receiver,
                last_finalized: 0,
            }
        }
    }

    #[async_trait::async_trait]
    impl FinalityNotifier for MockNotifier {
        async fn next(&mut self) -> Option<BlockNumber> {
            self.receiver.next().await
        }

        fn last_finalized(&self) -> BlockNumber {
            self.last_finalized
        }
    }

    fn authority_data_for_session(session_id: u32) -> SessionAuthorityData {
        authority_data(session_id * 4, (session_id + 1) * 4)
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn genesis_catch_up() {
        let (_sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mock_notifier = MockNotifier::new(receiver);

        mock_provider.add_session(0);

        let updater = SessionMapUpdater::new(mock_provider, mock_notifier, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        let _handle = tokio::spawn(updater.run());

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        assert_eq!(
            session_map.get(SessionId(0)).await,
            Some(authority_data(0, 4))
        );
        assert_eq!(
            session_map.get(SessionId(1)).await,
            Some(authority_data(4, 8))
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn updates_session_map_on_notifications() {
        let (sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mock_notificator = MockNotifier::new(receiver);

        mock_provider.add_session(0);
        mock_provider.add_session(1);
        mock_provider.add_session(2);

        let updater = SessionMapUpdater::new(mock_provider, mock_notificator, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        for n in 1..3 {
            sender.unbounded_send(n).unwrap();
        }

        let _handle = tokio::spawn(updater.run());

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        assert_eq!(
            session_map.get(SessionId(0)).await,
            Some(authority_data(0, 4))
        );
        assert_eq!(
            session_map.get(SessionId(1)).await,
            Some(authority_data(4, 8))
        );
        assert_eq!(
            session_map.get(SessionId(2)).await,
            Some(authority_data(8, 12))
        );
        assert_eq!(
            session_map.get(SessionId(3)).await,
            Some(authority_data(12, 16))
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn catch_up() {
        let (_sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mut mock_notificator = MockNotifier::new(receiver);

        mock_provider.add_session(0);
        mock_provider.add_session(1);
        mock_provider.add_session(2);

        mock_notificator.last_finalized = 2;

        let updater = SessionMapUpdater::new(mock_provider, mock_notificator, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        let _handle = tokio::spawn(updater.run());

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        assert_eq!(
            session_map.get(SessionId(0)).await,
            Some(authority_data_for_session(0))
        );
        assert_eq!(
            session_map.get(SessionId(1)).await,
            Some(authority_data_for_session(1))
        );
        assert_eq!(
            session_map.get(SessionId(2)).await,
            Some(authority_data_for_session(2))
        );
        assert_eq!(
            session_map.get(SessionId(3)).await,
            Some(authority_data_for_session(3))
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn catch_up_old_sessions() {
        let (_sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mut mock_notificator = MockNotifier::new(receiver);

        for i in 0..SECOND_THRESHOLD {
            mock_provider.add_session(i);
        }

        mock_notificator.last_finalized = 20;

        let updater = SessionMapUpdater::new(mock_provider, mock_notificator, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        let _handle = tokio::spawn(updater.run());

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        for i in 0..FIRST_THRESHOLD {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                None,
                "Session {i:?} should be pruned"
            );
        }
        for i in FIRST_THRESHOLD..SECOND_THRESHOLD {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                Some(authority_data_for_session(i)),
                "Session {i:?} should not be pruned"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn deals_with_database_pruned_authorities() {
        let (_sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mut mock_notificator = MockNotifier::new(receiver);

        mock_provider.add_session(5);
        mock_notificator.last_finalized = 5;

        let updater = SessionMapUpdater::new(mock_provider, mock_notificator, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        let _handle = tokio::spawn(updater.run());

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        for i in 0..5 {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                None,
                "Session {i:?} should not be available"
            );
        }

        assert_eq!(
            session_map.get(SessionId(5)).await,
            Some(authority_data_for_session(5))
        );
        assert_eq!(
            session_map.get(SessionId(6)).await,
            Some(authority_data_for_session(6))
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn prunes_old_sessions() {
        let (sender, receiver) = tracing_unbounded("test", 1_000);
        let mut mock_provider = MockProvider::new();
        let mock_notificator = MockNotifier::new(receiver);

        for i in 0..SECOND_THRESHOLD {
            mock_provider.add_session(i);
        }

        let updater = SessionMapUpdater::new(mock_provider, mock_notificator, SessionPeriod(1));
        let session_map = updater.readonly_session_map();

        let _handle = tokio::spawn(updater.run());

        for n in 1..FIRST_THRESHOLD {
            sender.unbounded_send(n).unwrap();
        }

        // wait a bit
        Delay::new(Duration::from_millis(50)).await;

        for i in 0..=FIRST_THRESHOLD {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                Some(authority_data_for_session(i)),
                "Session {i:?} should be available"
            );
        }

        for i in (FIRST_THRESHOLD + 1)..=SECOND_THRESHOLD {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                None,
                "Session {i:?} should not be avalable yet"
            );
        }

        for n in FIRST_THRESHOLD..SECOND_THRESHOLD {
            sender.unbounded_send(n).unwrap();
        }

        Delay::new(Duration::from_millis(50)).await;

        for i in 0..(FIRST_THRESHOLD - 1) {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                None,
                "Session {i:?} should be pruned"
            );
        }

        for i in FIRST_THRESHOLD..=SECOND_THRESHOLD {
            assert_eq!(
                session_map.get(SessionId(i)).await,
                Some(authority_data_for_session(i)),
                "Session {i:?} should be avalable"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn subscription_with_already_defined_session_works() {
        let mut shared = SharedSessionMap::new();
        let readonly = shared.read_only();
        let session = SessionId(0);

        shared.update(session, authority_data(0, 2)).await;

        let mut receiver = readonly.subscribe_to_insertion(session).await;

        // we should have this immediately
        assert_eq!(Ok(authority_data(0, 2)), receiver.try_recv());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn notifies_on_insertion() {
        let mut shared = SharedSessionMap::new();
        let readonly = shared.read_only();
        let session = SessionId(0);
        let mut receiver = readonly.subscribe_to_insertion(session).await;

        // does not yet have any value
        assert_eq!(Err(TryRecvError::Empty), receiver.try_recv());
        shared.update(session, authority_data(0, 2)).await;
        assert_eq!(Ok(authority_data(0, 2)), receiver.await);
    }
}