lean_ctx_cloud/
background.rs1use std::collections::{BTreeMap, BTreeSet, VecDeque};
19use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
20use std::time::{Duration, Instant};
21
22type Job = Box<dyn FnOnce() -> Option<String> + Send>;
24
25#[derive(Default)]
26struct Queue {
27 jobs: VecDeque<(String, Option<String>, Job)>,
28 answers: BTreeMap<String, Vec<String>>,
30 keys: BTreeSet<String>,
32 running: bool,
33 started: bool,
34}
35
36static QUEUE: Mutex<Option<Queue>> = Mutex::new(None);
37static WAKE: Condvar = Condvar::new();
38
39fn queue() -> MutexGuard<'static, Option<Queue>> {
40 QUEUE.lock().unwrap_or_else(PoisonError::into_inner)
41}
42
43fn with_queue<T>(change: impl FnOnce(&mut Queue) -> T) -> T {
44 let mut guard = queue();
45 change(guard.get_or_insert_with(Queue::default))
46}
47
48pub fn submit(caller: &str, job: impl FnOnce() -> Option<String> + Send + 'static) {
51 push(caller, None, Box::new(job));
52}
53
54pub fn submit_once(
57 caller: &str,
58 key: &str,
59 job: impl FnOnce() -> Option<String> + Send + 'static,
60) -> bool {
61 if with_queue(|q| q.keys.contains(key)) {
62 return false;
63 }
64 push(caller, Some(key.to_string()), Box::new(job));
65 true
66}
67
68fn push(caller: &str, key: Option<String>, job: Job) {
69 let start = with_queue(|q| {
70 if let Some(key) = &key {
71 q.keys.insert(key.clone());
72 }
73 q.jobs.push_back((caller.to_string(), key, job));
74 !std::mem::replace(&mut q.started, true)
75 });
76 WAKE.notify_all();
77 if start {
78 let spawned = std::thread::Builder::new()
79 .name("cloud-calls".into())
80 .spawn(run);
81 if spawned.is_err() {
82 with_queue(|q| q.started = false);
84 }
85 }
86}
87
88fn run() {
89 loop {
90 let (caller, key, job) = {
91 let mut guard = queue();
92 loop {
93 let q = guard.get_or_insert_with(Queue::default);
94 if let Some(next) = q.jobs.pop_front() {
95 q.running = true;
96 break next;
97 }
98 q.running = false;
99 WAKE.notify_all();
100 guard = WAKE.wait(guard).unwrap_or_else(PoisonError::into_inner);
101 }
102 };
103 let line = job();
104 with_queue(|q| {
105 if let Some(key) = key {
106 q.keys.remove(&key);
107 }
108 if let Some(line) = line {
109 q.answers.entry(caller).or_default().push(line);
110 }
111 });
112 }
113}
114
115pub fn take(caller: &str) -> Vec<String> {
117 with_queue(|q| q.answers.remove(caller).unwrap_or_default())
118}
119
120pub fn with_answers(caller: &str, text: String) -> String {
122 earlier(caller).present(text)
123}
124
125pub fn earlier(caller: &str) -> Earlier {
130 Earlier {
131 caller: caller.to_string(),
132 answers: take(caller),
133 }
134}
135
136pub struct Earlier {
138 caller: String,
139 answers: Vec<String>,
140}
141
142impl Earlier {
143 pub fn present(mut self, text: String) -> String {
145 let answers = std::mem::take(&mut self.answers);
146 if answers.is_empty() {
147 return text;
148 }
149 let mut out = String::from("The Cloud answered your earlier requests:\n");
150 for answer in answers {
151 out.push_str("- ");
152 out.push_str(&answer);
153 out.push('\n');
154 }
155 out.push('\n');
156 out.push_str(&text);
157 out
158 }
159}
160
161impl Drop for Earlier {
162 fn drop(&mut self) {
163 if self.answers.is_empty() {
164 return;
165 }
166 let answers = std::mem::take(&mut self.answers);
167 with_queue(|q| {
168 let waiting = q
169 .answers
170 .entry(std::mem::take(&mut self.caller))
171 .or_default();
172 waiting.splice(0..0, answers);
173 });
174 }
175}
176
177pub fn wait_idle(timeout: Duration) -> bool {
180 let deadline = Instant::now() + timeout;
181 let mut guard = queue();
182 loop {
183 let idle = guard
184 .as_ref()
185 .is_none_or(|q| q.jobs.is_empty() && !q.running);
186 if idle {
187 return true;
188 }
189 let Some(left) = deadline.checked_duration_since(Instant::now()) else {
190 return false;
191 };
192 guard = WAKE
193 .wait_timeout(guard, left)
194 .unwrap_or_else(PoisonError::into_inner)
195 .0;
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn requests_run_in_order_off_the_caller_and_answer_once() {
205 let caller = "test:requests_run_in_order";
206 let order = std::sync::Arc::new(Mutex::new(Vec::new()));
207 for n in 0..3 {
208 let order = std::sync::Arc::clone(&order);
209 submit(caller, move || {
210 order.lock().unwrap().push(n);
211 Some(format!("answer {n}"))
212 });
213 }
214 assert!(wait_idle(Duration::from_secs(10)));
215 assert_eq!(*order.lock().unwrap(), vec![0, 1, 2]);
216 let shown = with_answers(caller, "now".into());
217 assert_eq!(
218 shown,
219 "The Cloud answered your earlier requests:\n- answer 0\n- answer 1\n- answer 2\n\nnow"
220 );
221 assert_eq!(with_answers(caller, "again".into()), "again", "shown once");
222 }
223
224 #[test]
225 fn an_answer_during_the_call_comes_with_the_next_one() {
226 let caller = "test:during_the_call";
227 let call = earlier(caller);
228 submit(caller, || Some("fast".into()));
230 assert!(wait_idle(Duration::from_secs(10)));
231 assert_eq!(call.present("first".into()), "first");
232 let next = earlier(caller).present("second".into());
233 assert!(
234 next.contains("- fast") && next.ends_with("second"),
235 "{next}"
236 );
237
238 submit(caller, || Some("kept".into()));
240 assert!(wait_idle(Duration::from_secs(10)));
241 drop(earlier(caller));
242 submit(caller, || Some("later".into()));
243 assert!(wait_idle(Duration::from_secs(10)));
244 let shown = with_answers(caller, "third".into());
245 assert!(shown.find("- kept") < shown.find("- later"), "{shown}");
246 }
247
248 #[test]
249 fn a_keyed_request_is_queued_once() {
250 let caller = "test:keyed";
251 let gate = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
252 let held = std::sync::Arc::clone(&gate);
253 assert!(submit_once(caller, "test:key", move || {
254 let (open, cv) = &*held;
255 let mut open = open.lock().unwrap();
256 while !*open {
257 open = cv.wait(open).unwrap();
258 }
259 None
260 }));
261 assert!(!submit_once(caller, "test:key", || None), "already queued");
262 *gate.0.lock().unwrap() = true;
263 gate.1.notify_all();
264 assert!(wait_idle(Duration::from_secs(10)));
265 assert!(submit_once(caller, "test:key", || None), "done, so again");
266 assert!(wait_idle(Duration::from_secs(10)));
267 }
268}