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

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

use crate::{
    mask::model::Model,
    state_machine::events::{EventListener, EventSubscriber, ModelUpdate},
};

/// [`ModelService`]'s request type
pub struct ModelRequest;

/// [`ModelService`]'s response type.
///
/// The response is `None` when no model is currently available.
pub type ModelResponse = Option<Arc<Model>>;

/// A service that serves the latest available global model
pub struct ModelService(EventListener<ModelUpdate>);

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

impl Service<ModelRequest> for ModelService {
    type Response = ModelResponse;
    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: ModelRequest) -> Self::Future {
        future::ready(match self.0.get_latest().event {
            ModelUpdate::Invalidate => Ok(None),
            ModelUpdate::New(model) => Ok(Some(model)),
        })
    }
}