Merge pull request #3974 from dotCooCoo/fix/font-test-handshakes

font-catalog, font-manager: scan and preview tests wait on signals instead of on time
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 11:32:31 +07:00
commit 7b1c044995
4 files changed
+146 -66

No files matched your search

+13 -5
View File
@@ -588,12 +588,20 @@ impl Catalog {
/// it. Does nothing once it has started or run, or when no thread can be started (the first
/// lookup then scans).
pub fn scan_in_background(self: &Arc<Self>) {
if self.ready.get().is_none() && !self.scanning.swap(true, Ordering::AcqRel) {
let me = Arc::clone(self);
if std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()).is_err() {
self.scanning.store(false, Ordering::Release);
}
drop(self.start_background_scan());
}
/// [`Catalog::scan_in_background`], returning the thread it started, if it started one.
pub(crate) fn start_background_scan(self: &Arc<Self>) -> Option<std::thread::JoinHandle<()>> {
if self.ready.get().is_some() || self.scanning.swap(true, Ordering::AcqRel) {
return None;
}
let me = Arc::clone(self);
let thread = std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan());
if thread.is_err() {
self.scanning.store(false, Ordering::Release);
}
thread.ok()
}
/// The background thread's scan. A scan that panics leaves the catalog unscanned and not
+16 -12
View File
@@ -586,11 +586,11 @@ fn a_background_scan_that_panics_lets_the_next_call_scan_again() {
});
let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister));
// Each call starts a scan only when none is running; the second starts once the failed one has ended.
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !cat.is_ready() && std::time::Instant::now() < deadline {
cat.scan_in_background();
std::thread::sleep(Duration::from_millis(1));
}
let failed = cat.start_background_scan().expect("the first call starts a scan");
assert!(failed.join().is_err(), "the first scan fails");
assert!(!cat.is_ready());
let again = cat.start_background_scan().expect("a failed scan must not leave the catalog waiting on it");
again.join().unwrap();
assert!(cat.is_ready(), "a failed scan must not leave the catalog waiting on it");
assert_eq!(calls.load(Ordering::Relaxed), 2);
}
@@ -605,13 +605,10 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() {
let (entered, scan_entered) = mpsc::channel();
let (release, scan_released) = mpsc::channel::<()>();
let scan_released = std::sync::Mutex::new(scan_released);
let waited_out = Arc::new(AtomicUsize::new(0));
let flag = Arc::clone(&waited_out);
let lister: Lister = Arc::new(move || {
let _ = entered.send(());
if let Err(mpsc::RecvTimeoutError::Timeout) = scan_released.lock().unwrap().recv_timeout(Duration::from_secs(10)) {
flag.fetch_add(1, Ordering::Relaxed);
}
// The first scan stays here until the test sends on `release`; once it is dropped, scans go straight through.
let _ = scan_released.lock().unwrap().recv();
Vec::new()
});
let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister));
@@ -619,12 +616,19 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() {
assert!(!cat.is_ready(), "adding started no scan");
cat.scan_in_background();
scan_entered.recv_timeout(Duration::from_secs(10)).unwrap();
cat.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default()).unwrap();
let adding = Arc::clone(&cat);
let (added, add_returned) = mpsc::channel();
std::thread::spawn(move || {
let _ = added.send(adding.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default()));
});
// The scan cannot end before `release` sends, so an add that returns now did not wait for it. The limit only stops a
// test whose add waits.
let returned = add_returned.recv_timeout(Duration::from_secs(10));
release.send(()).unwrap();
// Later scans (the rescans below) go straight through.
drop(release);
returned.expect("the add during the scan returned before the scan did").unwrap();
assert_eq!(cat.styles("App Face").len(), 1);
assert_eq!(waited_out.load(Ordering::Relaxed), 0, "the add during the scan returned before the scan did");
// The added Bold comes first; the installed file's Bold is another version of it, not another face.
assert_eq!(cat.resolve("Test Sans", "Bold").map(|(f, _)| f), bold.first().cloned());
assert_eq!(cat.versions(&bold[0]).len(), 2);
+68 -17
View File
@@ -4,8 +4,8 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::time::Duration;
use craft_font_manager::craft_font_catalog::Os;
@@ -73,6 +73,36 @@ struct Rig {
fx: Fixture,
panel: Rc<RefCell<FontsPanel>>,
store: Arc<FakeStore>,
woken: Arc<Woken>,
}
/// How long a test waits for another thread before it fails as hung. A result that comes does not depend on it.
const HANG: Duration = Duration::from_secs(10);
/// Counts the repaints asked for from threads other than the test's, as the preview workers ask for one after each
/// result.
#[derive(Default)]
struct Woken {
count: Mutex<u64>,
changed: Condvar,
}
impl Woken {
fn count(&self) -> u64 {
*self.count.lock().unwrap_or_else(PoisonError::into_inner)
}
fn wake(&self) {
*self.count.lock().unwrap_or_else(PoisonError::into_inner) += 1;
self.changed.notify_all();
}
/// Waits until a repaint is asked for after [`Woken::count`] was `seen`.
fn wait_past(&self, seen: u64) {
let count = self.count.lock().unwrap_or_else(PoisonError::into_inner);
let (count, _) = self.changed.wait_timeout_while(count, HANG, |count| *count == seen).unwrap_or_else(PoisonError::into_inner);
assert!(*count > seen, "previews kept loading");
}
}
fn root(name: &str) -> PathBuf {
@@ -132,9 +162,16 @@ fn show(panel: FontsPanel, store: Arc<FakeStore>, host: Arc<Host>) -> Rig {
let mut fx = Fixture::new(move |ui| {
FontsPanelView::new(&mut shown.borrow_mut()).show(ui);
});
let woken = Arc::new(Woken::default());
let (counted, test) = (Arc::clone(&woken), std::thread::current().id());
fx.ctx().set_repaint_observer(move |_| {
if std::thread::current().id() != test {
counted.wake();
}
});
fx.in_room(Room::Window).host(host);
fx.settle();
Rig { fx, panel, store }
Rig { fx, panel, store, woken }
}
impl Rig {
@@ -367,8 +404,9 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() {
struct FakeService {
answered: Mutex<Vec<String>>,
cancelled: Mutex<Vec<String>>,
/// Requests that reached the service.
started: AtomicUsize,
/// Requests that reached the service, notified on `arrived` as each one does.
started: Mutex<usize>,
arrived: Condvar,
held: AtomicBool,
/// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have.
no_samples: AtomicBool,
@@ -378,7 +416,8 @@ struct FakeService {
impl Fetch for FakeService {
fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError> {
self.started.fetch_add(1, Ordering::SeqCst);
*self.started.lock().unwrap_or_else(PoisonError::into_inner) += 1;
self.arrived.notify_all();
while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(2));
}
@@ -403,6 +442,18 @@ impl FakeService {
std::mem::take(&mut *self.answered.lock().unwrap_or_else(PoisonError::into_inner))
}
/// The requests that reached the service.
fn started(&self) -> usize {
*self.started.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Waits until a request has reached the service.
fn wait_started(&self) {
let started = self.started.lock().unwrap_or_else(PoisonError::into_inner);
let (started, _) = self.arrived.wait_timeout_while(started, HANG, |started| *started == 0).unwrap_or_else(PoisonError::into_inner);
assert!(*started > 0, "the service was asked");
}
/// The numbers of the families whose `subset` the URLs of `answered` name: `sample`, `ascii`, or `u/` for typed
/// characters.
fn numbers(answered: &[String], subset: &str) -> Vec<usize> {
@@ -468,16 +519,22 @@ impl Rig {
self.fx.settle();
}
/// Runs passes until the panel has fetched what it asks for and asks for nothing more.
/// Runs passes until the panel has fetched what it asks for and asks for nothing more. While a preview is on its
/// way, the next pass waits for the repaint its worker asks for once the result is ready.
fn load(&mut self) {
let mut quiet = 0;
for _ in 0..500 {
let seen = self.woken.count();
self.fx.frame(Vec::new());
quiet = if self.panel.borrow().loading_previews() { 0 } else { quiet + 1 };
if self.panel.borrow().loading_previews() {
quiet = 0;
self.woken.wait_past(seen);
continue;
}
quiet += 1;
if quiet == 3 {
return;
}
std::thread::sleep(Duration::from_millis(1));
}
panic!("previews kept loading");
}
@@ -563,13 +620,7 @@ fn a_resize_and_a_search_cancel_no_preview() {
service.held.store(true, Ordering::SeqCst);
let mut rig = service_rig("previews-kept", &service, latin_index());
rig.set_previews(true);
for _ in 0..500 {
if service.started.load(Ordering::SeqCst) > 0 {
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked");
service.wait_started();
let shown = rig.numbers();
rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle();
rig.type_into("Search", "Family");
@@ -602,7 +653,7 @@ fn a_family_of_an_added_source_is_not_asked_of_the_service() {
rig.open("Added");
rig.load();
rig.named(Role::BUTTON, "Preview");
assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls());
assert_eq!(service.started(), 0, "{:?}", service.urls());
}
/// A sample the service has not (another text) is asked for as the sample's characters, once.
+49 -32
View File
@@ -9,8 +9,9 @@ use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use std::time::Duration;
use craft_font_manager::craft_font_catalog::Os;
use craft_font_manager::store::{FakeStore, Installer, SuiteStore};
@@ -118,7 +119,8 @@ enum Reply {
struct Service {
base: String,
routes: Arc<Mutex<HashMap<String, Reply>>>,
log: Arc<Mutex<Vec<String>>>,
/// The paths asked for, notified as each one arrives.
log: Arc<(Mutex<Vec<String>>, Condvar)>,
gate: Arc<(Mutex<bool>, Condvar)>,
}
@@ -143,7 +145,14 @@ impl Service {
}
fn requests(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
self.log.0.lock().unwrap().clone()
}
/// Waits until `n` requests have reached the service.
fn wait_for_requests(&self, n: usize) {
let log = self.log.0.lock().unwrap();
let (log, _) = self.log.1.wait_timeout_while(log, HANG, |log| log.len() < n).unwrap();
assert!(log.len() >= n, "{} of {n} requests reached the service", log.len());
}
fn release(&self) {
@@ -152,7 +161,7 @@ impl Service {
}
}
fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &Mutex<Vec<String>>, gate: &(Mutex<bool>, Condvar)) {
fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &(Mutex<Vec<String>>, Condvar), gate: &(Mutex<bool>, Condvar)) {
let mut head = Vec::new();
let mut b = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
@@ -162,7 +171,8 @@ fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &Mutex<
}
}
let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string();
log.lock().unwrap().push(path.clone());
log.0.lock().unwrap().push(path.clone());
log.1.notify_all();
let reply = routes.lock().unwrap().get(&path).cloned();
let body = match reply {
Some(Reply::Ok(body)) => body,
@@ -182,22 +192,28 @@ fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &Mutex<
let _ = s.write_all(&body);
}
/// The results until `n` have come, or two seconds.
fn wait_for(previews: &Previews, n: usize) -> Vec<Preview> {
let deadline = Instant::now() + Duration::from_secs(2);
let mut out = Vec::new();
while out.len() < n && Instant::now() < deadline {
out.extend(previews.poll());
std::thread::sleep(Duration::from_millis(5));
}
out
/// How long a test waits for a result or a request before it fails as hung. A result that comes does not depend on it.
const HANG: Duration = Duration::from_secs(10);
/// `previews` and a channel that gets `()` after each result it delivers ([`Previews::on_ready`]).
fn watched(previews: Previews) -> (Previews, Receiver<()>) {
let (ready, results) = channel();
let previews = previews.on_ready(move || {
let _ = ready.send(());
});
(previews, results)
}
fn wait_until(mut done: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(2);
while !done() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
/// The results until `n` have come.
fn wait_for(previews: &Previews, ready: &Receiver<()>, n: usize) -> Vec<Preview> {
let mut out = previews.poll();
while out.len() < n {
if ready.recv_timeout(HANG).is_err() {
panic!("{} of {n} previews came", out.len());
}
out.extend(previews.poll());
}
out
}
#[test]
@@ -209,12 +225,12 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
service.serve(&sample, Reply::Ok(WOFF2.to_vec()));
service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec()));
let previews = Previews::new(store.clone());
let (previews, ready) = watched(Previews::new(store.clone()));
// No service: nothing happens.
assert!(!previews.available());
previews.request(sample.clone(), 1);
let got = wait_for(&previews, 1);
let got = wait_for(&previews, &ready, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService));
// A service, but previews off: no request.
@@ -222,7 +238,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
store.set_previews_enabled(false).unwrap();
assert!(!previews.available());
previews.request(sample.clone(), 1);
let got = wait_for(&previews, 1);
let got = wait_for(&previews, &ready, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff));
assert!(service.requests().is_empty());
@@ -231,7 +247,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
assert!(previews.available() && !store.downloads_allowed());
previews.request(sample.clone(), 1);
previews.request(broken.clone(), 1);
let got = wait_for(&previews, 2);
let got = wait_for(&previews, &ready, 2);
let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone());
assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f)));
assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont)));
@@ -241,9 +257,9 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
// A new session reads the disk cache, even with previews off.
store.set_previews_enabled(false).unwrap();
let later = Previews::new(store.clone());
let (later, later_ready) = watched(Previews::new(store.clone()));
later.request(sample.clone(), 1);
assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f))));
assert!(wait_for(&later, &later_ready, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f))));
assert_eq!(service.requests().len(), 2);
let _ = std::fs::remove_dir_all(dir);
}
@@ -276,9 +292,9 @@ fn a_service_marked_down_gets_no_requests() {
// The client is shared with, say, the store's installs, which found the service unreachable.
let client = Client::default();
client.mark_service_down(&service.base);
let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client));
let (previews, ready) = watched(Previews::new(store.clone()).with_fetcher(Arc::new(client)));
previews.request(key, 1);
let got = wait_for(&previews, 1);
let got = wait_for(&previews, &ready, 1);
assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_)))));
assert!(service.requests().is_empty());
let _ = std::fs::remove_dir_all(dir);
@@ -297,10 +313,10 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() {
for key in [low, high, dropped] {
service.serve(key, Reply::Ok(WOFF2.to_vec()));
}
let previews = Previews::new(store.clone()).with_cache(None).with_workers(1);
let (previews, ready) = watched(Previews::new(store.clone()).with_cache(None).with_workers(1));
previews.request(held.clone(), 9);
wait_until(|| !service.requests().is_empty());
service.wait_for_requests(1);
previews.request(low.clone(), 1);
previews.request(dropped.clone(), 1);
previews.request(high.clone(), 5);
@@ -310,11 +326,12 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() {
// The running request stops while the service still sends nothing.
previews.cancel(held);
let got = wait_for(&previews, 2);
let got = wait_for(&previews, &ready, 2);
assert_eq!(got.iter().map(|p| &p.key).collect::<Vec<_>>(), [high, low]);
let path = |k: &PreviewKey| format!("/{}", k.path());
assert_eq!(service.requests(), [path(held), path(high), path(low)]);
std::thread::sleep(Duration::from_millis(100));
// The one worker delivers in the order it takes requests, and it had ended the held one before it asked for `high`,
// so nothing more can come.
assert!(previews.poll().is_empty());
assert_eq!(previews.pending(), 0);
service.release();
@@ -343,9 +360,9 @@ fn a_404_comes_back_as_not_found() {
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
store.set_preview_service(Some(&service.base)).unwrap();
let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
let previews = Previews::new(store.clone());
let (previews, ready) = watched(Previews::new(store.clone()));
previews.request(key, 1);
let got = wait_for(&previews, 1);
let got = wait_for(&previews, &ready, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound));
let _ = std::fs::remove_dir_all(dir);
}