use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
type Job = Box<dyn FnOnce() -> Option<String> + Send>;
#[derive(Default)]
struct Queue {
jobs: VecDeque<(String, Option<String>, Job)>,
answers: BTreeMap<String, Vec<String>>,
keys: BTreeSet<String>,
running: bool,
started: bool,
}
static QUEUE: Mutex<Option<Queue>> = Mutex::new(None);
static WAKE: Condvar = Condvar::new();
fn queue() -> MutexGuard<'static, Option<Queue>> {
QUEUE.lock().unwrap_or_else(PoisonError::into_inner)
}
fn with_queue<T>(change: impl FnOnce(&mut Queue) -> T) -> T {
let mut guard = queue();
change(guard.get_or_insert_with(Queue::default))
}
pub fn submit(caller: &str, job: impl FnOnce() -> Option<String> + Send + 'static) {
push(caller, None, Box::new(job));
}
pub fn submit_once(
caller: &str,
key: &str,
job: impl FnOnce() -> Option<String> + Send + 'static,
) -> bool {
if with_queue(|q| q.keys.contains(key)) {
return false;
}
push(caller, Some(key.to_string()), Box::new(job));
true
}
fn push(caller: &str, key: Option<String>, job: Job) {
let start = with_queue(|q| {
if let Some(key) = &key {
q.keys.insert(key.clone());
}
q.jobs.push_back((caller.to_string(), key, job));
!std::mem::replace(&mut q.started, true)
});
WAKE.notify_all();
if start {
let spawned = std::thread::Builder::new()
.name("cloud-calls".into())
.spawn(run);
if spawned.is_err() {
with_queue(|q| q.started = false);
}
}
}
fn run() {
loop {
let (caller, key, job) = {
let mut guard = queue();
loop {
let q = guard.get_or_insert_with(Queue::default);
if let Some(next) = q.jobs.pop_front() {
q.running = true;
break next;
}
q.running = false;
WAKE.notify_all();
guard = WAKE.wait(guard).unwrap_or_else(PoisonError::into_inner);
}
};
let line = job();
with_queue(|q| {
if let Some(key) = key {
q.keys.remove(&key);
}
if let Some(line) = line {
q.answers.entry(caller).or_default().push(line);
}
});
}
}
pub fn take(caller: &str) -> Vec<String> {
with_queue(|q| q.answers.remove(caller).unwrap_or_default())
}
pub fn with_answers(caller: &str, text: String) -> String {
earlier(caller).present(text)
}
pub fn earlier(caller: &str) -> Earlier {
Earlier {
caller: caller.to_string(),
answers: take(caller),
}
}
pub struct Earlier {
caller: String,
answers: Vec<String>,
}
impl Earlier {
pub fn present(mut self, text: String) -> String {
let answers = std::mem::take(&mut self.answers);
if answers.is_empty() {
return text;
}
let mut out = String::from("LeanCTX Cloud answered your earlier requests:\n");
for answer in answers {
out.push_str("- ");
out.push_str(&answer);
out.push('\n');
}
out.push('\n');
out.push_str(&text);
out
}
}
impl Drop for Earlier {
fn drop(&mut self) {
if self.answers.is_empty() {
return;
}
let answers = std::mem::take(&mut self.answers);
with_queue(|q| {
let waiting = q
.answers
.entry(std::mem::take(&mut self.caller))
.or_default();
waiting.splice(0..0, answers);
});
}
}
pub fn wait_idle(timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
let mut guard = queue();
loop {
let idle = guard
.as_ref()
.is_none_or(|q| q.jobs.is_empty() && !q.running);
if idle {
return true;
}
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
return false;
};
guard = WAKE
.wait_timeout(guard, left)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn requests_run_in_order_off_the_caller_and_answer_once() {
let caller = "test:requests_run_in_order";
let order = std::sync::Arc::new(Mutex::new(Vec::new()));
for n in 0..3 {
let order = std::sync::Arc::clone(&order);
submit(caller, move || {
order.lock().unwrap().push(n);
Some(format!("answer {n}"))
});
}
assert!(wait_idle(Duration::from_secs(10)));
assert_eq!(*order.lock().unwrap(), vec![0, 1, 2]);
let shown = with_answers(caller, "now".into());
assert_eq!(
shown,
"LeanCTX Cloud answered your earlier requests:\n- answer 0\n- answer 1\n- answer 2\n\nnow"
);
assert_eq!(with_answers(caller, "again".into()), "again", "shown once");
}
#[test]
fn an_answer_during_the_call_comes_with_the_next_one() {
let caller = "test:during_the_call";
let call = earlier(caller);
submit(caller, || Some("fast".into()));
assert!(wait_idle(Duration::from_secs(10)));
assert_eq!(call.present("first".into()), "first");
let next = earlier(caller).present("second".into());
assert!(
next.contains("- fast") && next.ends_with("second"),
"{next}"
);
submit(caller, || Some("kept".into()));
assert!(wait_idle(Duration::from_secs(10)));
drop(earlier(caller));
submit(caller, || Some("later".into()));
assert!(wait_idle(Duration::from_secs(10)));
let shown = with_answers(caller, "third".into());
assert!(shown.find("- kept") < shown.find("- later"), "{shown}");
}
#[test]
fn a_keyed_request_is_queued_once() {
let caller = "test:keyed";
let gate = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
let held = std::sync::Arc::clone(&gate);
assert!(submit_once(caller, "test:key", move || {
let (open, cv) = &*held;
let mut open = open.lock().unwrap();
while !*open {
open = cv.wait(open).unwrap();
}
None
}));
assert!(!submit_once(caller, "test:key", || None), "already queued");
*gate.0.lock().unwrap() = true;
gate.1.notify_all();
assert!(wait_idle(Duration::from_secs(10)));
assert!(submit_once(caller, "test:key", || None), "done, so again");
assert!(wait_idle(Duration::from_secs(10)));
}
}