Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,16 +294,25 @@ fn uninstall_geolibre_language(_s: &mut Session, p: &Value) -> CmdResult {
}

/// Downloads and installs the pinned GeoLibre runner release for this platform; returns the
/// program's path. `progress` gets the bytes received and the expected total. Blocks: the app
/// calls it from a background thread, then picks the runner with `gp.setGeolibre`. Native only.
/// program's path. `progress` gets the bytes received and the expected total. This blocking path
/// serves `gp.installGeolibre` and scripts; the desktop card uses [`install_geolibre_cancellable`]
/// on a background thread. Native only.
pub fn install_geolibre(progress: &dyn Fn(u64, Option<u64>)) -> Result<String, String> {
install_geolibre_cancellable(progress, &std::sync::atomic::AtomicBool::new(false))
}

/// The desktop card's background install path: checks Cancel between download chunks, before
/// extraction and before publication. A blocked HTTP read finishes or times out first. Checksum
/// verification, extraction, runner lookup and version probing have no internal Cancel checks;
/// cancellation waits for those steps to finish.
pub fn install_geolibre_cancellable(progress: &dyn Fn(u64, Option<u64>), cancel: &std::sync::atomic::AtomicBool) -> Result<String, String> {
#[cfg(all(feature = "geolibre", not(target_arch = "wasm32")))]
{
rustgis_geolibre::install::install(progress).map(|p| p.display().to_string())
rustgis_geolibre::install::install_cancellable(progress, cancel).map(|p| p.display().to_string())
}
#[cfg(not(all(feature = "geolibre", not(target_arch = "wasm32"))))]
{
let _ = progress;
let _ = (progress, cancel);
Err("this build can't install the GeoLibre runner".into())
}
}
Expand Down
121 changes: 102 additions & 19 deletions crates/engine/src/grids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,21 @@ pub enum News {
Got { name: String, bytes: usize },
/// A grid couldn't be had, and why.
Failed { name: String, error: String },
/// A contiguous batch ended; failures have their own notices.
Finished { grids: usize, bytes: u64 },
/// News a session asked for too late to hear, counted ([`news_since`]).
Missed(u64),
}

