Skip to main content

rightkit_context/
activation.rs

1//! The activation lock.
2//!
3//! The host app's installer and updater own install, update and removal of this binary,
4//! its plugins and its hooks. What stays here is the lock that serializes
5//! anything mutating the state root.
6
7use std::{path::Path, time::Duration};
8
9const LOCK_WAIT: Duration = Duration::from_secs(15);
10const POLL_INTERVAL: Duration = Duration::from_millis(250);
11
12/// Held for as long as the caller mutates the state root. The kernel-backed guard is released by
13/// the OS on drop or crash, so a killed activation never leaves the state root locked.
14pub struct ActivationLock {
15    _guard: rightkit_fs::lock::FileLock,
16}
17
18/// Take the activation lock under `state_root`, waiting up to 15 s.
19pub fn acquire_lock(state_root: &Path) -> Result<ActivationLock, String> {
20    acquire_lock_with_wait(state_root, LOCK_WAIT)
21}
22
23fn acquire_lock_with_wait(root: &Path, wait: Duration) -> Result<ActivationLock, String> {
24    let guard_path = root.join(".activation.guard");
25    let guard_options = rightkit_fs::lock::LockOptions {
26        timeout: wait,
27        poll: POLL_INTERVAL,
28        label: "activation".to_string(),
29    };
30    let guard =
31        rightkit_fs::lock::FileLock::acquire(&guard_path, &guard_options).map_err(|error| {
32            match error {
33                rightkit_fs::FsError::Locked { .. } | rightkit_fs::FsError::LockTimeout { .. } => {
34                    "activation startup lock remained busy".to_string()
35                }
36                other => format!("open activation guard: {other}"),
37            }
38        })?;
39    Ok(ActivationLock { _guard: guard })
40}