Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix API request timer regression #6872

Merged
merged 3 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mullvad-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ talpid-time = { path = "../talpid-time" }

shadowsocks = { workspace = true, features = [ "stream-cipher" ] }

[dev-dependencies]
talpid-time = { path = "../talpid-time", features = ["test"] }
tokio = { workspace = true, features = ["test-util", "time"] }

[build-dependencies]
cbindgen = { version = "0.24.3", default-features = false }

Expand Down
70 changes: 60 additions & 10 deletions mullvad-api/src/availability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ pub enum Error {
Interrupted(#[from] broadcast::error::RecvError),
}

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

#[derive(Clone, Debug)]
pub struct ApiAvailability(Arc<Mutex<ApiAvailabilityState>>);

Expand All @@ -34,6 +26,14 @@ struct ApiAvailabilityState {
inactivity_timer: Option<tokio::task::JoinHandle<()>>,
}

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

impl State {
pub const fn is_suspended(&self) -> bool {
self.suspended
Expand Down Expand Up @@ -71,7 +71,7 @@ impl ApiAvailability {
/// Reset task that automatically pauses API requests due inactivity,
/// starting it if it's not currently running.
pub fn reset_inactivity_timer(&self) {
let mut inner = self.0.lock().unwrap();
let mut inner = self.acquire();
log::debug!("Restarting API inactivity check");
inner.stop_inactivity_timer();
let availability_handle = self.clone();
Expand All @@ -94,7 +94,7 @@ impl ApiAvailability {
pub fn resume_background(&self) {
let should_reset = {
let mut inner = self.acquire();
inner.pause_background();
inner.resume_background();
inner.inactivity_timer_running()
};
// Note: It is important that we do not hold on to the Mutex when calling `reset_inactivity_timer()`.
Expand Down Expand Up @@ -179,6 +179,12 @@ impl ApiAvailability {
}
}

impl Default for ApiAvailability {
fn default() -> Self {
ApiAvailability::new(State::default())
}
}

impl ApiAvailabilityState {
fn suspend(&mut self) {
if !self.state.suspended {
Expand Down Expand Up @@ -237,6 +243,14 @@ impl ApiAvailabilityState {
}
}

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

fn stop_inactivity_timer(&mut self) {
log::debug!("Stopping API inactivity check");
if let Some(timer) = self.inactivity_timer.take() {
Expand All @@ -254,3 +268,39 @@ impl Drop for ApiAvailabilityState {
self.stop_inactivity_timer();
}
}

#[cfg(test)]
mod test {
use super::*;
/// Use mockable time for tests
pub use tokio::time::Duration;

// Note that all of these tests needs a tokio runtime. Creating an instance of [`ApiAvailability`] will implicitly
// spawn a tokio task.

/// Test that the inactivity timer starts in an expected state.
#[tokio::test(start_paused = true)]
async fn test_initially_active() {
// Start a new timer. It should *not* start as paused.
let timer = ApiAvailability::default();
assert!(
!timer.get_state().is_background_paused(),
"Inactivity timer should be active"
)
}

/// Test that the inactivity timer kicks in after [`INACTIVITY_TIME`] of inactivity.
#[tokio::test(start_paused = true)]
async fn test_inactivity() {
// Start a new timer. It should be marked as 'active'.
let timer = ApiAvailability::default();
// Elapse INACTIVITY_TIME (+ some slack because clocks)
const SLACK: Duration = Duration::from_secs(1);
talpid_time::sleep(INACTIVITY_TIME + SLACK).await;
// Check that the timer is now marked as 'inactive'
assert!(
timer.get_state().is_background_paused(),
"Inactivity timer should be inactive because 'INACTIVITY_TIME' has passed"
)
}
}
8 changes: 5 additions & 3 deletions mullvad-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ impl Runtime {
Runtime {
handle,
address_cache: AddressCache::with_static_addr(address),
api_availability: ApiAvailability::new(availability::State::default()),
api_availability: ApiAvailability::default(),
}
}

Expand All @@ -351,7 +351,7 @@ impl Runtime {
Ok(Runtime {
handle,
address_cache: AddressCache::new(None)?,
api_availability: ApiAvailability::new(availability::State::default()),
api_availability: ApiAvailability::default(),
#[cfg(target_os = "android")]
socket_bypass_tx,
})
Expand Down Expand Up @@ -396,10 +396,12 @@ impl Runtime {
}
};

let api_availability = ApiAvailability::default();

Ok(Runtime {
handle,
address_cache,
api_availability: ApiAvailability::new(availability::State::default()),
api_availability,
#[cfg(target_os = "android")]
socket_bypass_tx,
})
Expand Down
Loading