#[derive(Default)]
struct State {
/// Byte counter shared with the download transport, retained until this batch ends.
progress: std::sync::Arc<crate::render::rustgis_tiles::cache::Progress>,
batch_active: bool,
batch_total: usize,
batch_done: usize,
batch_got: usize,
batch_bytes: u64,
/// Grids being downloaded now.
busy: HashSet<String>,
/// Grids whose download failed this run: not tried again until the setting is turned on again.
Expand Down Expand Up @@ -104,6 +113,37 @@ impl State {
out
}

/// Records a settled download before waking readers, including its final batch summary.
fn finish(&mut self, name: &str, outcome: Result<usize, String>) {
self.busy.remove(name);
self.batch_done += 1;
match outcome {
Ok(bytes) => {
self.bytes += bytes;
self.batch_got += 1;
self.batch_bytes += bytes as u64;
self.got.insert(name.to_string());
self.tell(News::Got { name: name.to_string(), bytes });
}
Err(error) => {
self.failed.insert(name.to_string());
self.tell(News::Failed { name: name.to_string(), error });
}
}
self.running = self.running.saturating_sub(1);
self.finish_batch();
}

/// Ends a batch only after every queued or running grid has settled.
fn finish_batch(&mut self) {
if self.batch_active && self.busy.is_empty() {
self.batch_active = false;
if self.batch_got > 0 {
self.tell(News::Finished { grids: self.batch_got, bytes: self.batch_bytes });
}
}
}

/// The setting turned on: this run's failures are tried again, and the limits start over.
fn turned_on(&mut self) {
self.turns += 1;
Expand Down Expand Up @@ -159,6 +199,13 @@ pub fn enabled() -> bool {
ENABLED.load(Ordering::SeqCst)
}

/// Current batch progress: settled grids, total grids, bytes received, and whether it is active.
/// Native downloads count bytes as they arrive; browser downloads count them on completion.
pub fn progress() -> (usize, usize, u64, bool) {
let s = lock();
(s.batch_done, s.batch_total, s.progress.received().max(s.batch_bytes), s.batch_active)
}

/// How many times downloads were turned on this run: a download said before is said again after.
pub fn turns() -> u64 {
lock().turns
Expand Down Expand Up @@ -260,6 +307,7 @@ fn next() {
let Some(grid) = grid else { break };
start(grid);
}
lock().finish_batch();
// Those dropped or refused on the way: their waiters see it.
state().1.notify_all();
}
Expand Down Expand Up @@ -312,6 +360,15 @@ impl State {
self.tell(News::Failed { name: name.to_string(), error });
return Claim::Settled;
}
if !self.batch_active {
self.batch_active = true;
self.batch_total = 0;
self.batch_done = 0;
self.batch_got = 0;
self.batch_bytes = 0;
self.progress = Default::default();
}
self.batch_total += 1;
self.started += 1;
self.busy.insert(name.to_string());
Claim::Mine
Expand All @@ -326,8 +383,10 @@ impl State {
if !on {
self.busy.remove(&grid.name);
self.started = self.started.saturating_sub(1);
self.batch_total = self.batch_total.saturating_sub(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new batch test covers success and failure accounting, but no assertion checks the batch counters on the two paths that change them without a download finishing: this line (the setting turned off with grids still queued), and the 2 GB refusal in the branch just below (batch_done += 1). Both decide when News::Finished is told and what the Settings progress shows, and the public progress() (line 204) has no test at all. A short test that calls take_next(false) with a queued grid, and take_next(true) with bytes = MAX_BYTES, then asserts (batch_total, batch_done, batch_active) would pin them.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving these additional batch-counter and progress() assertions for the release quality pass. The existing limit/setting test exercises both queued-grid refusal and dropping; their new counter values are not asserted. I found no incorrect accounting on those paths, so this is a coverage addition rather than a demonstrated defect.

} else if self.bytes >= MAX_BYTES {
self.busy.remove(&grid.name);
self.batch_done += 1;
self.failed.insert(grid.name.clone());
self.tell(News::Failed { name: grid.name, error: limit_text() });
} else {
Expand Down Expand Up @@ -365,19 +424,7 @@ fn limit_text() -> String {
/// Records how `name`'s download went, and wakes those waiting for it.
fn finish(name: &str, outcome: Result<usize, String>) {
let mut s = lock();
s.busy.remove(name);
match outcome {
Ok(bytes) => {
s.bytes += bytes;
s.got.insert(name.to_string());
s.tell(News::Got { name: name.to_string(), bytes });
}
Err(error) => {
s.failed.insert(name.to_string());
s.tell(News::Failed { name: name.to_string(), error });
}
}
s.running = s.running.saturating_sub(1);
s.finish(name, outcome);
drop(s);
state().1.notify_all();
rustgis_map::source::wake();
Expand Down Expand Up @@ -545,7 +592,8 @@ fn start(grid: MissingGrid) {
fn fetch_now(grid: &MissingGrid) {
let got = std::panic::catch_unwind(|| {
let download = *download().read().unwrap_or_else(|e| e.into_inner());
let bytes = download(&grid.url, MAX_GRID, DOWNLOAD_TIMEOUT)?;
let progress = lock().progress.clone();
let bytes = crate::render::rustgis_tiles::cache::with_progress(Some(progress), || download(&grid.url, MAX_GRID, DOWNLOAD_TIMEOUT))?;
keep(&grid.name, &bytes).map(|()| bytes.len())
})
.unwrap_or_else(|payload| Err(crate::bug("the download", payload.as_ref())));
Expand Down Expand Up @@ -634,8 +682,8 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> {
let mut count = 0;
for n in news {
match n {
News::Missed(_) => {}
News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes))),
News::Missed(_) | News::Finished { .. } => {}
News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes as u64))),
News::Failed { name, error } => {
count += 1;
match why.iter_mut().find(|(e, _)| e == error) {
Expand Down Expand Up @@ -683,15 +731,44 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> {
out
}

fn size_text(bytes: usize) -> String {
let mb = bytes as f64 / 1_000_000.0;
if mb >= 1.0 { format!("{mb:.1} MB") } else { format!("{} KB", bytes.div_ceil(1000)) }
/// Download sizes in decimal units; rounding small amounts up keeps received bytes visible.
/// Accepts the batch counters directly without narrowing them through `usize`.
pub fn size_text(bytes: u64) -> String {
let kb = bytes.div_ceil(1000);
if kb < 1000 { format!("{kb} KB") } else { format!("{:.1} MB", bytes as f64 / 1_000_000.0) }
}

#[cfg(test)]
mod tests {
use super::*;

/// A completion is emitted once per batch, after its last grid settles, with only
/// successfully retained bytes counted; a later batch starts with fresh counters.
#[test]
fn batch_summary_waits_for_all_grids_and_counts_successes() {
let mut s = State::default();
assert!(matches!(s.claim("a.tif", true), Claim::Mine));
assert!(matches!(s.claim("b.tif", true), Claim::Mine));
s.finish("a.tif", Ok(123_456));
assert_eq!(s.news_since(&mut 0), [News::Got { name: "a.tif".into(), bytes: 123_456 }]);
s.finish("b.tif", Err("HTTP 404".into()));
s.finish_batch();
assert_eq!(
s.news_since(&mut 0),
[
News::Got { name: "a.tif".into(), bytes: 123_456 },
News::Failed { name: "b.tif".into(), error: "HTTP 404".into() },
News::Finished { grids: 1, bytes: 123_456 }
]
);
assert!(!s.batch_active);
assert!(matches!(s.claim("c.tif", true), Claim::Mine));
assert_eq!((s.batch_total, s.batch_done, s.batch_got, s.batch_bytes), (1, 0, 0, 0));
let mut seen = s.told;
s.finish("c.tif", Err("HTTP 404".into()));
assert_eq!(s.news_since(&mut seen), [News::Failed { name: "c.tif".into(), error: "HTTP 404".into() }]);
}

#[test]
fn only_plain_names_are_kept() {
assert!(plain("us_noaa_conus.tif"));
Expand Down Expand Up @@ -828,5 +905,11 @@ mod tests {
);
assert_eq!(said[0].0.matches("at most 16").count(), 1, "{said:?}");
assert_eq!(size_text(12_345_678), "12.3 MB");
assert_eq!(size_text(13_442), "14 KB");
assert_eq!(size_text(999_000), "999 KB");
assert_eq!(size_text(999_999), "1.0 MB");
assert_eq!(size_text(1), "1 KB");
assert_eq!(size_text(0), "0 KB");
assert_eq!(size_text(5_000_000_000), "5000.0 MB");
}
}
9 changes: 9 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3002,6 +3002,15 @@ impl Session {
self.notify(text, error);
}
for n in &news {
if let crate::grids::News::Finished { grids, bytes } = n {
self.notify_text(
crate::notice_text::NoticeText::format(
if *grids == 1 { "Downloaded {count} datum grid, {size}" } else { "Downloaded {count} datum grids, {size}" },
[("count", grids.to_string().into()), ("size", crate::grids::size_text(*bytes).into())],
),
false,
);
Comment on lines +3006 to +3012

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The batch total is always printed as {:.1} MB, so a batch under 50 KB reads as 0.0 MB. The test grid is 13,442 bytes, so Downloaded 1 datum grid, 0.0 MB is what a user would see. The per-grid notices already use size_text (grids.rs), which switches to KB below 1 MB. Reuse it here so the two notices agree. This needs size_text in crates/engine/src/grids.rs made pub(crate), which the suggestion assumes.

Suggested change
self.notify_text(
crate::notice_text::NoticeText::format(
if *grids == 1 { "Downloaded {count} datum grid, {mb} MB" } else { "Downloaded {count} datum grids, {mb} MB" },
[("count", grids.to_string().into()), ("mb", format!("{:.1}", *bytes as f64 / 1_000_000.0).into())],
),
false,
);
self.notify_text(
crate::notice_text::NoticeText::format(
if *grids == 1 { "Downloaded {count} datum grid, {size}" } else { "Downloaded {count} datum grids, {size}" },
[("count", grids.to_string().into()), ("size", crate::grids::size_text(*bytes as usize).into())],
),
false,
);

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5eb352f. Per-grid notices, completion notices, the Settings ribbon and the install card share the existing decimal size formatter, now taking u64 so totals stay wide on 32-bit builds. A 13,442-byte completion reads 14 KB. The grid integration covers singular/plural session notices; zero-success batches produce no completion. Restoring the old summary formatting makes the regression fail. Fork CI passed.

}
// Its download is over: one tried again (the setting turned on again) is said again.
if let crate::grids::News::Got { name, .. } | crate::grids::News::Failed { name, .. } = n {
self.grid_downloads_said.remove(name);
Expand Down
32 changes: 31 additions & 1 deletion crates/engine/tests/datum_grid_downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ fn a_read_waits_for_the_grids_its_system_needs() {
assert_eq!(ASKED.load(Ordering::SeqCst), 0);

// On: the read gets both grids first, keeps them, and its features land where they put them.
let mut download_notices = Session::new(Project::default());
grids::set_enabled(true);
let t = crs::waiting_for_grids(|| texas.transformer()).unwrap();
assert!(close(t.to_lonlat(at).unwrap(), (-99.00031395482138, 29.208749002954207)), "{:?}", t.to_lonlat(at));
Expand All @@ -80,9 +81,23 @@ fn a_read_waits_for_the_grids_its_system_needs() {
news.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
assert_eq!(
news,
[News::Got { name: "us_noaa_conus.tif".into(), bytes: 173_029 }, News::Got { name: "us_noaa_ethpgn.tif".into(), bytes: 13_442 }]
[
News::Finished { grids: 2, bytes: 186_471 },
News::Got { name: "us_noaa_conus.tif".into(), bytes: 173_029 },
News::Got { name: "us_noaa_ethpgn.tif".into(), bytes: 13_442 }
]
);
assert!(crs::missing_grids(texas).is_empty());
download_notices.notice_landed_rasters();
assert_eq!(
download_notices
.notices
.iter()
.filter(|n| n.text.starts_with("Downloaded 2 datum grids"))
.map(|n| (n.text.as_str(), n.error))
.collect::<Vec<_>>(),
[("Downloaded 2 datum grids, 187 KB", false)]
);
// Read again, nothing more is asked for.
let _ = crs::waiting_for_grids(|| texas.transformer()).unwrap();
assert_eq!(ASKED.load(Ordering::SeqCst), 2);
Expand Down Expand Up @@ -238,4 +253,19 @@ fn a_read_waits_for_the_grids_its_system_needs() {
}
grids::set_enabled(false);
MODE.store(GRIDS, Ordering::SeqCst);
// This binary owns the process-wide grid news: exercise a small singular completion through
// the real session landing, once despite repeated frames, without another network request.
let mut summary = Session::new(Project::default());
grids::tell(News::Finished { grids: 1, bytes: 13_442 });
summary.notice_landed_rasters();
summary.notice_landed_rasters();
assert_eq!(
summary
.notices
.iter()
.filter(|n| n.text.starts_with("Downloaded 1 datum grid"))
.map(|n| (n.text.as_str(), n.error))
.collect::<Vec<_>>(),
[("Downloaded 1 datum grid, 14 KB", false)]
);
}
Loading
Loading