summaryrefslogtreecommitdiffhomepage
path: root/mullvad-api/src/availability.rs
blob: 2cf40cf53b39577fa9da8f49246abafa259d5624 (plain)
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
use std::{
    future::Future,
    sync::{Arc, Mutex},
};
use tokio::sync::broadcast;

const CHANNEL_CAPACITY: usize = 100;

#[derive(err_derive::Error, Debug)]
pub enum Error {
    /// The [`ApiAvailability`] instance was dropped, or the receiver lagged behind.
    #[error(display = "API availability instance was dropped")]
    Interrupted(#[error(source)] broadcast::error::RecvError),
}

#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
pub struct State {
    suspended: bool,
    pause_background: bool,
    offline: bool,
}

impl State {
    pub fn is_suspended(&self) -> bool {
        self.suspended
    }

    pub fn is_background_paused(&self) -> bool {
        self.offline || self.pause_background || self.suspended
    }

    pub fn is_offline(&self) -> bool {
        self.offline
    }
}

pub struct ApiAvailability {
    state: Arc<Mutex<State>>,
    tx: broadcast::Sender<State>,
}

impl ApiAvailability {
    pub fn new(initial_state: State) -> Self {
        let (tx, _rx) = broadcast::channel(CHANNEL_CAPACITY);
        let state = Arc::new(Mutex::new(initial_state));
        ApiAvailability { state, tx }
    }

    pub fn get_state(&self) -> State {
        *self.state.lock().unwrap()
    }

    pub fn handle(&self) -> ApiAvailabilityHandle {
        ApiAvailabilityHandle {
            state: self.state.clone(),
            tx: self.tx.clone(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct ApiAvailabilityHandle {
    state: Arc<Mutex<State>>,
    tx: broadcast::Sender<State>,
}

impl ApiAvailabilityHandle {
    pub fn suspend(&self) {
        log::debug!("Suspending API requests");
        let mut state = self.state.lock().unwrap();
        if !state.suspended {
            state.suspended = true;
            let _ = self.tx.send(*state);
        }
    }

    pub fn unsuspend(&self) {
        log::debug!("Unsuspending API requests");
        let mut state = self.state.lock().unwrap();
        if state.suspended {
            state.suspended = false;
            let _ = self.tx.send(*state);
        }
    }

    pub fn pause_background(&self) {
        log::debug!("Pausing background API requests");
        let mut state = self.state.lock().unwrap();
        if !state.pause_background {
            state.pause_background = true;
            let _ = self.tx.send(*state);
        }
    }

    pub fn resume_background(&self) {
        log::debug!("Resuming background API requests");
        let mut state = self.state.lock().unwrap();
        if state.pause_background {
            state.pause_background = false;
            let _ = self.tx.send(*state);
        }
    }

    pub fn set_offline(&self, offline: bool) {
        if offline {
            log::debug!("Pausing API requests due to being offline");
        } else {
            log::debug!("Resuming API requests due to coming online");
        }
        let mut state = self.state.lock().unwrap();
        if state.offline != offline {
            state.offline = offline;
            let _ = self.tx.send(*state);
        }
    }

    pub fn get_state(&self) -> State {
        *self.state.lock().unwrap()
    }

    pub fn wait_for_unsuspend(&self) -> impl Future<Output = Result<(), Error>> {
        self.wait_for_state(|state| !state.is_suspended())
    }

    pub fn when_bg_resumes<F: Future<Output = O>, O>(&self, task: F) -> impl Future<Output = O> {
        let wait_task = self.wait_for_state(|state| !state.is_background_paused());
        async move {
            let _ = wait_task.await;
            task.await
        }
    }

    pub fn wait_background(&self) -> impl Future<Output = Result<(), Error>> {
        self.wait_for_state(|state| !state.is_background_paused())
    }

    pub fn when_online<F: Future<Output = O>, O>(&self, task: F) -> impl Future<Output = O> {
        let wait_task = self.wait_for_state(|state| !state.is_offline());
        async move {
            let _ = wait_task.await;
            task.await
        }
    }

    pub fn wait_online(&self) -> impl Future<Output = Result<(), Error>> {
        self.wait_for_state(|state| !state.is_offline())
    }

    fn wait_for_state(
        &self,
        state_ready: impl Fn(State) -> bool,
    ) -> impl Future<Output = Result<(), Error>> {
        let mut rx = self.tx.subscribe();
        let state = self.state.clone();

        async move {
            let current_state = { *state.lock().unwrap() };
            if state_ready(current_state) {
                return Ok(());
            }

            loop {
                let new_state = rx.recv().await?;
                if state_ready(new_state) {
                    return Ok(());
                }
            }
        }
    }
}