mnemo_engine/shared/
call.rs1use std::sync::{Arc, Condvar, Mutex};
6use std::time::{Duration, Instant};
7
8use crate::error::{MnemoError, Result};
9
10#[derive(Clone, Debug, Default)]
20pub struct CancelToken(Arc<(Mutex<bool>, Condvar)>);
21
22impl CancelToken {
23 pub fn new() -> Self {
25 Self::default()
26 }
27
28 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 pub fn is_cancelled(&self) -> bool {
37 *self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
38 }
39
40 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
55pub(crate) struct Call {
57 started: Instant,
58 deadline: Instant,
59 cancel: Option<CancelToken>,
60 sleep: Duration,
61 pub(crate) sidecar_reopened: bool,
64 hurried: bool,
67}
68
69const HURRIED: (f64, f64) = (1.0, 2.0);
71
72const FIRST_SLEEP: Duration = Duration::from_millis(1);
75const LONGEST_SLEEP: Duration = Duration::from_millis(50);
76
77const 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
104const 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 pub(crate) fn waited(&self) -> Duration {
127 self.started.elapsed()
128 }
129
130 pub(crate) fn hurry(&mut self) {
133 self.hurried = true;
134 }
135
136 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 pub(crate) fn past_deadline(&self) -> bool {
146 Instant::now() >= self.deadline
147 }
148
149 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 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}