diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index b33373564e..8e3f8a9078 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), @@ -5339,7 +5339,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { // With a box (`"bbox"`, #3055), only the record's headers and the rows of the box. A `false` // is no box, as [`byte_range`] reads it. #[cfg(not(target_arch = "wasm32"))] - if ["bytes", "bbox"].iter().all(|k| p.get(*k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { + if asks_rows(p) { return add_url_rows(s, p, url, public); } #[cfg(not(target_arch = "wasm32"))] @@ -5348,8 +5348,9 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { } #[cfg(target_arch = "wasm32")] byte_range(p, url)?; - // A window of a cloud-optimised GeoTIFF, read as a raster (opengeos/RustGIS#1204). - let window = p.get("bbox").is_some_and(|v| !v.is_null()); + // A window of a cloud-optimised GeoTIFF, read as a raster (opengeos/RustGIS#1204). A `false` + // box is no box, as with a range ([`asks_rows`]). + let window = p.get("bbox").is_some_and(|v| !v.is_null() && v.as_bool() != Some(false)); if !window && p.get("cellSize").is_some_and(|v| !v.is_null()) { return Err(format!("{url}: \"cellSize\" goes with \"bbox\": give a box, or leave it out")); } @@ -5528,18 +5529,10 @@ pub const MAX_RANGE: u64 = 64 << 20; /// The range `layer.addUrl` is asked for (`"bytes": [first, last]`, octets counted from 0, both /// included, as HTTP's `Range` writes them), checked: of a GRIB file only (by its address's name, /// or `"format": "grib"`), at most [`MAX_RANGE`], and with nothing that reads an address another -/// way. `None` without `"bytes"`. The browser refuses it: a range from another site needs that -/// site's leave (CORS), which comes in a later part. +/// way. A box (`"bbox"`) may come with it: then only the rows of the box are read ([`asks_rows`]). +/// `None` without `"bytes"`. The browser refuses it: a range from another site needs that site's +/// leave (CORS), which comes in a later part. pub fn byte_range(p: &Value, url: &str) -> Result, String> { - range_asked(p, url, false) -} - -/// What `"bbox"` with `"bytes"` says where the rows of a box aren't read yet: the app, whose -/// downloads run off the frame, and a plugin's command there. -const ROWS_ELSEWHERE: &str = "\"bbox\" with \"bytes\" (the rows of a box of a GRIB record) is read on the command line for now, not in the app yet: leave \"bbox\" out to read the whole record"; - -/// [`byte_range`], `rows` being whether a box may come with the range ([`add_url_rows`]). -fn range_asked(p: &Value, url: &str, rows: bool) -> Result, String> { let grib = match p.get("format") { None | Some(Value::Null) => false, Some(Value::String(f)) if f.trim().eq_ignore_ascii_case("grib") => true, @@ -5577,11 +5570,8 @@ fn range_asked(p: &Value, url: &str, rows: bool) -> Result, S if cfg!(target_arch = "wasm32") { return Err("\"bytes\" works on the desktop and the command line for now: in the browser, a range from another site needs that site's leave (CORS)".into()); } - let other = ["bbox", "cellSize", "as", "service", "coverage", "cube", "cog", "whole", "dates"]; - if let Some(k) = other.iter().skip(usize::from(rows)).find(|k| p.get(**k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { - if *k == "bbox" { - return Err(ROWS_ELSEWHERE.into()); - } + let other = ["cellSize", "as", "service", "coverage", "cube", "cog", "whole", "dates"]; + if let Some(k) = other.iter().find(|k| p.get(**k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { return Err(format!("\"bytes\" doesn't go with \"{k}\": a range is downloaded and read as a GRIB file")); } if rustgis_data::time::is_template(url) { @@ -5590,6 +5580,12 @@ fn range_asked(p: &Value, url: &str, rows: bool) -> Result, S Ok(Some((first, last))) } +/// Whether `p` asks for the rows of a box of a GRIB record (`"bytes"` with `"bbox"`, #3055): both +/// given, neither `false` (a `false` box is no box). +pub fn asks_rows(p: &Value) -> bool { + ["bytes", "bbox"].iter().all(|k| p.get(*k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) +} + /// The address a range is downloaded from: `url` with the range the fetchers send as `Range` /// ([`cache::RANGE`]); its reach is the address's own. /// @@ -5659,21 +5655,34 @@ fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), publi super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named) } -/// Adds the rows of a box of a GRIB record (`"bytes"` with `"bbox"`, #3055), on the command line: -/// the record's first octets ([`grib::HEAD`]), then one range for the rows of the box, cut to its -/// columns. A record that can't be read by rows ([`grib::Plan::Whole`]) is downloaded whole and -/// cut to the same box, and a notice says why. The layer keeps the box's cells as a GeoTIFF, as a -/// window of a cloud-optimised one does. Each request waits at most -/// [`cache::BLOCKING_TIMEOUT`], without a look at Cancel, as [`add_url_range`]'s one does. -/// -/// [`grib::HEAD`]: rustgis_data::raster::grib::HEAD -/// [`grib::Plan::Whole`]: rustgis_data::raster::grib::Plan::Whole -/// [`cache::BLOCKING_TIMEOUT`]: crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT +/// Adds the rows of a box of a GRIB record (`"bytes"` with `"bbox"`, #3055), read here +/// ([`read_grib_rows_until`]) on the command line. A plugin's command on the desktop leaves them to +/// the app, which reads them off the frame as it reads a window of a cloud-optimised GeoTIFF +/// ([`read_cog_window_until`]), with Cancel: the request keeps the range and the box, by which the +/// command run again is answered. #[cfg(not(target_arch = "wasm32"))] fn add_url_rows(s: &mut Session, p: &Value, url: &str, public: bool) -> CmdResult { - use crate::render::rustgis_tiles::cache; - use rustgis_data::raster::grib; - let Some(range) = range_asked(p, url, true)? else { return Err("\"bbox\" with \"bytes\" needs the range".into()) }; + let settled = rows_settled(s, p, url, None, public)?; + if s.leave_downloads { + let mut asked = p.clone(); + asked["url"] = json!(url); + // `"view"` is the view now, as for a window ([`window_settled`]). + s.window_view = is_view(p.get("bbox")).then_some(settled.bbox); + let queued = s.request_url(&asked); + s.window_view = None; + return queued; + } + let read = read_cog_window(&settled)?; + add_window(s, p, read) +} + +/// The rows of a box of a GRIB record (`p`, a `layer.addUrl` with `"bytes"` and `"bbox"`), checked +/// on the frame, which holds the view (`"view"` is `seen` when given): what [`read_grib_rows_until`] +/// needs, on any thread. `public`: the address may reach only the internet (a plugin's). +#[cfg(not(target_arch = "wasm32"))] +fn rows_settled(s: &Session, p: &Value, url: &str, seen: Option<[f64; 4]>, public: bool) -> Result { + use crate::render::rustgis_tiles::{address::Reach, cache}; + let Some(range) = byte_range(p, url)? else { return Err("\"bbox\" with \"bytes\" needs the range".into()) }; // The keys of other kinds of address, which a window doesn't read either ([`window_checks`]). let unread: Vec<&str> = WINDOW_UNREAD.iter().copied().filter(|k| p.get(*k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))).collect(); @@ -5684,20 +5693,45 @@ fn add_url_rows(s: &mut Session, p: &Value, url: &str, public: bool) -> CmdResul if side(0).zip(side(2)).is_some_and(|(west, east)| west > east) { return Err("\"bbox\": a box across the antimeridian (west greater than east) isn't read from a GRIB record yet: give one box on each side of it".into()); } - let bbox = window_box(s, p, None)?; - if s.leave_downloads { - return Err(ROWS_ELSEWHERE.into()); - } + let bbox = window_box(s, p, seen)?; + let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(String::from); + let public = public || cache::ceiling_for(url) == Reach::Public; + Ok(WindowAsked { url: url.to_string(), bbox, cell: None, name, bands: None, auto_cell: false, rows: Some(RowsAsked { range, public }) }) +} + +/// Reads the rows of a box of a GRIB record ([`rows_settled`]): the record's first octets +/// ([`grib::HEAD`]), then one range for the rows of the box, cut to its columns. A record that +/// can't be read by rows ([`grib::Plan::Whole`]) is downloaded whole and cut to the same box, and a +/// note says why. The layer keeps the box's cells as a GeoTIFF, as a window of a cloud-optimised +/// one does. Each request waits at most [`cache::BLOCKING_TIMEOUT`]. `stop` (the app's Cancel, or +/// its project closed) is looked at before each request; the app also stops a transfer under way +/// at its next bytes (the request's `Still`). Needs no [`Session`]. +/// +/// [`grib::HEAD`]: rustgis_data::raster::grib::HEAD +/// [`grib::Plan::Whole`]: rustgis_data::raster::grib::Plan::Whole +/// [`cache::BLOCKING_TIMEOUT`]: crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT +#[cfg(not(target_arch = "wasm32"))] +fn read_grib_rows_until(asked: &WindowAsked, rows: &RowsAsked, stop: &std::sync::atomic::AtomicBool) -> Result { + use crate::render::rustgis_tiles::{cache, cog}; + use rustgis_data::raster::grib; + let url = asked.url.as_str(); + let (range, bbox) = (rows.range, asked.bbox); let named = |e: String| crate::sources::message_with_address(url, &e); - let public = public || cache::ceiling_for(url) == crate::render::rustgis_tiles::address::Reach::Public; let fetch = |first: u64, last: u64| -> Result, String> { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + return Err(named(cog::STOPPED.to_string())); + } let ranged = ranged_address(url, (first, last)); let len = usize::try_from(last - first + 1).unwrap_or(usize::MAX); - let bytes = if public { + let bytes = if rows.public { cache::download_public_within(&ranged, len, cache::BLOCKING_TIMEOUT) } else { cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) }; + // A transfer cut short by Cancel is said as stopped, whatever its own error. + if bytes.is_err() && stop.load(std::sync::atomic::Ordering::Relaxed) { + return Err(named(cog::STOPPED.to_string())); + } let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(named)?; if bytes.len() != len { return Err(named(format!("the server answered {} octets of the {len} asked for (octets {first} to {last})", bytes.len()))); @@ -5734,11 +5768,9 @@ fn add_url_rows(s: &mut Session, p: &Value, url: &str, public: bool) -> CmdResul } }; let bytes = rustgis_data::raster::geotiff::write_all(&r).map_err(data)?; - let title = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(stem).to_string(); + let name = asked.name.clone().unwrap_or_else(|| stem.to_string()); let layer = rustgis_map::RasterLayer::from_written(r, format!("{stem}.tif"), bytes); - let added = super::raster::add_raster_after(s, &title, layer, b(p, "zoom")).map_err(named)?; - s.notify(format!("{title}: {note}"), false); - Ok(added) + Ok(CogWindow { name, layer, notes: vec![note], answer: None }) } /// Whether a Shapefile's part other than its `.dbf` can be done without: it isn't there (404 or @@ -6438,6 +6470,16 @@ pub struct WindowAsked { /// Whether `cell` was worked out by the caller (not asked for by the user): a window whose full /// image has finer cells than it is the intended read, not something to say. auto_cell: bool, + /// The rows of a box of a GRIB record's range instead (`"bytes"` with `"bbox"`, #3055). + rows: Option, +} + +/// A GRIB record's range whose rows of a box are read ([`read_grib_rows_until`]). +#[cfg(not(target_arch = "wasm32"))] +struct RowsAsked { + range: (u64, u64), + /// Whether its requests may reach only the internet (a plugin's). + public: bool, } #[cfg(not(target_arch = "wasm32"))] @@ -6447,7 +6489,7 @@ impl WindowAsked { /// with that box and `"cellSize"` reads it; a file without `bands` bands is refused from its /// header. pub(crate) fn of(url: &str, bbox: [f64; 4], cell: Option, bands: usize) -> WindowAsked { - WindowAsked { url: url.to_string(), bbox, cell, name: None, bands: Some(bands), auto_cell: false } + WindowAsked { url: url.to_string(), bbox, cell, name: None, bands: Some(bands), auto_cell: false, rows: None } } /// The cell size is the caller's own choice, not the user's: a full image finer than it is /// read without saying so. @@ -6472,10 +6514,9 @@ pub struct CogWindow { layer: rustgis_map::RasterLayer, /// What to say of it, once the layer has its name. notes: Vec, - columns: [u32; 2], - rows: [u32; 2], - level: usize, - cell_size: f64, + /// What the command answers of the read (`"window"`): a cloud-optimised GeoTIFF's columns, + /// rows, level and cell size; none for a GRIB record's rows, which the notes say. + answer: Option, } /// `p`'s box and cell size, read on the frame, which holds the view. @@ -6488,11 +6529,12 @@ fn window_settled(s: &Session, p: &Value, url: &str, seen: Option<[f64; 4]>) -> Some(v) => Some(v.as_f64().filter(|c| c.is_finite() && *c > 0.0).ok_or_else(|| named("cellSize is a size above 0".into()))?), }; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(String::from); - Ok(WindowAsked { url: url.to_string(), bbox, cell, name, bands: None, auto_cell: false }) + Ok(WindowAsked { url: url.to_string(), bbox, cell, name, bands: None, auto_cell: false, rows: None }) } /// A window the app reads off the frame: `p`, a `layer.addUrl` with `"bbox"` and its address bound -/// to its login, checked as the command checks it. Errors quote the address without its keys. +/// to its login, checked as the command checks it; with `"bytes"`, the rows of a box of a GRIB +/// record ([`rows_settled`]). Errors quote the address without its keys. #[cfg(not(target_arch = "wasm32"))] pub fn window_asked(s: &Session, p: &Value) -> Result { window_asked_in(s, p, None) @@ -6503,6 +6545,10 @@ pub fn window_asked(s: &Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] pub fn window_asked_in(s: &Session, p: &Value, seen: Option<[f64; 4]>) -> Result { let url = ps(p, "url").map(str::trim).filter(|u| !u.is_empty()).ok_or("url is required")?; + if asks_rows(p) { + let checked = web_address(url).and_then(|_| request_origin_for(s, p)).and_then(|(_, public)| rows_settled(s, p, url, seen, public)); + return checked.map_err(|e| crate::sources::message_with_address(url, &e)); + } let checked = web_address(url) .and_then(|_| super::raster::as_scan(p)) .and_then(|scan| window_checks(p, url, scan)) @@ -6795,9 +6841,13 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: /// [`read_cog_window`], giving up within a moment of `stop` being set (the app's Cancel of the /// download, or its project closed): in the wait on the header, before each batch of bands and in /// the wait on their tiles. Making the raster and writing its GeoTIFF, once the values are in, -/// don't look. +/// don't look. With a GRIB record's range (`"bytes"`), its rows of the box instead +/// ([`read_grib_rows_until`]). #[cfg(not(target_arch = "wasm32"))] pub fn read_cog_window_until(asked: &WindowAsked, stop: &std::sync::atomic::AtomicBool) -> Result { + if let Some(rows) = &asked.rows { + return read_grib_rows_until(asked, rows, stop); + } let named = |e: String| crate::sources::message_with_address(&asked.url, &e); let WindowRaster { raster: r, read, finer, edges, columns, rows, level, cell_size } = read_window_raster(asked, stop)?; let name = asked.name.clone().unwrap_or_else(|| cog_name(&asked.url)); @@ -6834,7 +6884,8 @@ pub fn read_cog_window_until(asked: &WindowAsked, stop: &std::sync::atomic::Atom notes.push(format!("the project keeps {kept} of its {band_count} bands: {left_out} band(s) are left out once it is reopened")); } notes.extend(edges); - Ok(CogWindow { name, layer, notes, columns, rows, level, cell_size }) + let answer = json!({"columns": columns, "rows": rows, "level": level, "cellSize": cell_size}); + Ok(CogWindow { name, layer, notes, answer: Some(answer) }) } /// A window's raster as [`read_window_raster`] reads it, every band kept, and what to say of the @@ -6873,13 +6924,15 @@ impl WindowRaster { /// (`layer.addUrl`, or `layer.addDownload` when the app read it off the frame). #[cfg(not(target_arch = "wasm32"))] fn add_window(s: &mut Session, p: &Value, read: CogWindow) -> CmdResult { - let CogWindow { name, layer, notes, columns, rows, level, cell_size } = read; + let CogWindow { name, layer, notes, answer } = read; let mut out = super::raster::add_raster_after(s, &name, layer, b(p, "zoom"))?; let added = s.active_layer.and_then(|id| s.map().layer(id)).map(|l| l.name.clone()).unwrap_or(name); for note in notes { s.notify(format!("{added}: {note}"), false); } - out["window"] = json!({"columns": columns, "rows": rows, "level": level, "cellSize": cell_size}); + if let Some(answer) = answer { + out["window"] = answer; + } // `"zoom": true` zooms to the window whatever the map held, as for any other address. if b(p, "zoom") == Some(true) { out["zoomed"] = json!(zoom_to_added(s, &out)); diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index ee6158fcdb..54582c3364 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -549,7 +549,7 @@ const MAX_EXPIRED: usize = 1024; /// and what the app adds of its own (`id`), don't count. Another import of the same address /// (other columns, another name) isn't it. A byte range of a GRIB file (`"bytes"`) comes back as /// the address the front end downloads, with the range marked in it -/// ([`crate::cmd::layer::ranged_address`]). +/// ([`crate::cmd::layer::ranged_address`]), and its rows of a box (`"bbox"`) with the box too. fn asked_by(asked: &Value, params: &Value) -> bool { let Some(o) = asked.as_object() else { return false }; let range = match asked.get("bytes").and_then(Value::as_array).map(Vec::as_slice) { @@ -579,8 +579,19 @@ fn asked_by(asked: &Value, params: &Value) -> bool { _ if passed_on(k, v) => params.get(k) == Some(v), _ => true, }); + // The rows of a box of a range (`"bbox"` with `"bytes"`, #3055) come back with their box marked + // (`"window"`, as the app reads them off the frame), or as asked: the range with another box, + // or with none (the whole record), isn't it, nor is a box for a range asked without one. + let boxed = |q: &Value| { + q.get("window") + .and_then(|w| w.get("bbox")) + .or_else(|| q.get("bbox")) + .filter(|b| !b.is_null() && b.as_bool() != Some(false)) + .cloned() + }; + let boxes = range.is_none() || boxed(asked) == boxed(params); // ... and nothing it passes on that wasn't asked for (another import of the address). - given && params.as_object().is_none_or(|p| p.iter().all(|(k, v)| k == "url" || !passed_on(k, v) || o.get(k) == Some(v))) + given && boxes && params.as_object().is_none_or(|p| p.iter().all(|(k, v)| k == "url" || !passed_on(k, v) || o.get(k) == Some(v))) } impl UrlWaits { @@ -1366,6 +1377,31 @@ mod tests { )); } + /// The rows of a box of a range (#3055) land with their box marked (`"window"`, as the app + /// reads them off the frame), or as asked: the range with another box, or with none, isn't + /// what was asked, nor are the rows of a box what a range asked without one is. + #[test] + fn the_rows_of_a_box_land_only_with_their_box() { + let u = "https://x.org/model.grb"; + let bbox = json!([-51.45, -23.32, -39.46, -13.83]); + let asked = json!({"url": u, "bytes": [100, 199], "bbox": bbox, "name": "rain", "anonymous": true}); + let ranged = crate::cmd::layer::ranged_address(u, (100, 199)); + let landed = |window: Value| json!({"url": ranged, "name": "rain", "anonymous": true, "id": 3, "window": window}); + assert!(asked_by(&asked, &landed(json!({"bbox": bbox})))); + assert!(!asked_by(&asked, &landed(json!({"bbox": [-50, -23, -40, -14]})))); + assert!(!asked_by(&asked, &json!({"url": ranged, "name": "rain", "anonymous": true, "id": 3})), "the whole record"); + // A failure the app says with the parameters asked. + assert!(asked_by(&asked, &asked)); + // "view" stays "view": the box it was is the request's own. + let view = json!({"url": u, "bytes": [100, 199], "bbox": "view", "anonymous": true}); + assert!(asked_by(&view, &json!({"url": ranged, "anonymous": true, "window": {"bbox": "view"}}))); + // A range asked without a box: its whole record lands it, the rows of a box don't. + let whole = json!({"url": u, "bytes": [100, 199], "name": "rain", "anonymous": true}); + assert!(asked_by(&whole, &json!({"url": ranged, "name": "rain", "anonymous": true, "id": 3}))); + assert!(!asked_by(&whole, &landed(json!({"bbox": bbox})))); + assert!(asked_by(&json!({"url": u, "bytes": [100, 199], "bbox": false}), &json!({"url": ranged})), "a false box is none"); + } + fn load_test_plugin(id: &str) -> String { let package = rustgis_plugins::Package::from_zip(&rustgis_plugins::testing::package(id, &["edit", "network"])).unwrap(); rustgis_plugins::load(package, "test").unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 884569cb2b..2ae58836c1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54384,8 +54384,8 @@ fn grib1_grid_message() -> Vec { /// `layer.addUrl` with `"bytes"` and `"bbox"` (#3055) asks for the record's first 4,096 octets, /// then for the rows of the box only, and adds the cells the box touches, saying how much it -/// read. A record that can't be read by rows is downloaded whole and cut to the box, and said; -/// where rows aren't read yet (a plugin's command in the app, the app's own check) it is refused. +/// read. A record that can't be read by rows is downloaded whole and cut to the box, and said. +/// A plugin's command leaves them to the app ([`a_plugin_commands_grib_rows_are_read_off_the_frame`]). #[cfg(not(target_arch = "wasm32"))] #[test] fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { @@ -54417,11 +54417,14 @@ fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 87], "bbox": false})).unwrap(); assert_eq!(cells(&s, &r).4, vec![1.0, 2.0]); assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88); + // Without a range too: the file is downloaded whole, never read as a window of a GeoTIFF. + s.run("layer.addUrl", &json!({"url": url, "bbox": false})).unwrap(); + assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88 + 4972); // Two messages in the range: downloaded whole after the first read, cut to the box, and said. let mark = s.notice_mark(); let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 4971], "bbox": [9.6, 59.6, 10.4, 60.4], "name": "Two"})).unwrap(); assert_eq!(cells(&s, &r).4, vec![1.0]); - assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88 + 4096 + 4972); + assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88 + 4972 + 4096 + 4972); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); let whole = "Two: a range that isn't one whole message of one field can't be read row by row: the whole record was downloaded (5 kB) and cut to the box"; assert!(said.contains(&whole.to_string()), "{said:?}"); @@ -54445,16 +54448,69 @@ fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { let e = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": [10, 70, 12, 80]})).unwrap_err(); assert!(e.contains("the box's latitudes (70° to 80°) are outside the record's grid (20.5° to 60.5°)"), "{e}"); assert_eq!(count(), before + 4096); - // The app's check of a range, and a plugin's command it runs: not read by rows yet, and said. + // The app's check of a range takes the box: its rows are read off the frame. let asked = json!({"url": url, "bytes": [88, 4971], "bbox": [10.6, 56.7, 12.4, 59.3]}); - let e = crate::cmd::layer::byte_range(&asked, &url).unwrap_err(); - assert!(e.contains("is read on the command line for now, not in the app yet"), "{e}"); + assert_eq!(crate::cmd::layer::byte_range(&asked, &url), Ok(Some((88, 4971)))); + assert!(crate::cmd::layer::asks_rows(&asked)); + assert!(!crate::cmd::layer::asks_rows(&json!({"url": url, "bytes": [88, 4971], "bbox": false}))); +} + +/// A plugin's command asking for the rows of a box of a GRIB record (#3055) leaves them to the +/// app, nothing read on the frame. The app reads them on its own thread as it reads a window (the +/// record's first 4,096 octets, then the box's rows) and adds them with the range marked on the +/// address and the box in `"window"`: the command runs again and is answered the layer. A read +/// stopped before it starts (Cancel) asks for nothing. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_plugin_commands_grib_rows_are_read_off_the_frame() { + use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; + let mut file = grib1_message(1, 2); + file.extend(grib1_grid_message()); + let (base, sent) = serve_ranges(file); let mut s = world(); - plugin("eng-grib-rows", &["edit", "network"]); + plugin("eng-grib-rows-app", &["edit", "network"]); + // Its downloads come from this computer (a test server). fetch_mode(true, true); - let e = s.run_leaving_downloads("plugin:eng-grib-rows/f", &json!({"op": "layer.addUrl", "params": asked})).unwrap_err(); - assert!(e.contains("is read on the command line for now, not in the app yet"), "{e}"); - assert!(s.take_url_requests().is_empty()); + let url = format!("{base}/run/PREC.grb"); + let bbox = json!([10.6, 22.7, 12.4, 25.3]); + let p = json!({"op": "layer.addUrl", "params": {"url": url, "bytes": [88, 4971], "bbox": bbox, "name": "Rain"}}); + s.run_leaving_downloads("plugin:eng-grib-rows-app/f", &p).unwrap(); + assert_eq!(sent.load(Relaxed), 0, "nothing is read on the frame"); + let asked = s.take_url_requests(); + assert_eq!(asked.len(), 1); + let params = asked[0].params().clone(); + assert_eq!((params["bytes"].clone(), params["bbox"].clone()), (json!([88, 4971]), bbox.clone())); + let id = s.download_started_for(&asked[0]).unwrap(); + // As the app reads it, off the frame: Cancel before the first request asks for nothing. + let window = crate::cmd::layer::window_asked_in(&s, ¶ms, asked[0].view_asked()).unwrap(); + let e = crate::cmd::layer::read_cog_window_until(&window, &AtomicBool::new(true)).err().unwrap(); + assert!(e.contains(crate::render::rustgis_tiles::cog::STOPPED), "{e}"); + assert_eq!(sent.load(Relaxed), 0); + let read = crate::cmd::layer::read_cog_window_until(&window, &AtomicBool::new(false)).unwrap(); + assert_eq!(sent.load(Relaxed), 4096 + 360, "the first read and three rows"); + assert!(s.download_landed_window(id, read)); + // Added as the app adds it: the range marked on the address, the box in "window". + let mut add = json!({"id": id, "url": crate::cmd::layer::ranged_address(&url, (88, 4971)), "name": "Rain"}); + for k in ["request", "anonymous"] { + add[k] = params[k].clone(); + } + add["window"] = json!({"bbox": bbox}); + let mark = s.notice_mark(); + s.complete_download(id, &add).unwrap(); + let layer = s.map().layer_by_name("Rain").filter(|l| l.is_raster()).unwrap(); + let added = layer.id; + let data = layer.raster.as_ref().unwrap().data.clone().unwrap(); + assert_eq!((data.width, data.height), (2, 3)); + assert_eq!(data.bands[0].data, vec![2101.0, 2102.0, 2161.0, 2162.0, 2221.0, 2222.0]); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.contains(&"Rain: read 3 of 40 rows (5 kB of 5 kB)".to_string()), "{said:?}"); + // The command runs again, and its `layer.addUrl` answers the layer added. + let ran = s.poll_plugin_retries(); + assert_eq!(ran.len(), 1, "{ran:?}"); + assert_eq!(ran[0].1.as_ref().unwrap()["layer"], json!(added), "{ran:?}"); + assert!(s.take_url_requests().is_empty() && !s.plugin_retries_waiting()); + assert_eq!(sent.load(Relaxed), 4096 + 360, "nothing read again"); + rustgis_plugins::unload("eng-grib-rows-app"); } /// Each page of a map series is georeferenced with its own view, not the first page's (#1191). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f28a1e832c..8a2cbe7d47 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -342,8 +342,14 @@ type PageRead = Slot, rustgis_engine::data::raster::Raster), Str /// See [`UiState::window_reads`]. #[cfg(not(target_arch = "wasm32"))] -type WindowRead = - (u64, String, Value, Slot>, std::sync::Arc); +type WindowRead = ( + u64, + String, + Value, + Slot>, + std::sync::Arc, + Option>, +); /// A window's turn to be read off the frame, or `None` once `left` says its project was closed or /// its download was cancelled: one waiting for its turn then gives up its place at once, without @@ -1073,9 +1079,10 @@ pub struct UiState { /// that can be read in place are added so, others downloaded (the `ui.addUrl` parameters, /// and the answer). pub cog_probes: Vec<(Value, Option, Slot>)>, - /// Windows of cloud-optimised GeoTIFFs (`"bbox"`) being read on threads: the session's - /// download id, the address, the parameters to add it with, where the read lands, and whether - /// its project was closed. + /// Windows of cloud-optimised GeoTIFFs (`"bbox"`), and the rows of a box of GRIB records + /// (`"bytes"` with `"bbox"`, #3055), being read on threads: the session's download id, the + /// address, the parameters to add it with, where the read lands, whether its project was + /// closed, and how far a GRIB record's requests have come (a window's tiles aren't counted). #[cfg(not(target_arch = "wasm32"))] pub window_reads: Vec, /// PDF downloads whose page is being drawn on a thread before it is added (#2336): the @@ -3865,6 +3872,18 @@ impl RustGisApp { if let Some(Value::Object(window)) = window { o.extend(window); } + // The rows of a box of a GRIB record (#3055): the range marked on the address is + // its `"bytes"` again, and an address whose name doesn't say GRIB is one by + // `"format"`, as it was asked. + let marked = o.get("url").and_then(Value::as_str).map(rustgis_engine::render::rustgis_tiles::cache::split_range); + if let Some((url, Some((first, last)))) = marked.map(|(u, r)| (u.to_string(), r)) { + let named = rustgis_engine::data::raster::grib::is_grib_name(url.split(['?', '#']).next().unwrap_or(&url)); + o.insert("url".into(), json!(url)); + o.insert("bytes".into(), json!([first, last])); + if !named { + o.insert("format".into(), json!("grib")); + } + } } finished = again; ("layer.addUrl", &finished) @@ -6233,7 +6252,10 @@ impl RustGisApp { let range = rustgis_engine::cmd::layer::byte_range(p, url)?; // A window of a cloud-optimised GeoTIFF is read off the frame (below), with no // probe: it is refused unless it is one. In the browser the command refuses it. - let window = cfg!(not(target_arch = "wasm32")) && p.get("bbox").is_some_and(|v| !v.is_null()); + // With a range, the rows of the box of a GRIB record are read off the frame the same + // way (#3055), the range marked on the address. A `false` box is no box, as the + // command reads it. + let window = cfg!(not(target_arch = "wasm32")) && p.get("bbox").is_some_and(|v| !v.is_null() && v.as_bool() != Some(false)); if !window && url.to_ascii_lowercase().split(['?', '#']).next().is_some_and(|u| u.ends_with(".pmtiles")) { let before = self.session.sources.generation; let result = if let Some(id) = claim { @@ -6587,7 +6609,7 @@ impl RustGisApp { { let mut read = Vec::new(); let session = &self.session; - self.ui.window_reads.retain(|(id, url, p, slot, left)| match slot.lock().unwrap_or_else(|e| e.into_inner()).take() { + self.ui.window_reads.retain(|(id, url, p, slot, left, _)| match slot.lock().unwrap_or_else(|e| e.into_inner()).take() { Some(r) => { read.push((*id, url.clone(), p.clone(), r)); false @@ -6620,7 +6642,7 @@ impl RustGisApp { let downloads = self.ui.downloads.iter().map(|d| shown(d.id, &d.url, Some(&d.progress))); #[cfg(not(target_arch = "wasm32"))] let downloads = downloads - .chain(self.ui.window_reads.iter().map(|(id, url, ..)| shown(*id, url, None))) + .chain(self.ui.window_reads.iter().map(|(id, url, _, _, _, progress)| shown(*id, url, progress.as_ref()))) .chain(self.ui.page_reads.iter().map(|(l, ..)| shown(l.id, &l.url, None))) .chain(self.ui.page_queue.iter().map(|(l, ..)| shown(l.id, &l.url, None))); let mut under_way: Vec<_> = downloads.collect(); @@ -6641,7 +6663,7 @@ impl RustGisApp { #[cfg(not(target_arch = "wasm32"))] let cancelled = cancelled.or_else(|| { let i = self.ui.window_reads.iter().position(|d| d.0 == id)?; - let (_, url, p, _, left) = self.ui.window_reads.remove(i); + let (_, url, p, _, left, _) = self.ui.window_reads.remove(i); left.store(true, std::sync::atomic::Ordering::Relaxed); Some((url, p)) }); @@ -6725,15 +6747,30 @@ impl RustGisApp { let land = slot.clone(); let left = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let leaving = left.clone(); + // A GRIB record's rows (#3055) are whole requests on this thread: counted, as a download + // is, and stopped at their next bytes once cancelled or no longer wanted by their claim + // (a window's tiles look at `left` themselves). + let rows = rustgis_engine::cmd::layer::asks_rows(p); + let progress = rows.then(std::sync::Arc::::default); + let counted = progress.clone(); + let claimed = claim.and_then(|id| self.session.download_still(id)).filter(|_| rows); + let watched = left.clone(); + let wanted: Option = + rows.then(|| std::sync::Arc::new(move || !watched.load(std::sync::atomic::Ordering::Relaxed)) as _); // Its requests stay in the session's diagnostics. let diagnostics = self.session.diagnostics.capture(); let spawned = std::thread::Builder::new().name("cog-window".into()).spawn(move || { let _diagnostics = diagnostics.enter(); let turn = window_turn(&leaving); let read = if turn.is_some() { + use rustgis_engine::render::rustgis_tiles::cache; // On a thread no command's catch reaches: a bug must not leave it running forever. let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::layer::read_cog_window_until(&asked, &leaving) + cache::with_optional_still(claimed, || { + cache::with_optional_still(wanted, || { + cache::with_progress(counted, || rustgis_engine::cmd::layer::read_cog_window_until(&asked, &leaving)) + }) + }) })); let read = read.unwrap_or_else(|_| Err(tl!("Reading the window failed unexpectedly").to_string())); // Stopped by `left`: said as one given up before its turn is. A read that failed @@ -6772,7 +6809,7 @@ impl RustGisApp { let shown = rustgis_engine::sources::address_in_message(&url); self.session.notify(i18n::fmt("Reading {url}…", &[("url", &shown)]), false); let id = claim.unwrap_or_else(|| self.session.download_started()); - self.ui.window_reads.push((id, url, q, slot, left)); + self.ui.window_reads.push((id, url, q, slot, left, progress)); Ok(Value::Null) } @@ -8881,6 +8918,21 @@ mod record_tests { assert_eq!(steps.len(), 1, "{:?}", app.session.notices); assert_eq!(steps[0].command, "layer.addUrl"); assert_eq!(steps[0].params, json!({"url": "https://example.com/data", "name": "W", "bbox": "view", "cellSize": 30, "cog": true})); + // The rows of a box of a GRIB record (#3055): the range marked on the address goes back + // to "bytes", so the step reads the same rows again. + let url = "https://example.com/run/PREC.grb"; + let ranged = rustgis_engine::cmd::layer::ranged_address(url, (88, 4971)); + let p = json!({"id": 2, "url": ranged, "name": "Rain", "request": 8, "window": {"bbox": [-51, -23, -39, -14]}}); + app.record_step("layer.addDownload", &p, None); + let steps = app.ws.recording.as_ref().unwrap(); + assert_eq!(steps[1].params, json!({"url": url, "bytes": [88, 4971], "name": "Rain", "bbox": [-51, -23, -39, -14]})); + // An address whose name doesn't say GRIB keeps "format", without which its range is refused. + let unnamed = "https://example.com/record?id=2"; + let p = json!({"id": 3, "url": rustgis_engine::cmd::layer::ranged_address(unnamed, (0, 87)), "window": {"bbox": [10, 59, 11, 60]}}); + app.record_step("layer.addDownload", &p, None); + let step = &app.ws.recording.as_ref().unwrap()[2].params; + assert_eq!(step, &json!({"url": unnamed, "bytes": [0, 87], "format": "grib", "bbox": [10, 59, 11, 60]})); + assert_eq!(rustgis_engine::cmd::layer::byte_range(step, unnamed), Ok(Some((0, 87))), "replayed, the range is read"); } /// `ui.addUrl` with `"bbox"`: a slow server doesn't hold the @@ -8944,7 +8996,7 @@ mod record_tests { fn too_many_windows_under_way_are_refused() { let mut app = RustGisApp::with_sample(); for _ in 0..crate::MAX_WINDOW_READS { - app.ui.window_reads.push((0, String::new(), serde_json::Value::Null, Default::default(), Default::default())); + app.ui.window_reads.push((0, String::new(), serde_json::Value::Null, Default::default(), Default::default(), None)); } let e = app.run("ui.addUrl", json!({"url": "https://x.org/a.tif?token=hidden-1330", "bbox": [1, 2, 3, 4]})).unwrap_err(); assert!(e.contains("x.org/a.tif") && e.contains("16 windows") && !e.contains("hidden-1330"), "{e}"); @@ -9018,6 +9070,48 @@ mod record_tests { assert!(app.session.map().layer_by_name("Cancelled").is_none()); } + /// The rows of a box of a GRIB record (`"bytes"` with `"bbox"`, #3055) are read off the frame + /// as a window is, the range marked on the address: listed with how much of their requests has + /// come, and Cancel drops them, said, with nothing added once the server answers after all. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn the_rows_of_a_grib_record_are_read_off_the_frame_and_cancelled() { + use std::sync::atomic::Ordering; + let _turn = crate::fetching::turn(); + let slow = crate::fetching::slow_ranges(vec![0; 8192]); + slow.open.store(false, Ordering::Relaxed); + let mut app = RustGisApp::with_sample(); + let url = format!("{}/run/PREC.grb", slow.origin); + let asked = std::time::Instant::now(); + let p = json!({"url": url, "bytes": [0, 8191], "bbox": [10.6, 22.7, 12.4, 25.3], "name": "Rows"}); + app.run("ui.addUrl", p).unwrap(); + assert!(asked.elapsed() < std::time::Duration::from_secs(5), "asking for it held the frame"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while slow.held.load(Ordering::Relaxed) == 0 { + assert!(std::time::Instant::now() < deadline, "no request held"); + std::thread::sleep(std::time::Duration::from_millis(20)); // test-wait: polling for the held first read + } + let under_way = app.downloads_under_way(); + assert_eq!(under_way.len(), 1, "{under_way:?}"); + assert!(under_way[0].shown.contains("PREC.grb") && under_way[0].progress.is_some(), "{under_way:?}"); + assert!(app.ui.window_reads[0].1.contains(rustgis_engine::render::rustgis_tiles::cache::RANGE), "{}", app.ui.window_reads[0].1); + app.cancel_download(under_way[0].id); + assert!(app.ui.window_reads.is_empty() && app.downloads_under_way().is_empty()); + let said = |n: &rustgis_engine::Notice| n.text.contains("PREC.grb") && n.text.contains("cancelled") && !n.error; + assert!(app.session.notices.iter().any(said), "{:?}", app.session.notices); + // The server answers after all: the read's thread ends (its turn comes free once it has + // landed whatever it read, or given up), and only then is nothing added looked for. + slow.open.store(true, Ordering::Relaxed); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while crate::WINDOW_TURN.try_lock().is_err() { + assert!(std::time::Instant::now() < deadline, "the cancelled read never ended"); + std::thread::sleep(std::time::Duration::from_millis(20)); // test-wait: polling for the cancelled read's thread to end + } + app.poll_data_downloads(); + assert!(app.ui.window_reads.is_empty() && app.downloads_under_way().is_empty()); + assert!(app.session.map().layer_by_name("Rows").is_none()); + } + /// Cancel drops a whole file's download as one that failed: said, and not added when its /// bytes come in after all. #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index c74d1af7e4..eae40af78e 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -701,7 +701,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. Keys for other kinds of address (`"crs"`, `"layer"`, `"x"`, `"y"` and the like) are refused with a box. Values past the range of 32-bit floats are counted over the box's cells; in a record downloaded whole the notice says they are the whole record's. In the app, `"bbox"` with `"bytes"` is refused for now. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"` (desktop and command line), only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. Keys for other kinds of address (`"crs"`, `"layer"`, `"x"`, `"y"` and the like) are refused with a box. Values past the range of 32-bit floats are counted over the box's cells; in a record downloaded whole the notice says they are the whole record's. In the app, and for a plugin's command it runs, the rows are read off the frame, listed in the status bar with how much has come and a Cancel, as a download is; each request waits at most a minute. | | SRTM height tile | `.hgt` | Add Data, or upload (desktop and browser) | One 1° tile of 16-bit heights in meters, 1201 × 1201 (3 arc-seconds), 3601 × 3601 (1 arc-second) or 7201 × 7201 (0.5 arc-second), read natively; a tile larger than the memory budget (a 0.5 arc-second tile in the browser) is read at every second sample or fewer, each kept sample still at its cell's center. The file name places it (`N37W122.hgt` is the tile whose south-west corner is 37°N, 122°W; an upload keeps its name), so a file whose name isn't a tile's, or whose size is neither grid's, is refused. Samples sit on the whole-degree lines, so each is a cell centered on its point and the layer reaches half a cell past the tile's edges. WGS 84; voids (−32768) are no data, and a notice counts them. Heights are above the EGM96 geoid (mean sea level), not the ellipsoid, and a notice says so once as the layer is added. SRTM and DTED files hold one band and give their own coordinates (read as WGS 84; a DTED file naming another datum says so), so a `"crs"` or `"layer"` given for one (or kept by a project saved when these files went through GDAL) is ignored, and a notice says so. | | DTED | `.dt0`, `.dt1`, `.dt2` | Add Data, or upload (desktop and browser) | DTED levels 0, 1 and 2, read natively per MIL-PRF-89020B: the UHL header gives the south-west post, the spacing (wider in longitude at high latitudes) and the counts. Posts are cells centered on them, as for SRTM. Voids (−32767) are no data and counted in a notice. In a two's-complement file, a void stored as 0x8001 reads as −1 m and no notice counts it; a height of −1 m stored as 0xFFFF reads as no data. A column whose record lacks its 0xAA sentinel is read as no data, and a notice counts those columns; a whole cell whose longitude counts number its columns from 1 rather than 0 is read by place, and a notice counts those columns; a file with any other longitude count that doesn't match its place (leading columns left out, counts offset, or a stray count), or a record whose latitude count isn't 0, is refused, naming the record, since its heights would land in the wrong place; a column whose checksum doesn't match its heights (some producers write them wrongly) is read as stored, and a notice counts those too. Heights some producers write in two's complement rather than signed magnitude (those that would read below −16000 m) are read as two's complement, and counted in a notice. A complete cell cut short opens with its missing columns as no data, and says so. A partial cell is read in the full-grid layout of CD-ROM files, its missing posts as voids; one in the magnetic-tape layout is refused when its DSI counts only the lines that have heights. A tape cell with a height on every line counts the whole cell too, but its file is shorter than the full grid's, so it's refused as well; a partial cell cut short is refused the same way, since the two can't be told apart. The level is the one the DSI record names (the extension's when it names none, and a notice says when the two differ). A spacing other than the specification's for the level and latitude, a DSI record that disagrees with the UHL, or a horizontal datum other than WGS 84 is said. The vertical datum (EGM96, or mean sea level) is said once, as for SRTM. | | Rasters GDAL reads | `.img`, `.dem`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. |