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

const CHANNEL_CAPACITY: usize = 100;

/// Pause background requests if [ApiAvailabilityHandle::reset_inactivity_timer] hasn't been
/// called for this long.
const INACTIVITY_TIME: Duration = Duration::from_secs(3 * 24 * 60 * 60);

#[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,
    inactive: 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 || self.inactive
    }

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

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

    inactivity_timer: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
}

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

        let availability = ApiAvailability {
            state,
            tx,
            inactivity_timer: Arc::new(Mutex::new(None)),
        };
        availability.handle().reset_inactivity_timer();
        availability
    }

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

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

impl Drop for ApiAvailability {
    fn drop(&mut self) {
        if let Some(timer) = self.inactivity_timer.lock().unwrap().take() {
            timer.abort();
        }
    }
}

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

impl ApiAvailabilityHandle {
    /// Reset task that automatically pauses API requests due inactivity,
    /// starting it if it's not currently running.
    pub fn reset_inactivity_timer(&self) {
        log::trace!("Restarting API inactivity check");

        let self_ = self.clone();

        let mut inactivity_timer = self.inactivity_timer.lock().unwrap();
        if let Some(timer) = inactivity_timer.take() {
            timer.abort();
        }

        self.set_active();

        *inactivity_timer = Some(tokio::spawn(async move {
            talpid_time::sleep(INACTIVITY_TIME).await;
            self_.set_inactive();
        }));
    }

    /// Stops timer that pauses API requests due to inactivity.
    pub fn stop_inactivity_timer(&self) {
        log::trace!("Stopping API inactivity check");

        let mut inactivity_timer = self.inactivity_timer.lock().unwrap();
        if let Some(timer) = inactivity_timer.take() {
            timer.abort();
        }
        self.set_active();
    }

    fn inactivity_timer_running(&self) -> bool {
        self.inactivity_timer.lock().unwrap().is_some()
    }

    pub fn suspend(&self) {
        let mut state = self.state.lock().unwrap();
        if !state.suspended {
            log::debug!("Suspending API requests");

            state.suspended = true;
            let _ = self.tx.send(*state);
        }
    }

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

            state.suspended = false;
            let _ = self.tx.send(*state);
        }
    }

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

            state.pause_background = true;
            let _ = self.tx.send(*state);
        }
    }

    pub fn resume_background(&self) {
        if self.inactivity_timer_running() {
            self.reset_inactivity_timer();
        }

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

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

    fn set_active(&self) {
        let mut state = self.state.lock().unwrap();
        if state.inactive {
            log::debug!("Resuming background API requests due to activity");
            state.inactive = false;
            let _ = self.tx.send(*state);
        }
    }

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

            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(());
                }
            }
        }
    }
}