Skip to content
Merged
85 changes: 71 additions & 14 deletions crates/engine/src/cmd/cube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,14 @@ pub struct TrendRun {
}

impl TrendRun {
/// About the bytes its four outputs hold once made, with their GeoTIFFs: all of them, for a
/// cube that knows its size, as the run doesn't cap its outputs (only its pairs); when it
/// doesn't, those of a block of [`MAX_VALUES`] cells.
pub fn output_bytes(&self) -> u64 {
let cells = self.cube.size().map_or(MAX_VALUES, |(w, h)| (w as u64).saturating_mul(h as u64));
output_bytes(cells.saturating_mul(OUTPUTS as u64))
}

/// The work, for a progress bar: the slices read (every piece's), then the cells worked out,
/// in [`CELL_PARTS`] parts.
pub fn total(&self) -> usize {
Expand Down Expand Up @@ -1108,6 +1116,14 @@ fn trend_cmd(s: &mut Session, p: &Value) -> CmdResult {
let (_, rasters, dates) = s.trend_results.remove(at);
return add_outputs(s, rasters, dates);
}
// A plugin's command the app runs reads a STAC collection off the frame (#3183), with the
// panes' bound, as the Workflows pane's thread does.
if let Some(left) = super::plugins::summary::left(s, "cube.trend", p, |s| {
let run = trend_start(s, p)?;
Ok(super::plugins::summary::Work::new(run.total(), run.dates(), run.output_bytes(), move |cancel, done| run.run(cancel, done)))
}) {
return left;
}
// Worked out here, waited for with no Cancel: in the app (a script, the assistant) and Python a
// run of seconds, not minutes; where only a shell waits on it (`rustgis-cli run`), the panes'
// bound, its progress told.
Expand Down Expand Up @@ -1212,30 +1228,53 @@ fn run_telling<T: Send>(
})
}

/// About the bytes `values` output cells hold as a raster (4 bytes each) and as its GeoTIFF.
fn output_bytes(values: u64) -> u64 {
values.saturating_mul(8)
}

/// Adds a trend's (or a summary's) layers, each as a GeoTIFF the project keeps.
pub fn add_outputs(s: &mut Session, rasters: Vec<Raster>, dates: usize) -> CmdResult {
let mut layers = Vec::new();
for r in rasters {
let name = r.name.clone();
let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect();
let named = class_values(&r);
let mut layer = rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif);
// Named classes (firstDate's dates): a colour each for every value held, from the
// earliest, labelled by its name (a day before 1970, unnamed, by its number).
if !named.is_empty() && named.len() <= rustgis_map::raster::MAX_UNIQUE_VALUES {
let ramp = rustgis_map::color::Ramp::Viridis;
let values = named.iter().enumerate().map(|(k, v)| (*v, ramp.pick(k, named.len()))).collect();
layer.style.renderer = rustgis_map::raster::RasterRenderer::UniqueValues { band: 0, ramp, values };
layer.style.stretch = rustgis_map::raster::Stretch::None;
layer.style.resampling = rustgis_map::raster::Resampling::Nearest;
}
let (name, layer) = output_layer(r)?;
let out = super::raster::add_raster(s, &name, layer)?;
layers.push(out["layer"].clone());
}
Ok(json!({ "layers": layers, "dates": dates }))
}

/// A trend's (or a summary's) output as the layer it adds, with its name: its GeoTIFF written, so
/// it is made on any thread.
pub(crate) fn output_layer(r: Raster) -> Result<(String, rustgis_map::raster::RasterLayer), String> {
let name = r.name.clone();
let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect();
let named = class_values(&r);
let mut layer = rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif);
// Named classes (firstDate's dates): a colour each for every value held, from the
// earliest, labelled by its name (a day before 1970, unnamed, by its number).
if !named.is_empty() && named.len() <= rustgis_map::raster::MAX_UNIQUE_VALUES {
let ramp = rustgis_map::color::Ramp::Viridis;
let values = named.iter().enumerate().map(|(k, v)| (*v, ramp.pick(k, named.len()))).collect();
layer.style.renderer = rustgis_map::raster::RasterRenderer::UniqueValues { band: 0, ramp, values };
layer.style.stretch = rustgis_map::raster::Stretch::None;
layer.style.resampling = rustgis_map::raster::Resampling::Nearest;
}
Ok((name, layer))
}

/// Adds layers [`output_layer`] made (a summary read off the frame, #3183), sharing their pixels
/// and GeoTIFFs with whatever holds them.
pub(crate) fn add_output_layers(s: &mut Session, made: &[(String, rustgis_map::raster::RasterLayer)], dates: usize) -> CmdResult {
let mut layers = Vec::new();
for (name, layer) in made {
let out = super::raster::add_raster(s, name, layer.clone())?;
layers.push(out["layer"].clone());
}
Ok(json!({ "layers": layers, "dates": dates }))
}

