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
use tokio::time::Instant;

use super::{DataCommitRequest, DataLoadRequest};

pub trait LoadFromUpstream<Key: Send, Data: ServiceData>: Send + 'static {
    fn load(&mut self, request: DataLoadRequest<'_, Key, Data>);
}

pub trait CommitToUpstream<Key: Send, Data: ServiceData>: Send + 'static {
    fn commit(&mut self, request: DataCommitRequest<'_, Key, Data>);
}

pub trait UpstreamFactory<Key: Send, Data: ServiceData> {
    type Upstream: LoadFromUpstream<Key, Data>;

    fn create(&mut self) -> Self::Upstream;
}

impl<Key: Send, Data: ServiceData, T: Clone + LoadFromUpstream<Key, Data>>
    UpstreamFactory<Key, Data> for T
{
    type Upstream = Self;

    fn create(&mut self) -> Self::Upstream {
        self.clone()
    }
}

pub trait MutableUpstreamFactory<Key: Send, Data: ServiceData> {
    type Upstream: LoadFromUpstream<Key, Data> + CommitToUpstream<Key, Data>;

    fn create(&mut self) -> Self::Upstream;
}

impl<
        Key: Send,
        Data: ServiceData,
        T: Clone + LoadFromUpstream<Key, Data> + CommitToUpstream<Key, Data>,
    > MutableUpstreamFactory<Key, Data> for T
{
    type Upstream = Self;

    fn create(&mut self) -> Self::Upstream {
        self.clone()
    }
}

/// Marks data that can be managed through thingvellir.
pub trait ServiceData: Send + 'static {
    /// Hint to signal if data should be sent to a [CommitToUpstream].
    /// Return `false` if the data should be returned but not upstreamed.
    /// Defaults to `true`
    fn should_persist(&self) -> bool {
        true
    }

    /// Indicates when the data is considered stale and should be evicted from the cache.
    /// `None` indicates that the data should live forever.
    fn get_expires_at(&self) -> Option<&Instant> {
        None
    }
}

impl<T: ServiceData> ServiceData for Option<T> {
    fn should_persist(&self) -> bool {
        self.is_some()
    }

    fn get_expires_at(&self) -> Option<&Instant> {
        self.as_ref().and_then(|x| x.get_expires_at())
    }
}