mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 14:51:20 -05:00
Merge pull request #10570 from dotCooCoo/fix/paper-lookup-one-worker
Print: a stalled paper-size lookup no longer piles up worker threads
This commit is contained in:
@@ -37,32 +37,88 @@ impl PrintService for SystemPrint {
|
||||
true
|
||||
}
|
||||
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
|
||||
self.papers.poll(printer, fresh, |printer| installed_papers(&printer))
|
||||
self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer))
|
||||
}
|
||||
}
|
||||
|
||||
/// The paper-size lookup in flight: the printer it reads and its worker's channel.
|
||||
/// A paper-size read that waits for the worker before it.
|
||||
type PaperRead = Box<dyn FnOnce(String) -> Vec<Paper> + Send>;
|
||||
|
||||
/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits
|
||||
/// when no worker may start before its printer is given no paper sizes.
|
||||
const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
/// The most paper-size workers alive at once, stalled ones included.
|
||||
const PAPER_WORKERS: usize = 4;
|
||||
|
||||
/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it
|
||||
/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when
|
||||
/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive.
|
||||
#[derive(Default)]
|
||||
struct PaperLookup(Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>);
|
||||
struct PaperLookup {
|
||||
current: Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>,
|
||||
waiting: Option<(String, PaperRead, std::time::Instant)>,
|
||||
started: Vec<(std::time::Instant, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
|
||||
workers: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
/// Marks a worker finished and counts it down when it ends, including when it panics.
|
||||
struct WorkerDone(std::sync::Arc<std::sync::atomic::AtomicUsize>, std::sync::Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl Drop for WorkerDone {
|
||||
fn drop(&mut self) {
|
||||
self.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl PaperLookup {
|
||||
/// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight
|
||||
/// reads another printer, or when none is in flight; the earlier one's answer is dropped.
|
||||
fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
||||
if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) {
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
let name = printer.to_string();
|
||||
let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
||||
let _ = send.send(read(name));
|
||||
});
|
||||
self.0 = Some((printer.to_string(), receive));
|
||||
/// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or
|
||||
/// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest
|
||||
/// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`.
|
||||
/// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while
|
||||
/// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes.
|
||||
fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
||||
let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p));
|
||||
if fresh || wanted.is_none_or(|p| p != printer) {
|
||||
self.current = None;
|
||||
self.waiting = Some((printer.to_string(), Box::new(read), now));
|
||||
}
|
||||
let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) {
|
||||
self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst));
|
||||
let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let may_start = alive == 0
|
||||
|| (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT));
|
||||
if may_start && let Some((name, read, _)) = self.waiting.take() {
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let done = WorkerDone(self.workers.clone(), running.clone());
|
||||
let printer = name.clone();
|
||||
let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
||||
let worker = done;
|
||||
let papers = read(printer);
|
||||
worker.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = send.send(papers);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
return Papers::Ready(Vec::new());
|
||||
}
|
||||
self.started.push((now, running));
|
||||
self.current = Some((name, receive));
|
||||
}
|
||||
if let Some((.., since)) = &self.waiting {
|
||||
if now.saturating_duration_since(*since) < PAPER_WAIT {
|
||||
return Papers::Pending;
|
||||
}
|
||||
self.waiting = None;
|
||||
return Papers::Ready(Vec::new());
|
||||
}
|
||||
let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) {
|
||||
Some(Ok(papers)) => Papers::Ready(papers),
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending,
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()),
|
||||
};
|
||||
self.0 = None;
|
||||
self.current = None;
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -254,15 +310,27 @@ mod paper_lookup_tests {
|
||||
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
|
||||
}
|
||||
|
||||
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
||||
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
||||
let mut polled = lookup.poll(printer, true, move |_| paper(key));
|
||||
/// The test clock: `secs` seconds after a fixed start.
|
||||
fn at(secs: u64) -> std::time::Instant {
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
*START.get_or_init(std::time::Instant::now) + std::time::Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
/// Poll the lookup of `printer` at `now` until it answers.
|
||||
fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec<Paper> {
|
||||
loop {
|
||||
match polled {
|
||||
match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) {
|
||||
Papers::Ready(papers) => return papers,
|
||||
Papers::Pending => std::thread::yield_now(),
|
||||
}
|
||||
polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
||||
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
||||
match lookup.poll(printer, true, at(0), move |_| paper(key)) {
|
||||
Papers::Ready(papers) => papers,
|
||||
Papers::Pending => settle(lookup, printer, at(0)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,19 +347,110 @@ mod paper_lookup_tests {
|
||||
fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() {
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (open, read) = gated("Old");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let (other, read) = gated("Office");
|
||||
assert!(matches!(lookup.poll("Office", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
let _ = other.send(());
|
||||
// Back on the card printer.
|
||||
assert_eq!(answer(&mut lookup, "Card", "New"), paper("New"));
|
||||
// The dialog opens again on the card printer while a lookup of it is still running.
|
||||
let (open, read) = gated("Stale");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (open, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let started = std::sync::Arc::new(AtomicUsize::new(0));
|
||||
for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() {
|
||||
let count = started.clone();
|
||||
let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
paper("Changed")
|
||||
});
|
||||
assert!(matches!(polled, Papers::Pending), "{printer}");
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs");
|
||||
}
|
||||
let _ = open.send(());
|
||||
// Only the newest choice is read, once the stalled worker ends.
|
||||
assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed"));
|
||||
assert_eq!(started.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (card, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let (office, read) = gated("Office");
|
||||
assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new");
|
||||
// The worker has stalled for the whole wait: the waiting read starts beside it.
|
||||
assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker");
|
||||
let _ = office.send(());
|
||||
assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office"));
|
||||
// The worker that answered counts itself down once its thread ends.
|
||||
while lookup.workers.load(Ordering::SeqCst) > 1 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// The older worker has stalled long enough for another read to start immediately.
|
||||
let (next, began) = std::sync::mpsc::channel();
|
||||
let (open, read) = gated("Next");
|
||||
assert!(matches!(
|
||||
lookup.poll("Next", false, at(16), move |printer| {
|
||||
let _ = next.send(());
|
||||
read(printer)
|
||||
}),
|
||||
Papers::Pending
|
||||
));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait");
|
||||
began.recv().expect("the next read started");
|
||||
let _ = open.send(());
|
||||
assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next"));
|
||||
drop(card);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (card, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
// More stalls fill the workers up to the limit, one wait apart.
|
||||
let mut stalls = vec![card];
|
||||
for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() {
|
||||
let (gate, read) = gated("Stalled");
|
||||
stalls.push(gate);
|
||||
assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}");
|
||||
}
|
||||
assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
// Reopening the same printer and choosing another printer each starts a new wait.
|
||||
assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) {
|
||||
Papers::Ready(papers) => assert_eq!(papers, []),
|
||||
Papers::Pending => panic!("the wait for the stalled workers did not end"),
|
||||
}
|
||||
assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS);
|
||||
// Once the stalled workers end, the next choice is read again.
|
||||
drop(stalls);
|
||||
let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) {
|
||||
Papers::Ready(papers) => papers,
|
||||
Papers::Pending => settle(&mut lookup, "Photo", at(107)),
|
||||
};
|
||||
assert_eq!(papers, paper("Ready"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user