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}
65
66const FIRST_SLEEP: Duration = Duration::from_millis(1);
69const LONGEST_SLEEP: Duration = Duration::from_millis(50);
70
71const 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
98const 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 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 pub(crate) fn past_deadline(&self) -> bool {
128 Instant::now() >= self.deadline
129 }
130
131 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 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}