/// The values held by a raster's first band when it names its classes (firstDate's dates), in
/// order, named or not; none when it names none. Only distinct values are kept, and no more than
/// one past what a Unique Values renderer draws, so a large layer of few dates takes no copy of
Expand Down Expand Up @@ -1803,6 +1842,17 @@ pub struct ReduceRun {
}

impl ReduceRun {
/// About the bytes its outputs hold once made, with their GeoTIFFs: a band for each group and
/// asset (firstDate's one date for all the assets, as [`ReduceRun::run`] makes them); the most
/// a run can make ([`MAX_REDUCED`] values) when the cube doesn't know its size, or for
/// frequency, whose classes aren't known before it is read.
pub fn output_bytes(&self) -> u64 {
let per = if self.stat == Stat::FirstDate { 1 } else { self.cube.assets().len().max(1) };
let slots = (self.groups.len() * per) as u64;
let cells = self.cube.size().filter(|_| self.stat != Stat::Frequency).map(|(w, h)| (w as u64).saturating_mul(h as u64));
output_bytes(cells.map_or(MAX_REDUCED, |c| c.saturating_mul(slots).min(MAX_REDUCED)))
}

/// The work, for a progress bar: the slices read, every piece's, and the dates' clear shares
/// when first takes them in that order.
pub fn total(&self) -> usize {
Expand Down Expand Up @@ -2470,6 +2520,13 @@ pub fn reduce_start(s: &mut Session, p: &Value) -> Result<ReduceRun, String> {
/// `cube.reduce`: the summary computed here (blocking), its progress told where only a shell waits
/// on it (`rustgis-cli run`), its layers added, each kept in the project as a GeoTIFF.
fn reduce_cmd(s: &mut Session, p: &Value) -> CmdResult {
// A plugin's command the app runs reads a STAC collection off the frame (#3183).
if let Some(left) = super::plugins::summary::left(s, "cube.reduce", p, |s| {
let run = reduce_start(s, p)?;
Ok(super::plugins::summary::Work::new(run.total(), run.dates(), run.output_bytes(), move |cancel, done| run.run(cancel, done)))
}) {
return left;
}
let run = reduce_start(s, p)?;
let rasters = run_here(s.long_runs, "cube.reduce", run.total(), |cancel, done| run.run(cancel, done))?;
let added = add_outputs(s, rasters, run.dates());
Expand Down
45 changes: 36 additions & 9 deletions crates/engine/src/cmd/plugin_fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
//!
//! A plugin command's `service.add` on the desktop waits the same way (#1319): the documents it
//! reads are fetched off the frame ([`Session::left_document`]), and its features or coverage are
//! left to the app as `layer.addUrl`'s download is.
//! left to the app as `layer.addUrl`'s download is. So does its `cube.reduce` or `cube.trend` on a
//! STAC collection (#3183): the slices are read on a thread of the session's (see
//! [`super::summary`]).

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
Expand Down Expand Up @@ -435,7 +437,7 @@ pub(crate) struct UrlWaits {
pub(crate) views: std::collections::BTreeMap<u64, [f64; 4]>,
owners: std::collections::BTreeMap<u64, crate::policy::Continuation>,
in_flight: Vec<(u64, Value, Instant)>,
landed: Vec<(u64, Value, CmdResult, Added)>,
pub(super) landed: Vec<(u64, Value, CmdResult, Added)>,
/// Requests given up (past [`REQUEST_WAIT`], or their command replaced or dropped), with their
/// addresses (about [`MAX_EXPIRED`] at most, see `remember_given_up`): one that lands after is
/// refused, not added with no command left to go on with it.
Expand All @@ -446,6 +448,8 @@ pub(crate) struct UrlWaits {
added: VecDeque<(u64, Value)>,
/// A service's documents being read off the frame, by request number.
reading: Vec<(u64, String, Arc<Mutex<Option<Result<Vec<u8>, String>>>>)>,
/// Data cubes' summaries being read off the frame ([`super::summary`]).
pub(super) summaries: Vec<super::summary::Reading>,
}

/// What adding a landed download added, to tell when its command runs again whether it is still
Expand All @@ -463,6 +467,8 @@ pub(crate) struct Added {
pub(crate) map: u64,
/// A service's document read off the frame ([`Session::left_document`]), which adds nothing.
pub(crate) document: Option<Arc<[u8]>>,
/// A data cube's summary read off the frame ([`super::summary`]), which its command adds.
pub(crate) summary: Option<super::summary::Summary>,
}

impl Added {
Expand All @@ -482,7 +488,12 @@ impl Added {
(None, Some(i)) => usize::try_from(i).ok().and_then(|i| map.tiles.get(i)).cloned().into_iter().collect(),
_ => Vec::new(),
};
Added { layers, tiles, map: at, document: None }
Added { layers, tiles, map: at, document: None, summary: None }
}

/// What a data cube's summary read off the frame made: no layer yet, its command adds them.
pub(super) fn of_summary(summary: super::summary::Summary) -> Added {
Added { summary: Some(summary), ..Added::default() }
}

/// `answer` as it stands in `map` now: a tile layer's place in the list, which moves as others
Expand Down Expand Up @@ -551,6 +562,10 @@ const MAX_EXPIRED: usize = 1024;
/// the address the front end downloads, with the range marked in it
/// ([`crate::cmd::layer::ranged_address`]), and its rows of a box (`"bbox"`) with the box too.
fn asked_by(asked: &Value, params: &Value) -> bool {
// A summary read off the frame has no address: no front end's download is it.
if super::summary::is_summary(asked) {
return false;
}
let Some(o) = asked.as_object() else { return false };
let range = match asked.get("bytes").and_then(Value::as_array).map(Vec::as_slice) {
Some([a, b]) => a.as_u64().zip(b.as_u64()),
Expand Down Expand Up @@ -633,8 +648,8 @@ impl UrlWaits {
pub(crate) fn land(&mut self, n: u64, answer: CmdResult, added: Added) {
if let Some(i) = self.in_flight.iter().position(|(m, ..)| *m == n) {
let (_, asked, _) = self.in_flight.remove(i);
// (A document adds nothing, and no front end lands it again by its number.)
if answer.is_ok() && added.document.is_none() {
// (A document or a summary adds nothing, and no front end lands it again by its number.)
if answer.is_ok() && added.document.is_none() && added.summary.is_none() {
if self.added.len() >= MAX_EXPIRED {
self.added.pop_front();
}
Expand All @@ -650,7 +665,7 @@ impl UrlWaits {
}

/// Waits for request `n`, which asked for `asked`.
fn wait(&mut self, n: u64, asked: Value) {
pub(super) fn wait(&mut self, n: u64, asked: Value) {
if !self.has(n) {
self.in_flight.push((n, asked, Instant::now()));
}
Expand All @@ -663,7 +678,8 @@ impl UrlWaits {
let late: Vec<(u64, Value)> = self
.in_flight
.iter()
.filter(|(.., at)| now.saturating_duration_since(*at) >= REQUEST_WAIT)
// A summary still being read has its own end, and its Cancel.
.filter(|(n, _, at)| now.saturating_duration_since(*at) >= REQUEST_WAIT && !self.summarising(*n))
.map(|(n, q, _)| (*n, q.clone()))
.collect();
let mut addresses = Vec::new();
Expand All @@ -679,6 +695,9 @@ impl UrlWaits {
/// so a late landing is refused.
/// `taken`: whether the front end took it (it may still land); one it didn't is just forgotten.
fn give_up(&mut self, n: u64, taken: bool) {
// A summary being read is stopped, and never lands: there is nothing to refuse later.
let taken = taken && !self.summarising(n);
self.stop_summaries(|m| m != n);
if let Some(i) = self.in_flight.iter().position(|(m, ..)| *m == n) {
let (_, asked, _) = self.in_flight.remove(i);
if taken {
Expand Down Expand Up @@ -760,6 +779,7 @@ impl UrlWaits {
self.in_flight.retain(|(n, ..)| wanted(n));
self.landed.retain(|(n, ..)| wanted(n));
self.views.retain(|n, _| wanted(n));
self.stop_summaries(|n| wanted(&n));
let retained: Vec<u64> = self
.in_flight
.iter()
Expand Down Expand Up @@ -970,8 +990,14 @@ impl Session {
if !fetching.is_empty() {
answer["fetching"] = json!(fetching);
}
if !requests.is_empty() {
answer["downloading"] = json!(requests.iter().map(|(_, q)| q["url"].as_str().map(crate::sources::redact)).collect::<Vec<_>>());
let (summaries, downloads): (Vec<&(u64, Value)>, Vec<&(u64, Value)>) =
requests.iter().partition(|(_, q)| super::summary::is_summary(q));
if !downloads.is_empty() {
answer["downloading"] = json!(downloads.iter().map(|(_, q)| q["url"].as_str().map(crate::sources::redact)).collect::<Vec<_>>());
}
// A summary read off the frame, by its command's name.
if !summaries.is_empty() {
answer["reading"] = json!(summaries.iter().map(|(_, q)| q["summary"].clone()).collect::<Vec<_>>());
}
let numbers = requests.iter().map(|(n, _)| *n).collect();
for (n, asked) in requests {
Expand Down Expand Up @@ -1053,6 +1079,7 @@ impl Session {
/// by then are given up (a test passes a later time instead of backdating the waits).
fn poll_plugin_retries_at(&mut self, now: Instant) -> Vec<(String, CmdResult)> {
self.url_waits.documents_in();
self.url_waits.summaries_in();
if self.plugin_retries.is_empty() {
self.url_waits.prune_views();
return Vec::new();
Expand Down
Loading
Loading