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    /// LOCK-2: a writer past the valve's threshold retries every few ms, so
65    /// it doesn't sleep through the readers' drain.
66    hurried: bool,
67}
68
69/// LOCK-2: a hurried writer's sleeps, 1 to 2 ms, jittered.
70const HURRIED: (f64, f64) = (1.0, 2.0);
71
72/// The backoff's first and longest sleep. Step 5's bench tunes them (the
73/// design note: shorter sleeps while a wait is young).
74const FIRST_SLEEP: Duration = Duration::from_millis(1);
75const LONGEST_SLEEP: Duration = Duration::from_millis(50);
76
77/// Step 5's alternative shape ("short sleeps while a wait is young"): 1 to
78/// 2 ms sleeps for the first `YOUNG_FOR` of a wait, then doubling from
79/// `YOUNG_THEN`. Selected for benchmarking only, through
80/// `MNEMO_DEV_BACKOFF=young` in a `dev-hooks` build.
81const YOUNG_FOR: Duration = Duration::from_millis(15);
82const YOUNG_THEN: Duration = Duration::from_millis(2);
83
84#[derive(Clone, Copy, PartialEq, Eq)]
85enum Shape {
86    Doubling,
87    Young,
88}
89
90#[cfg(feature = "dev-hooks")]
91fn backoff_shape() -> Shape {
92    static SHAPE: std::sync::OnceLock<Shape> = std::sync::OnceLock::new();
93    *SHAPE.get_or_init(|| match std::env::var("MNEMO_DEV_BACKOFF").as_deref() {
94        Ok("young") => Shape::Young,
95        _ => Shape::Doubling,
96    })
97}
98
99#[cfg(not(feature = "dev-hooks"))]
100fn backoff_shape() -> Shape {
101    Shape::Doubling
102}
103
104/// The latest deadline a call gets: a longer one (`Duration::MAX`, say) is
105/// clamped to it rather than overflowing the clock.
106const LONGEST_DEADLINE: Duration = Duration::from_secs(100 * 365 * 24 * 3600);
107
108impl Call {
109    pub(crate) fn new(deadline: Duration, cancel: Option<&CancelToken>) -> Self {
110        let now = Instant::now();
111        let deadline = now
112            .checked_add(deadline.min(LONGEST_DEADLINE))
113            .or_else(|| now.checked_add(Duration::from_secs(24 * 3600)))
114            .unwrap_or(now);
115        Call {
116            started: now,
117            deadline,
118            cancel: cancel.cloned(),
119            sleep: FIRST_SLEEP,
120            sidecar_reopened: false,
121            hurried: false,
122        }
123    }
124
125    /// How long this call has been waiting.
126    pub(crate) fn waited(&self) -> Duration {
127        self.started.elapsed()
128    }
129
130    /// LOCK-2: from now on, retry every 1 to 2 ms instead of the doubling
131    /// backoff (a writer past the valve's threshold).
132    pub(crate) fn hurry(&mut self) {
133        self.hurried = true;
134    }
135
136    /// `Err(Cancelled)` once the call is cancelled.
137    pub(crate) fn check(&self) -> Result<()> {
138        match &self.cancel {
139            Some(c) if c.is_cancelled() => Err(MnemoError::Cancelled),
140            _ => Ok(()),
141        }
142    }
143
144    /// Whether the deadline has passed.
145    pub(crate) fn past_deadline(&self) -> bool {
146        Instant::now() >= self.deadline
147    }
148
149    /// Wait before the next try: a jittered sleep that doubles from 1 ms to
150    /// 50 ms, cut short by the deadline or a cancel. `Ok(false)` once the
151    /// deadline has passed.
152    pub(crate) fn back_off(&mut self) -> Result<bool> {
153        self.check()?;
154        let now = Instant::now();
155        if now >= self.deadline {
156            return Ok(false);
157        }
158        let young = backoff_shape() == Shape::Young && now - self.started < YOUNG_FOR;
159        let jittered = {
160            use rand::Rng;
161            // Step 5's alternative: 1 to 2 ms sleeps while the wait is young.
162            let (lo, hi) = if self.hurried {
163                HURRIED
164            } else if young {
165                (1.0, 2.0)
166            } else {
167                let ms = self.sleep.as_secs_f64() * 1000.0;
168                (ms / 2.0, ms)
169            };
170            Duration::from_secs_f64(rand::thread_rng().gen_range(lo..=hi) / 1000.0)
171        };
172        let d = jittered.min(self.deadline - now);
173        let cancelled = match &self.cancel {
174            Some(c) => c.sleep(d),
175            None => {
176                std::thread::sleep(d);
177                false
178            }
179        };
180        if cancelled {
181            return Err(MnemoError::Cancelled);
182        }
183        if young {
184            self.sleep = YOUNG_THEN;
185            return Ok(Instant::now() < self.deadline);
186        }
187        self.sleep = (self.sleep * 2).min(LONGEST_SLEEP);
188        Ok(Instant::now() < self.deadline)
189    }
190}