From e670abd57f99530e6ef81a0cdd4e83731650a72d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 01:29:48 -0300 Subject: [PATCH 1/3] feat(engine): layer.addUrl reads a byte range of a GRIB file (#2428, part 2) "bytes": [first, last] downloads only those octets of a GRIB file (by its name, or "format": "grib") and reads them as the file, on the desktop (off the frame) and the command line. A server that ignores the range, or answers fewer octets, is refused and said; the browser refuses bytes for now (CORS). Co-Authored-By: Claude Opus 5.5 --- crates/assistant/skills/add-data/SKILL.md | 3 +- crates/engine/src/cmd/layer.rs | 123 +++++++++++++++++++++- crates/engine/src/tests.rs | 70 ++++++++++++ crates/ui-egui/src/lib.rs | 17 ++- docs/user-guide/data-formats.md | 2 +- 5 files changed, 210 insertions(+), 5 deletions(-) diff --git a/crates/assistant/skills/add-data/SKILL.md b/crates/assistant/skills/add-data/SKILL.md index 195e9956e4..7d0f66e67d 100644 --- a/crates/assistant/skills/add-data/SKILL.md +++ b/crates/assistant/skills/add-data/SKILL.md @@ -15,7 +15,8 @@ and its limits are listed in `user-guide/data-formats.md`. coordinates land in the wrong place. Use `"delimiter"` when it isn't a comma. - **A web address:** `layer.addUrl` `{"url": U}` for GeoJSON, CSV, GeoParquet, FlatGeobuf, GeoPackage, zipped Shapefiles, KML/KMZ, GPX, GeoTIFF, GRIB or a PMTiles archive. This uses the - network, so the user is asked first. + network, so the user is asked first. One record of a large GRIB file: `"bytes": [first, last]`, + the octets its `.inv` inventory gives (the record's offset to the next one's, less one). - **SQL:** `layer.addSql` `{"sql": "SELECT … FROM read_parquet('…')"}` runs one DuckDB query (DuckDB Spatial's `ST_` functions; PostgreSQL through `"database"`). It needs DuckDB installed on the desktop. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2945912d34..63833c9b7a 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", "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)", "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), "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", "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)", "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), "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), "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)}"#), @@ -5007,6 +5007,14 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { // A scan (`"as"`) keeps the pixels and none of the coordinates: the file is downloaded whole and // read as one (`add_named_bytes` checks it is an image), never read in place. let scan = super::raster::as_scan(p)?; + // A byte range of a GRIB file (`"bytes"`, #2428): only that range is downloaded, and read as + // the file. The browser refuses it ([`byte_range`]). + #[cfg(not(target_arch = "wasm32"))] + if let Some(range) = byte_range(p, url)? { + return add_url_range(s, p, url, range, public); + } + #[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()); if !window && p.get("cellSize").is_some_and(|v| !v.is_null()) { @@ -5166,6 +5174,119 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { } } +/// The most octets a `"bytes"` range may ask for (64 MB): a record of a model's file, not the file. +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. +pub fn byte_range(p: &Value, url: &str) -> 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, + Some(_) => return Err("\"format\" is \"grib\", the one format a byte range is read as".into()), + }; + let asked = match p.get("bytes") { + None | Some(Value::Null) if grib => return Err("\"format\" goes with \"bytes\": give a range, or leave it out".into()), + None | Some(Value::Null) => return Ok(None), + Some(Value::Array(v)) if v.len() == 2 => v[0].as_u64().zip(v[1].as_u64()), + Some(_) => None, + }; + let Some((first, last)) = asked else { + return Err("\"bytes\" is [first, last]: two octet offsets counted from 0, both included".into()); + }; + if first > last { + return Err(format!("\"bytes\": the first octet ({first}) comes after the last ({last})")); + } + if last - first >= MAX_RANGE { + return Err(format!("\"bytes\": {} octets asked for, more than a range may have (64 MB)", (last - first).saturating_add(1))); + } + let path = url.split(['?', '#']).next().unwrap_or(url); + if !rustgis_data::raster::grib::is_grib_name(path) { + // An address naming another format is that format, whatever "format" says. + if let Some(name) = url_file_name(url, &[]).ok().filter(|_| grib) { + return Err(format!("\"bytes\": the address names {name}, not a GRIB file")); + } + if !grib { + return Err("\"bytes\" reads a range of a GRIB file (an address ending in .grb, .grib, .grb2 or .grib2, or \"format\": \"grib\"): a range of another format isn't a file".into()); + } + } + let other = ["bbox", "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) { + return Err("\"bytes\" doesn't go with a dated address: give the file's own address".into()); + } + 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()); + } + Ok(Some((first, last))) +} + +/// 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. +/// +/// [`cache::RANGE`]: crate::render::rustgis_tiles::cache::RANGE +pub fn ranged_address(url: &str, (first, last): (u64, u64)) -> String { + format!("{url}{}{first}-{last}", crate::render::rustgis_tiles::cache::RANGE) +} + +/// A range's answer is as long as the range: a server answering fewer octets (a range past the +/// file's end) is refused, never read as the record. Other addresses pass. +pub fn check_range_answer(url: &str, bytes: &[u8]) -> Result<(), String> { + match crate::render::rustgis_tiles::cache::split_range(url) { + (_, Some((first, last))) if bytes.len() as u64 != (last - first).saturating_add(1) => Err(format!( + "the server answered {} octets of the {} asked for (\"bytes\": [{first}, {last}]): check the range against the file's inventory", + bytes.len(), + (last - first).saturating_add(1) + )), + _ => Ok(()), + } +} + +/// A range's download failed: one whose answer was longer than the range (a server answering the +/// whole file from octet 0) says why. +pub fn range_failed(url: &str, e: String) -> String { + let (_, range) = crate::render::rustgis_tiles::cache::split_range(url); + if range.is_some() && e.contains("larger than") { + format!("{e}, more than the range asked for: {}", crate::render::rustgis_tiles::cache::NO_RANGES) + } else { + e + } +} + +/// Downloads a GRIB file's range ([`byte_range`]) and adds it (the command line); a plugin's +/// command on the desktop leaves it to the app, which downloads it off the frame. A server that +/// ignores the range is refused before the file comes ([`cache::NO_RANGES`]), or once its answer +/// is longer than the range. +/// +/// [`cache::NO_RANGES`]: crate::render::rustgis_tiles::cache::NO_RANGES +#[cfg(not(target_arch = "wasm32"))] +fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), public: bool) -> CmdResult { + use crate::render::rustgis_tiles::cache; + if s.leave_downloads { + let mut asked = p.clone(); + asked["url"] = json!(url); + return s.request_url(&asked); + } + let named = |e: String| crate::sources::message_with_address(url, &e); + let ranged = ranged_address(url, range); + let len = usize::try_from(range.1 - range.0 + 1).unwrap_or(usize::MAX); + let public = public || cache::ceiling_for(url) == crate::render::rustgis_tiles::address::Reach::Public; + let bytes = if public { + cache::download_public_within(&ranged, len, cache::BLOCKING_TIMEOUT) + } else { + cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) + }; + let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(cache::large_file_hint).map_err(named)?; + check_range_answer(&ranged, &bytes).map_err(named)?; + let name = url_file_name(&ranged, &bytes).map_err(named)?; + super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named) +} + /// Whether a Shapefile's part other than its `.dbf` can be done without: it isn't there (404 or /// 410, or 403, which S3 answers for a missing object to those who can't list the bucket). A 403 /// to an address read with keys ([`keyed`]) fails instead, as they may not cover the part. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a65189680e..4bf4cb9ba5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47806,6 +47806,76 @@ fn a_grib_download_is_read_off_the_frame() { assert!(download_page("https://example.org/a.tif", &asked, message).is_none()); } +/// A GRIB1 message of 88 octets: a 2 × 1 grid of 1° cells from 60° N, 10° E, its two values 16 +/// bits each (R = 0, E = 0, D = 0). +#[cfg(not(target_arch = "wasm32"))] +fn grib1_message(a: u16, b: u16) -> Vec { + let mut m = b"GRIB\0\0\x58\x01".to_vec(); + // Product definition (28 octets): a grid description follows, parameter 11 at the surface. + m.extend([0, 0, 28, 2, 7, 96, 255, 0x80, 11, 105, 0, 2, 26, 11, 18, 6, 0, 1, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0]); + // Grid description (32 octets): latitude/longitude, 2 × 1, 60° N 10° E to 60° N 11° E, 1°. + m.extend([0, 0, 32, 0, 255, 0, 0, 2, 0, 1, 0, 0xea, 0x60, 0, 0x27, 0x10, 0x80, 0, 0xea, 0x60, 0, 0x2a, 0xf8]); + m.extend([0x03, 0xe8, 0x03, 0xe8, 0, 0, 0, 0, 0]); + // Binary data (16 octets): 8 unused bits, 16 bits a value, one octet of padding. + m.extend([0, 0, 16, 8, 0, 0, 0, 0, 0, 0, 16]); + m.extend(a.to_be_bytes()); + m.extend(b.to_be_bytes()); + m.push(0); + m.extend(b"7777"); + m +} + +/// `layer.addUrl` with `"bytes"` asks for that range of a GRIB file only and reads it as the file +/// (#2428): the second of two records, by its name or by `"format"`. A server that ignores the +/// range, an answer shorter than the range, and a range of another format are refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_grib_files_byte_range_is_added_as_the_file() { + let mut file = grib1_message(1, 2); + file.extend(grib1_message(3, 4)); + assert_eq!(file.len(), 176); + let (base, sent) = serve_ranges(file.clone()); + let mut s = Session::new(Project::default()); + for p in [ + json!({"url": format!("{base}/run/PREC.grb"), "bytes": [88, 175]}), + json!({"url": format!("{base}/record?id=2"), "bytes": [88, 175], "format": "grib"}), + ] { + let r = s.run("layer.addUrl", &p).unwrap(); + let layer = s.map().layer(r["layer"].as_u64().unwrap() as u32).unwrap(); + let raster = layer.raster.as_ref().unwrap().data.as_ref().unwrap(); + assert_eq!(raster.bands[0].data, vec![3.0, 4.0], "{p}"); + } + assert_eq!(sent.load(std::sync::atomic::Ordering::Relaxed), 176, "the range alone, twice"); + // A range past the file's end: the 88 octets there aren't the 100 asked for. + let e = s.run("layer.addUrl", &json!({"url": format!("{base}/PREC.grb"), "bytes": [88, 187]})).unwrap_err(); + assert!(e.contains("answered 88 octets of the 100 asked for"), "{e}"); + // A server that answers the whole file to a range. + let (whole, _) = serve_file(file, false); + let e = s.run("layer.addUrl", &json!({"url": format!("{whole}/PREC.grb"), "bytes": [88, 175]})).unwrap_err(); + assert!(e.contains(crate::render::rustgis_tiles::cache::NO_RANGES), "{e}"); + // From octet 0, refused once its answer is longer than the range, and said so. + let e = s.run("layer.addUrl", &json!({"url": format!("{whole}/PREC.grb"), "bytes": [0, 87]})).unwrap_err(); + assert!(e.contains("more than the range asked for") && e.contains(crate::render::rustgis_tiles::cache::NO_RANGES), "{e}"); + // Asked wrongly, or of another format: refused before anything is fetched. + let grb = format!("{base}/PREC.grb"); + for (p, said) in [ + (json!({"url": format!("{base}/a.tif"), "bytes": [0, 9]}), "a range of another format isn't a file"), + (json!({"url": format!("{base}/a.tif"), "bytes": [0, 9], "format": "grib"}), "the address names a.tif"), + (json!({"url": grb, "bytes": [9, 0]}), "comes after the last"), + (json!({"url": grb, "bytes": [0, 64 << 20]}), "more than a range may have (64 MB)"), + (json!({"url": grb, "bytes": [0, u64::MAX]}), "more than a range may have (64 MB)"), + (json!({"url": grb, "bytes": "0-9"}), "two octet offsets"), + (json!({"url": grb, "bytes": [0, 9], "format": "tiff"}), "the one format a byte range is read as"), + (json!({"url": grb, "format": "grib"}), "\"format\" goes with \"bytes\""), + (json!({"url": grb, "bytes": [0, 9], "as": "scan"}), "doesn't go with \"as\""), + ] { + let before = sent.load(std::sync::atomic::Ordering::Relaxed); + let e = s.run("layer.addUrl", &p).unwrap_err(); + assert!(e.contains(said), "{p}: {e}"); + assert_eq!(sent.load(std::sync::atomic::Ordering::Relaxed), before, "{p}"); + } +} + /// Each page of a map series is georeferenced with its own view, not the first page's (#1191). #[test] fn a_map_series_pdf_georeferences_each_page_with_its_view() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e6d241e2a8..6983ffa343 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5624,6 +5624,9 @@ impl RustGisApp { if public || check_origin.is_some() || claim.is_none() { rustgis_engine::cmd::layer::mark_url_reach(bound_url, check_origin, public); } + // A byte range of a GRIB file (`"bytes"`), checked as the command checks it: only that + // range is downloaded (below), never probed, and read as the file. + 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()); @@ -5656,7 +5659,7 @@ impl RustGisApp { && !tiff && rustgis_engine::cmd::layer::is_unnamed_url(url) && ["service", "coverage"].iter().all(|k| p.get(*k).and_then(Value::as_bool) != Some(true)); - if !window && (remote || tiff || unnamed) && !scan && p.get("whole").and_then(Value::as_bool) != Some(true) { + if range.is_none() && !window && (remote || tiff || unnamed) && !scan && p.get("whole").and_then(Value::as_bool) != Some(true) { let slot: Slot> = Slot::default(); let land = slot.clone(); if remote { @@ -5694,7 +5697,10 @@ impl RustGisApp { self.ui.cog_probes.push((probe, claim, slot)); return Ok(Value::Null); } - let url = address; + let url = match range { + Some(r) => rustgis_engine::cmd::layer::ranged_address(&address, r), + None => address, + }; // The request receipt is correlation only; its admitted claim stays outside JSON. let mut q = json!({"url": url}); for k in ["name", "layer", "crs", "connection", "from"] { @@ -5776,6 +5782,9 @@ impl RustGisApp { public, if q.get("geolibreProject").and_then(Value::as_bool) == Some(true) { rustgis_engine::map::geolibre::MAX_TEXT + } else if let Some((first, last)) = range { + // A range's answer may be no longer than the range. + usize::try_from(last - first + 1).unwrap_or(usize::MAX) } else { rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD }, @@ -5875,6 +5884,10 @@ impl RustGisApp { }); for (id, url, mut p, r) in landed { let origin = connectiontree::take_origin_key(&mut p); + // A range's answer shorter than the range is refused, never read as the record. + let r = r + .map_err(|e| rustgis_engine::cmd::layer::range_failed(&url, e)) + .and_then(|bytes| rustgis_engine::cmd::layer::check_range_answer(&url, &bytes).map(|()| bytes)); match r { Ok(bytes) => { let landed = serviceui::Landed { id, url, params: p, origin }; diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 19063fea3d..68e392dbaa 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -649,7 +649,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 on regular latitude/longitude grids, with bitmaps (masked points 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 (complex, JPEG 2000, PNG) 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. | +| 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 on regular latitude/longitude grids, with bitmaps (masked points 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 (complex, JPEG 2000, PNG) 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. | | Rasters GDAL reads | `.img`, `.hgt`, `.dem`, `.dt0`–`.dt2`, `.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. | For GDAL subdatasets, the notice counts the other variables, names at most the first 20, and From cdd3ab9967be5079e2393fef57f00aff12bd9861 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 07:08:34 -0300 Subject: [PATCH 2/3] fix(engine): GRIB range review round 1 (#2669) - A plugin's range, left to the app, is completed with its ranged address: download_params accepts that address of the claim's own url and bytes, and no other. - A range's answer must start a GRIB message; any other is refused, naming the format its octets read as, never added by its sniffed name. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layer.rs | 11 ++++++++-- crates/engine/src/policy/downloads.rs | 11 ++++++++++ crates/engine/src/tests.rs | 30 +++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 67ad4b1537..5b91ab9488 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5261,8 +5261,9 @@ pub fn ranged_address(url: &str, (first, last): (u64, u64)) -> String { format!("{url}{}{first}-{last}", crate::render::rustgis_tiles::cache::RANGE) } -/// A range's answer is as long as the range: a server answering fewer octets (a range past the -/// file's end) is refused, never read as the record. Other addresses pass. +/// A range's answer is as long as the range and starts a GRIB message: a server answering fewer +/// octets (a range past the file's end), or a range that isn't a record (whatever its octets read +/// as, said), is refused, never read as the record. Other addresses pass. pub fn check_range_answer(url: &str, bytes: &[u8]) -> Result<(), String> { match crate::render::rustgis_tiles::cache::split_range(url) { (_, Some((first, last))) if bytes.len() as u64 != (last - first).saturating_add(1) => Err(format!( @@ -5270,6 +5271,12 @@ pub fn check_range_answer(url: &str, bytes: &[u8]) -> Result<(), String> { bytes.len(), (last - first).saturating_add(1) )), + (_, Some(_)) if !bytes.starts_with(b"GRIB") => Err(match rustgis_data::io::sniff_extension(bytes) { + Some(ext) => format!( + "the range doesn't start a GRIB message: its octets read as a .{ext} file (check the range against the file's inventory)" + ), + None => "the range doesn't start a GRIB message (check the range against the file's inventory)".to_string(), + }), _ => Ok(()), } } diff --git a/crates/engine/src/policy/downloads.rs b/crates/engine/src/policy/downloads.rs index 26d42c7422..9450abeeb0 100644 --- a/crates/engine/src/policy/downloads.rs +++ b/crates/engine/src/policy/downloads.rs @@ -14,6 +14,14 @@ use std::{ /// from the request, and a landed window holding any other key is refused. pub const WINDOW_KEYS: [&str; 3] = ["bbox", "cellSize", "cog"]; +/// The address a claim's GRIB range is downloaded from ([`crate::cmd::layer::ranged_address`]), +/// when it asks for one (`"bytes"`). +fn ranged_claim(p: &Value) -> Option { + let url = p.get("url")?.as_str()?; + let range = crate::cmd::layer::byte_range(p, url).ok()??; + Some(crate::cmd::layer::ranged_address(url, range)) +} + /// What a window the app read off the frame says it read (`"window"`, #1330) is what its request /// asked for: a box, and its cell size and `"cog"` if the request gave them, nothing else. fn asked_window(asked: &Value, window: &Value) -> bool { @@ -485,6 +493,9 @@ impl Session { && crate::cmd::bool_value(value) == Some(false) && claim.params.get(key).and_then(crate::cmd::bool_value) == Some(true)) || (key == "window" && asked_window(&claim.params, value)) + // A GRIB file's range (`"bytes"`): the app downloads, and completes with, the + // address that range makes of the claim's own, and no other. + || (key == "url" && ranged_claim(&claim.params).is_some_and(|u| value.as_str() == Some(u.as_str()))) // How an ArcGIS service draws the layer, read by the app from its description // while reading its features (#2080). || (key == "drawingInfo" && value.is_object() && claim.params.get("service").and_then(Value::as_bool) == Some(true)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96d0423f2c..402db84f98 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48908,6 +48908,12 @@ fn a_grib_files_byte_range_is_added_as_the_file() { // From octet 0, refused once its answer is longer than the range, and said so. let e = s.run("layer.addUrl", &json!({"url": format!("{whole}/PREC.grb"), "bytes": [0, 87]})).unwrap_err(); assert!(e.contains("more than the range asked for") && e.contains(crate::render::rustgis_tiles::cache::NO_RANGES), "{e}"); + // A range that isn't a GRIB message is refused, whatever its octets read as. + let text = br#"{"type": "FeatureCollection", "features": []}"#.to_vec(); + let last = text.len() as u64 - 1; + let (other, _) = serve_ranges(text); + let e = s.run("layer.addUrl", &json!({"url": format!("{other}/record"), "bytes": [0, last], "format": "grib"})).unwrap_err(); + assert!(e.contains("the range doesn't start a GRIB message"), "{e}"); // Asked wrongly, or of another format: refused before anything is fetched. let grb = format!("{base}/PREC.grb"); for (p, said) in [ @@ -48928,6 +48934,30 @@ fn a_grib_files_byte_range_is_added_as_the_file() { } } +/// A plugin's command asking for a GRIB file's range leaves it to the app, which completes the +/// download with the range's address (the claim's own address with its range): it is added. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_plugin_commands_grib_range_is_added_when_the_app_completes_it() { + let mut file = grib1_message(1, 2); + file.extend(grib1_message(3, 4)); + let (base, _) = serve_ranges(file.clone()); + let mut s = world(); + plugin("eng-grib-range", &["edit", "network"]); + let url = format!("{base}/run/PREC.grb"); + let p = json!({"op": "layer.addUrl", "params": {"url": url, "bytes": [88, 175], "name": "Rain"}}); + s.run_leaving_downloads("plugin:eng-grib-range/f", &p).unwrap(); + let asked = s.take_url_requests(); + assert_eq!(asked.len(), 1); + let id = s.download_started_for(&asked[0]).unwrap(); + assert!(s.download_landed(id, file[88..].to_vec())); + // As the app completes it: the address it downloaded, with the request's name. + let add = json!({"id": id, "url": crate::cmd::layer::ranged_address(&url, (88, 175)), "name": "Rain"}); + s.complete_download(id, &add).unwrap(); + let layer = s.map().layer_by_name("Rain").filter(|l| l.is_raster()).unwrap(); + assert_eq!(layer.raster.as_ref().unwrap().data.as_ref().unwrap().bands[0].data, vec![3.0, 4.0]); +} + /// Each page of a map series is georeferenced with its own view, not the first page's (#1191). #[test] fn a_map_series_pdf_georeferences_each_page_with_its_view() { From 75695c8e431da069aee667b30fb89e833e0a0525 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 08:13:20 -0300 Subject: [PATCH 3/3] fix(engine,tiles): GRIB range review round 2 (#2669) - Without "bytes", a "format" other than grib is ignored again, as it was before ranges. - A 206 whose Content-Range starts elsewhere or runs past the range is refused, never read as the range. - A range that times out isn't told to download the whole file. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layer.rs | 5 ++++- crates/engine/src/tests.rs | 21 ++++++++++++++++++++- crates/tiles/src/cache.rs | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 5b91ab9488..f3522143ab 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5213,6 +5213,8 @@ pub fn byte_range(p: &Value, url: &str) -> 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, + // Without a range, another format is left as before ranges (an unknown key, ignored). + Some(_) if p.get("bytes").is_none_or(Value::is_null) => false, Some(_) => return Err("\"format\" is \"grib\", the one format a byte range is read as".into()), }; let asked = match p.get("bytes") { @@ -5315,7 +5317,8 @@ fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), publi } else { cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) }; - let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(cache::large_file_hint).map_err(named)?; + // Without `large_file_hint`: a range timing out isn't helped by downloading the whole file. + let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(named)?; check_range_answer(&ranged, &bytes).map_err(named)?; let name = url_file_name(&ranged, &bytes).map_err(named)?; super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 402db84f98..a10a572870 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48902,12 +48902,31 @@ fn a_grib_files_byte_range_is_added_as_the_file() { let e = s.run("layer.addUrl", &json!({"url": format!("{base}/PREC.grb"), "bytes": [88, 187]})).unwrap_err(); assert!(e.contains("answered 88 octets of the 100 asked for"), "{e}"); // A server that answers the whole file to a range. - let (whole, _) = serve_file(file, false); + let (whole, _) = serve_file(file.clone(), false); let e = s.run("layer.addUrl", &json!({"url": format!("{whole}/PREC.grb"), "bytes": [88, 175]})).unwrap_err(); assert!(e.contains(crate::render::rustgis_tiles::cache::NO_RANGES), "{e}"); // From octet 0, refused once its answer is longer than the range, and said so. let e = s.run("layer.addUrl", &json!({"url": format!("{whole}/PREC.grb"), "bytes": [0, 87]})).unwrap_err(); assert!(e.contains("more than the range asked for") && e.contains(crate::render::rustgis_tiles::cache::NO_RANGES), "{e}"); + // A server answering other octets of the same length (the first record, `Content-Range: + // bytes 0-87/176`) for the second record asked for: refused, never read as it. + let first = file[..88].to_vec(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let wrong = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + use std::io::{Read, Write}; + for mut c in listener.incoming().flatten() { + let _ = c.read(&mut [0u8; 4096]); + let head = "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-87/176\r\nContent-Length: 88\r\nConnection: close\r\n\r\n"; + let _ = c.write_all(head.as_bytes()).and_then(|()| c.write_all(&first)); + } + }); + let e = s.run("layer.addUrl", &json!({"url": format!("{wrong}/PREC.grb"), "bytes": [88, 175]})).unwrap_err(); + assert!(e.contains("the server answered octets 0-87, not the 88-175 asked for"), "{e}"); + // Without a range, "format" is left as it was before ranges: not refused. + let text = br#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [1, 2]}}]}"#; + let (plain, _) = serve_ranges(text.to_vec()); + s.run("layer.addUrl", &json!({"url": format!("{plain}/points.geojson"), "format": "geojson"})).unwrap(); // A range that isn't a GRIB message is refused, whatever its octets read as. let text = br#"{"type": "FeatureCollection", "features": []}"#.to_vec(); let last = text.len() as u64 - 1; diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 626c3682b0..eb85437ffc 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -3409,6 +3409,14 @@ mod native { len.trim().parse::().ok().filter(|len| *len > 0) } + /// The octets a `Content-Range` header says an answer holds (`bytes 200-299/1000`: 200 and + /// 299); none when it can't be read. + pub(super) fn content_range_span(header: &str) -> Option<(u64, u64)> { + let span = header.trim().strip_prefix("bytes")?.trim_start().split('/').next()?; + let (a, b) = span.split_once('-')?; + Some((a.trim().parse().ok()?, b.trim().parse().ok()?)) + } + /// The sign-ins' tokens a hop to `at` carries, as (header, value, whether a refusal must be /// status-only): none for a `bare` request (signed for S3, or read anonymously, as a plugin's /// `host.fetch` is), at any hop. @@ -3655,6 +3663,15 @@ mod native { { return Err(rustgis_data::diagnostics::message_with_address(url, super::NO_RANGES).into()); } + // A range answered (206) with other octets than asked for: never read as the range. An + // answer may end sooner (the file's end), never start elsewhere or run past the range. + if let Some((a, b)) = range.filter(|_| !whole) + && let Some((from, to)) = resp.headers().get("content-range").and_then(|v| v.to_str().ok()).and_then(content_range_span) + && (from != a || to > b) + { + let why = format!("the server answered octets {from}-{to}, not the {a}-{b} asked for"); + return Err(rustgis_data::diagnostics::message_with_address(url, &why).into()); + } let mut buf = Vec::new(); if !resp.status().is_success() { return Err(format!("HTTP {}", resp.status().as_u16()).into());