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
use std::{
    sync::Arc,
    task::{Context, Poll},
};

use futures::future::{self, Ready};
use tower::Service;

use crate::{
    state_machine::events::{DictionaryUpdate, EventListener, EventSubscriber},
    SumDict,
};

/// A service that returns the sum dictionary for the current round.
pub struct SumDictService(EventListener<DictionaryUpdate<SumDict>>);

/// [`SumDictService`]'s request type
pub struct SumDictRequest;

/// [`SumDictService`]'s response type.
///
/// The response is `None` when no sum dictionary is currently
/// available
pub type SumDictResponse = Option<Arc<SumDict>>;

impl SumDictService {
    pub fn new(events: &EventSubscriber) -> Self {
        Self(events.sum_dict_listener())
    }
}

impl Service<SumDictRequest> for SumDictService {
    type Response = SumDictResponse;
    type Error = std::convert::Infallible;
    type Future = Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _req: SumDictRequest) -> Self::Future {
        future::ready(match self.0.get_latest().event {
            DictionaryUpdate::Invalidate => Ok(None),
            DictionaryUpdate::New(dict) => Ok(Some(dict)),
        })
    }
}