Skip to main content

mnemo_engine/shared/
call.rs

1//! One shared-mode call's deadline and cancellation (12.4 design note, "The
2//! protocol"): every wait in a call counts against one deadline, and another
3//! thread can cancel the call while it waits.
4
5use std::sync::{Arc, Condvar, Mutex};
6use std::time::{Duration, Instant};
7
8use crate::error::{MnemoError, Result};
9
10/// Cancels a shared-mode call that is waiting for the file's lock, from
11/// another thread: an iOS background activity's expiry handler, say. The
12/// call releases every lock it holds and returns [`MnemoError::Cancelled`].
13///
14/// A cancel reaches only a call that is **waiting** for a lock. Once a call
15/// holds the lock it runs to its end, so a write is never cut off part-way.
16///
17/// Clones share one flag. A cancelled token stays cancelled: give the handle
18/// a new one for its next calls (`SharedMnemo::set_cancel`).
19#[derive(Clone, Debug, Default)]
20pub struct CancelToken(Arc<(Mutex<bool>, Condvar)>);
21
22impl CancelToken {
23    /// A token that hasn't been cancelled.
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    /// Cancel every call waiting on this token, now and later.
29    pub fn cancel(&self) {
30        let (flag, wake) = &*self.0;
31        *flag.lock().unwrap_or_else(|e| e.into_inner()) = true;
32        wake.notify_all();
33    }
34
35    /// Whether [`CancelToken::cancel`] has been called.
36    pub fn is_cancelled(&self) -> bool {
37        *self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
38    }
39
40    /// Sleep for `d`, or less if the token is cancelled meanwhile. Returns
41    /// whether it was cancelled.
42    fn sleep(&self, d: Duration) -> bool {
43        let (flag, wake) = &*self.0;
44        let guard = flag.lock().unwrap_or_else(|e| e.into_inner());
45        if *guard {
46            return true;
47        }
48        let (guard, _) = wake
49            .wait_timeout_while(guard, d, |cancelled| !*cancelled)
50            .unwrap_or_else(|e| e.into_inner());
51        *guard
52    }
53}
54
55/// One call's deadline, its cancel token, and the backoff between tries.
56pub(crate) struct Call {
57    started: Instant,
58    deadline: Instant,
59    cancel: Option<CancelToken>,
60    sleep: Duration,
61    /// Whether this call has already reopened the sidecar directory once
62    /// (RB-007.7).
63    pub(crate) sidecar_reopened: bool,
64}
65
66/// The backoff's first and longest sleep. Step 5's bench tunes them (the
67/// design note: shorter sleeps while a wait is young).
68const FIRST_SLEEP: Duration = Duration::from_millis(1);
69const LONGEST_SLEEP: Duration = Duration::from_millis(50);
70
71/// Step 5's alternative shape ("short sleeps while a wait is young"): 1 to
72/// 2 ms sleeps for the first `YOUNG_FOR` of a wait, then doubling from
73/// `YOUNG_THEN`. Selected for benchmarking only, through
74/// `MNEMO_DEV_BACKOFF=young` in a `dev-hooks` build.
75const YOUNG_FOR: Duration = Duration::from_millis(15);
76const YOUNG_THEN: Duration = Duration::from_millis(2);
77
78#[derive(Clone, Copy, PartialEq, Eq)]
79enum Shape {
80    Doubling,
81    Young,
82}
83
84#[cfg(feature = "dev-hooks")]
85fn backoff_shape() -> Shape {
86    static SHAPE: std::sync::OnceLock<Shape> = std::sync::OnceLock::new();
87    *SHAPE.get_or_init(|| match std::env::var("MNEMO_DEV_BACKOFF").as_deref() {
88        Ok("young") => Shape::Young,
89        _ => Shape::Doubling,
90    })
91}
92
93#[cfg(not(feature = "dev-hooks"))]
94fn backoff_shape() -> Shape {
95    Shape::Doubling
96}
97
98/// The latest deadline a call gets: a longer one (`Duration::MAX`, say) is
99/// clamped to it rather than overflowing the clock.
100const LONGEST_DEADLINE: Duration = Duration::from_secs(100 * 365 * 24 * 3600);
101
102impl Call {
103    pub(crate) fn new(deadline: Duration, cancel: Option<&CancelToken>) -> Self {
104        let now = Instant::now();
105        let deadline = now
106            .checked_add(deadline.min(LONGEST_DEADLINE))
107            .or_else(|| now.checked_add(Duration::from_secs(24 * 3600)))
108            .unwrap_or(now);
109        Call {
110            started: now,
111            deadline,
112            cancel: cancel.cloned(),
113            sleep: FIRST_SLEEP,
114            sidecar_reopened: false,
115        }
116    }
117
118    /// `Err(Cancelled)` once the call is cancelled.
119    pub(crate) fn check(&self) -> Result<()> {
120        match &self.cancel {
121            Some(c) if c.is_cancelled() => Err(MnemoError::Cancelled),
122            _ => Ok(()),
123        }
124    }
125
126    /// Whether the deadline has passed.
127    pub(crate) fn past_deadline(&self) -> bool {
128        Instant::now() >= self.deadline
129    }
130
131    /// Wait before the next try: a jittered sleep that doubles from 1 ms to
132    /// 50 ms, cut short by the deadline or a cancel. `Ok(false)` once the
133    /// deadline has passed.
134    pub(crate) fn back_off(&mut self) -> Result<bool> {
135        self.check()?;
136        let now = Instant::now();
137        if now >= self.deadline {
138            return Ok(false);
139        }
140        let young = backoff_shape() == Shape::Young && now - self.started < YOUNG_FOR;
141        let jittered = {
142            use rand::Rng;
143            // Step 5's alternative: 1 to 2 ms sleeps while the wait is young.
144            let (lo, hi) = if young {
145                (1.0, 2.0)
146            } else {
147                let ms = self.sleep.as_secs_f64() * 1000.0;
148                (ms / 2.0, ms)
149            };
150            Duration::from_secs_f64(rand::thread_rng().gen_range(lo..=hi) / 1000.0)
151        };
152        let d = jittered.min(self.deadline - now);
153        let cancelled = match &self.cancel {
154            Some(c) => c.sleep(d),
155            None => {
156                std::thread::sleep(d);
157                false
158            }
159        };
160        if cancelled {
161            return Err(MnemoError::Cancelled);
162        }
163        if young {
164            self.sleep = YOUNG_THEN;
165            return Ok(Instant::now() < self.deadline);
166        }
167        self.sleep = (self.sleep * 2).min(LONGEST_SLEEP);
168        Ok(Instant::now() < self.deadline)
169    }
170}