From 4ff1db32d6c93a1e7e47d0fa43d306b812f8141c Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Thu, 26 Nov 2026 23:33:19 -0500 Subject: [PATCH 01/33] feat(STAC): Details reads the item's own document: Formatted and JSON tabs, with Add to map, Download and Copy link per asset Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/ui-egui/src/stacui.rs | 499 +++++++++++++++++++++++++++++++++-- docs/user-guide/web-data.md | 10 +- 2 files changed, 491 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index f54e57ff63..c3c0b17267 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -198,6 +198,8 @@ pub struct State { pub chosen: Vec, /// The item whose properties are shown. pub details: Option, + /// The JSON view of the item whose details are open: its own document, read or read from. + json: Option, /// Whether `info` is a search's count (kept when a catalog's children land after it). counted: bool, /// Items' preview pictures, by address. @@ -270,6 +272,7 @@ impl Default for State { sort_is_default: false, chosen: Vec::new(), details: None, + json: None, counted: false, thumbs: Default::default(), footprints: None, @@ -323,6 +326,26 @@ fn post_service(app: &mut RustGisApp, url: &str, body: String) -> Answer { } } +/// The most of an item's JSON the pane draws: more is cut from the view (Copy still takes it all). +const JSON_SHOWN_BYTES: usize = 200_000; + +/// The JSON view of one item (by its place in the list). +struct JsonView { + /// Whether the JSON text is the tab shown (else the formatted page). + text_tab: bool, + item: usize, + raw: Raw, +} + +/// An item's own document as the catalog sent it, for the JSON view. +enum Raw { + /// Being read from the item's own address. + Loading(Answer), + /// Ready: the whole text (what Copy takes), how much of it the pane draws, and a line saying + /// what is not the catalog's whole document or why not (read failed, text cut). + Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value }, +} + /// An item's preview picture: being fetched, shown, or not to be had. enum Thumb { Loading(BytesAnswer), @@ -426,6 +449,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { poll_walk(app, ctx); poll_loading(app, ctx); poll_preparing(app, ctx); + poll_json(app, ctx); stop_stale_drawing(app); let pending = match &app.ui.stac.waiting { Some((Asked::Link { url, opened }, _)) => Some((*opened, url.clone())), @@ -503,6 +527,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { st.info = Some(i18n::fmt("{count}. {note}", &[("count", st.info.as_deref().unwrap_or(&count)), ("note", note)])); } st.details = None; + st.json = None; st.counted = true; st.chosen = items.iter().map(|i| i.pick(None).map(|a| a.key.clone()).unwrap_or_default()).collect(); st.items = items; @@ -649,6 +674,7 @@ fn poll_walk(app: &mut RustGisApp, ctx: &egui::Context) { i18n::fmt("Showing {n} items (more match: narrow the search)", &[("n", &n)]) }); st.details = None; + st.json = None; st.counted = true; let items = walk.into_items(); st.chosen = items.iter().map(|i| i.pick(None).map(|a| a.key.clone()).unwrap_or_default()).collect(); @@ -1982,6 +2008,10 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { } want_thumbs(app); let (mut zoom, mut add, mut details) = (None, None, None); + // The view picked on an open card (true: JSON), whether Copy was clicked, and whether Cancel. + let (mut view, mut copy, mut cancel) = (None::, false, false); + // The asset picked in an open card's Formatted tab: its item's place and its key. + let mut asset: Option<(usize, String)> = None; // The band combination picked on a card: its item's place and the combination's id. #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] let mut bands: Option<(usize, &'static str)> = None; @@ -2088,20 +2118,49 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { ui.weak(tl!("Bands left out")).on_hover_text(cut); } } - if ui.selectable_label(st.details == Some(i), tl!("Details")).clicked() { + if ui.add(egui::Button::new(tl!("Details")).selected(st.details == Some(i))).clicked() { details = Some(i); } }); }); }); - if st.details == Some(i) { - properties(ui, i, item); + if st.details == Some(i) + && let Some(j) = st.json.as_ref().filter(|j| j.item == i) + { + let did = inspector(ui, j, item); + view = view.or(did.tab); + (copy, cancel) = (copy || did.copy, cancel || did.cancel); + if let Some(key) = did.add { + asset = Some((i, key)); + } } }); } }); if let Some(i) = details { - app.ui.stac.details = if app.ui.stac.details == Some(i) { None } else { Some(i) }; + let open = app.ui.stac.details != Some(i); + app.ui.stac.details = open.then_some(i); + // Opening a card reads its item's own document (another card's view, or a read still + // going, is dropped); closing it drops the view. + app.ui.stac.json = None; + if open { + start_json(app, i); + } + } + if let (Some(text_tab), Some(j)) = (view, app.ui.stac.json.as_mut()) { + j.text_tab = text_tab; + } + if let Some((i, key)) = asset { + let Some(item) = app.ui.stac.items.get(i).cloned() else { return }; + add_item_asset(app, &item, Some(key.as_str())); + } + if cancel { + // Stops the read, and with it the card's details: nothing else is there to show. + app.ui.stac.json = None; + app.ui.stac.details = None; + } + if copy && let Some(JsonView { raw: Raw::Shown { text, .. }, .. }) = &app.ui.stac.json { + ui.ctx().copy_text(text.clone()); } if let Some(e) = zoom.and_then(|i| app.ui.stac.items.get(i)).and_then(|i| i.bbox) { app.session.zoom_to(&rustgis_engine::geom::Extent::new(e[0], e[1], e[2], e[3])); @@ -2194,24 +2253,269 @@ fn add_item_index(app: &mut RustGisApp, _item: &Item, _index: &str) { app.ui.stac.error = Some(tl!("Indices are made on the desktop for now").to_string()); } -/// An item's properties, a row each (the first hundred, long values cut). -fn properties(ui: &mut egui::Ui, i: usize, item: &Item) { - let Some(props) = item.properties.as_ref().and_then(|p| p.as_object()) else { - ui.label(egui::RichText::new(tl!("No properties")).weak()); +/// The catalog's document pretty-printed, and how many of its bytes the pane draws (a cut on a +/// character boundary). Not JSON is an error: it is not shown as the item. +fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> { + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]))?; + let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?; + let mut drawn = text.len().min(JSON_SHOWN_BYTES); + while !text.is_char_boundary(drawn) { + drawn -= 1; + } + Ok((text, drawn, value)) +} + +/// What the pane keeps of an item when it can't show the catalog's own document: its properties +/// (the first hundred plain ones, long text cut), assets and footprint as RustGIS read them. +fn trimmed_text(item: &Item) -> (String, usize, serde_json::Value) { + let doc = stac::item_json_with(item, true); + let text = serde_json::to_string_pretty(&doc).unwrap_or_default(); + let mut drawn = text.len().min(JSON_SHOWN_BYTES); + while !text.is_char_boundary(drawn) { + drawn -= 1; + } + (text, drawn, doc) +} + +/// The line saying a view is not the whole document: text cut from the view, then why the +/// document wasn't used. +fn raw_note(text: &str, drawn: usize, why: Option) -> Option { + let cut = (drawn < text.len()).then(|| { + i18n::fmt( + "Showing the first {shown} of {total} bytes; Copy takes all of it", + &[("shown", &drawn.to_string()), ("total", &text.len().to_string())], + ) + }); + match (why, cut) { + (Some(why), Some(cut)) => Some(format!("{why} {cut}")), + (why, cut) => why.or(cut), + } +} + +/// Opens the inspector of item `i`: the item's own document read from its address, off the frame; +/// or, when it has none (or may not be read from there), what RustGIS read of it, with the reason. +fn start_json(app: &mut RustGisApp, i: usize) { + let Some(item) = app.ui.stac.items.get(i).cloned() else { return }; + let trimmed = |why: String| { + let (text, drawn, doc) = trimmed_text(&item); + let note = raw_note(&text, drawn, Some(why)); + Raw::Shown { text, drawn, note, doc } + }; + let Some(url) = item.url.clone() else { + let why = tl!( + "This item has no address of its own to read, so this is what RustGIS read of it: the first 100 plain properties, long text cut." + ); + app.ui.stac.json = Some(JsonView { item: i, text_tab: false, raw: trimmed(why.to_string()) }); return; }; - egui::Grid::new(("stac_props", i)).num_columns(2).striped(true).spacing(vec2(10.0, 2.0)).show(ui, |ui| { - for (k, v) in props.iter().take(100) { - let text = match v { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), - }; - let short: String = text.chars().take(160).collect(); + // The address is the document's own claim: it is read under the reach the item was found with. + let public = item.origin_reach == Reach::Public; + let from = item_document_origin(app, &item); + let ceiling = rustgis_engine::cmd::layer::origin_ceiling(Some(&from), public); + let raw = match address::check_reach(&url, ceiling) { + Ok(()) => Raw::Loading(fetch_service(app, &url, public)), + Err(e) => trimmed(i18n::fmt( + "{url} was not read: {e}. This is what RustGIS read of the item instead: the first 100 plain properties, long text cut.", + &[("url", &rustgis_engine::sources::address_in_message(&url)), ("e", &e)], + )), + }; + app.ui.stac.json = Some(JsonView { item: i, text_tab: false, raw }); +} + +/// Lands an item's own document in the inspector. +fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { + let Some(JsonView { item: i, text_tab, raw: Raw::Loading(slot) }) = &app.ui.stac.json else { return }; + let (i, text_tab) = (*i, *text_tab); + let Some(r) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + }; + let Some(item) = app.ui.stac.items.get(i).cloned() else { + app.ui.stac.json = None; + return; + }; + let raw = match r.and_then(|f| raw_text(&f.bytes)) { + Ok((text, drawn, doc)) => { + let note = raw_note(&text, drawn, None); + Raw::Shown { text, drawn, note, doc } + } + Err(e) => { + let (text, drawn, doc) = trimmed_text(&item); + let why = i18n::fmt( + "The item's own document was not read: {e}. This is what RustGIS read of it instead: the first 100 plain properties, long text cut.", + &[("e", &e)], + ); + let note = raw_note(&text, drawn, Some(why)); + Raw::Shown { text, drawn, note, doc } + } + }; + app.ui.stac.json = Some(JsonView { item: i, text_tab, raw }); +} + +/// What was clicked in an inspector. +#[derive(Default)] +struct Inspected { + /// A tab: true for the JSON text. + tab: Option, + copy: bool, + /// The key of an asset to add to the map. + add: Option, + cancel: bool, +} + +/// The inspector under an open card: the Formatted and JSON tabs, then the tab shown, or a +/// spinner and Cancel while the document is read. +fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { + let mut did = Inspected::default(); + ui.horizontal(|ui| { + if ui.add(egui::Button::new(tl!("Formatted")).selected(!view.text_tab)).clicked() { + did.tab = Some(false); + } + if ui.add(egui::Button::new(tl!("JSON")).selected(view.text_tab)).clicked() { + did.tab = Some(true); + } + if view.text_tab && matches!(view.raw, Raw::Shown { .. }) { + did.copy = ui.button(tl!("Copy JSON")).clicked(); + } + }); + match &view.raw { + Raw::Loading(_) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(tl!("Reading the item…")); + did.cancel = ui.button(tl!("Cancel")).clicked(); + }); + } + Raw::Shown { text, drawn, note, doc } => { + if let Some(note) = note { + ui.label(egui::RichText::new(note).small().weak()); + } + if view.text_tab { + egui::ScrollArea::both().id_salt(("stac_json", view.item)).max_height(260.0).show(ui, |ui| { + let mut shown = text.get(..*drawn).unwrap_or_default(); + ui.add(egui::TextEdit::multiline(&mut shown).code_editor().desired_width(f32::INFINITY).interactive(true)); + }); + } else { + did.add = formatted(ui, view.item, doc, item); + } + } + } + did +} + +/// The most rows a section of the formatted page draws; the rest is said, not dropped. +const FORMATTED_ROWS: usize = 200; + +/// A value as one short line: text as it is, anything else as JSON, cut at 160 characters. +fn short_value(v: &serde_json::Value) -> String { + let text = match v { + serde_json::Value::String(s) => s.clone(), + other => other.to_string(), + }; + let mut short: String = text.chars().take(160).collect(); + if short.len() < text.len() { + short.push('…'); + } + short +} + +/// A titled section of two-column rows (a label and a value): the rows given, and how many more +/// the document had. +fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: &str, rows: Vec<(String, String)>, total: usize) { + if rows.is_empty() { + return; + } + ui.add_space(4.0); + ui.label(egui::RichText::new(title).strong()); + egui::Grid::new(id).num_columns(2).striped(true).spacing(vec2(10.0, 2.0)).show(ui, |ui| { + for (k, v) in &rows { ui.label(egui::RichText::new(k).small()); - ui.add(egui::Label::new(egui::RichText::new(short).small().weak()).wrap()); + ui.add(egui::Label::new(egui::RichText::new(v).small().weak()).wrap()); ui.end_row(); } }); + if total > rows.len() { + let more = (total - rows.len()).to_string(); + ui.label(egui::RichText::new(i18n::fmt("{n} more are not shown: see JSON", &[("n", &more)])).small().weak()); + } +} + +/// An item's document laid out as a page: what it is, its properties, its assets and its links. +/// Only what the document holds is drawn; a section it lacks is left out. +fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, item: &Item) -> Option { + let field = |k: &str| doc.get(k).filter(|v| !v.is_null()).map(short_value); + let head: Vec<(String, String)> = [ + (tl!("ID"), field("id")), + (tl!("Collection"), field("collection")), + (tl!("Extent"), field("bbox")), + (tl!("Footprint"), doc.get("geometry").and_then(|g| g.get("type")).map(short_value)), + (tl!("Extensions"), field("stac_extensions")), + ] + .into_iter() + .filter_map(|(k, v)| Some((k.to_string(), v?))) + .collect(); + let n = head.len(); + section(ui, ("stac_head", id), tl!("Item"), head, n); + if let Some(props) = doc.get("properties").and_then(|p| p.as_object()) { + let rows = props.iter().take(FORMATTED_ROWS).map(|(k, v)| (k.clone(), short_value(v))).collect(); + section(ui, ("stac_props", id), tl!("Properties"), rows, props.len()); + } + let mut add = None; + if let Some(assets) = doc.get("assets").and_then(|a| a.as_object()) { + ui.add_space(4.0); + ui.label(egui::RichText::new(tl!("Assets")).strong()); + for (key, a) in assets.iter().take(FORMATTED_ROWS) { + let part = |k: &str| a.get(k).filter(|v| !v.is_null()).map(short_value); + let detail = [part("title"), part("type"), part("roles")].into_iter().flatten().collect::>().join(" · "); + // The address as the item resolves it (a relative one against the item), else as written. + let href = item.assets.iter().find(|x| &x.key == key).map(|x| x.href.clone()).or_else(|| part("href")); + // Offered to the browser only where the item may read it from and it needs no signing. + let web = item + .asset_href(Some(key)) + .ok() + .map(|(_, h)| h) + .filter(|h| h.starts_with("https://") || h.starts_with("http://")) + .filter(|h| !stac::needs_signing(h)); + ui.push_id(("stac_asset", id, key), |ui| { + ui.label(egui::RichText::new(key).small().strong()); + if !detail.is_empty() { + ui.add(egui::Label::new(egui::RichText::new(detail).small().weak()).wrap()); + } + if let Some(h) = &href { + ui.add( + egui::Label::new(egui::RichText::new(short_value(&serde_json::Value::String(h.clone()))).small().weak()).truncate(), + ) + .on_hover_text(h); + } + ui.horizontal(|ui| { + if ui.add(egui::Button::new(tl!("Add to map")).small()).on_hover_text(tl!("Add this asset to the map")).clicked() { + add = Some(key.clone()); + } + if let Some(h) = &web { + ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(h); + } + if let Some(h) = &href + && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(h).clicked() + { + ui.ctx().copy_text(h.clone()); + } + }); + }); + } + if assets.len() > FORMATTED_ROWS { + let more = (assets.len() - FORMATTED_ROWS).to_string(); + ui.label(egui::RichText::new(i18n::fmt("{n} more are not shown: see JSON", &[("n", &more)])).small().weak()); + } + } + if let Some(links) = doc.get("links").and_then(|l| l.as_array()) { + let rows = links + .iter() + .take(FORMATTED_ROWS) + .map(|l| (l.get("rel").map(short_value).unwrap_or_default(), l.get("href").map(short_value).unwrap_or_default())) + .collect(); + section(ui, ("stac_links", id), tl!("Links"), rows, links.len()); + } + add } #[cfg(test)] @@ -3468,4 +3772,167 @@ mod tests { assert!(notices.iter().any(|n| n.text.contains("1 catalog links were refused"))); assert!(notices.iter().any(|n| n.text.contains("1 catalog links were left out because their addresses"))); } + + /// A public item, as a search of `https://stac.example/api` found it: with its own address when `own`. + fn json_test_item(own: bool) -> Item { + let mut raw = json!({ + "type": "Feature", "id": "scene-1", "collection": "c", "bbox": [0.0, 0.0, 1.0, 1.0], + "properties": {"datetime": "2025-01-01T00:00:00Z"}, + "assets": {"visual": {"href": "https://stac.example/a.tif", "type": "image/tiff; application=geotiff; profile=cloud-optimized"}}, + }); + if own { + raw["links"] = json!([{"rel": "self", "href": "https://stac.example/api/collections/c/items/scene-1"}]); + } + let item = stac::parse_item_from_origin(raw.to_string().as_bytes(), &Origin::named("https://stac.example/api/search")).unwrap(); + assert_eq!(item.origin_reach, Reach::Public); + item + } + + #[test] + fn an_items_json_is_pretty_cut_on_a_character_boundary_and_not_json_is_refused() { + let (text, drawn, _) = raw_text(br#"{"a":1}"#).unwrap(); + assert!(drawn == text.len() && text.contains("\"a\": 1")); + assert_eq!(raw_note(&text, drawn, None), None, "a whole document has no note"); + // More than the pane draws: cut where a character ends, and said, with Copy taking it all. + let long = json!({"k": "é".repeat(JSON_SHOWN_BYTES)}); + let (text, drawn, _) = raw_text(long.to_string().as_bytes()).unwrap(); + assert!(drawn < text.len() && drawn <= JSON_SHOWN_BYTES && text.is_char_boundary(drawn)); + let note = raw_note(&text, drawn, Some("why.".into())).unwrap(); + assert!(note.starts_with("why.") && note.contains("Showing the first"), "{note}"); + assert!(raw_text(b"not a document").unwrap_err().contains("not JSON")); + } + + #[test] + fn json_without_an_own_address_shows_what_was_read_and_says_so_without_a_request() { + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = asked.clone(); + cache::set_fetcher(move |_, _| { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }); + let mut app = RustGisApp::with_sample(); + app.ui.stac.items = vec![json_test_item(false)]; + start_json(&mut app, 0); + let Some(JsonView { raw: Raw::Shown { text, note, .. }, .. }) = &app.ui.stac.json else { panic!("shown at once") }; + assert!(text.contains("scene-1")); + assert!(note.as_deref().unwrap_or("").contains("no address of its own"), "{note:?}"); + assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[test] + fn json_reads_the_items_own_document_and_a_failed_read_falls_back_with_the_reason() { + let _turn = crate::fetching::turn(); + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + let own = "https://stac.example/api/collections/c/items/scene-1"; + cache::set_fetcher(move |url, done| { + log.lock().unwrap().push(url.clone()); + // What RustGIS drops from an item: its links, here, past the self link. + let doc = json!({"type": "Feature", "id": "scene-1", "links": [{"rel": "alternate", "href": "https://stac.example/page"}]}); + done(Ok(doc.to_string().into_bytes())); + }); + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + app.ui.stac.items = vec![json_test_item(true)]; + start_json(&mut app, 0); + assert!(matches!(app.ui.stac.json, Some(JsonView { raw: Raw::Loading(_), .. }))); + poll_json(&mut app, &ctx); + let Some(JsonView { raw: Raw::Shown { text, note, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; + assert!(text.contains("\"alternate\""), "the catalog's own document, not the trimmed copy: {text}"); + assert_eq!(note, &None); + let asked = seen.lock().unwrap().clone(); + assert!(asked.len() == 1 && asked[0].ends_with(own), "{asked:?}"); + + // A read that fails (or isn't JSON) shows what RustGIS has, and why. + for failure in [Err("the server said no".to_string()), Ok(b"".to_vec())] { + let said = failure.clone(); + cache::set_fetcher(move |_, done| done(said.clone())); + start_json(&mut app, 0); + poll_json(&mut app, &ctx); + let Some(JsonView { raw: Raw::Shown { text, note, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; + assert!(text.contains("scene-1") && !text.contains("alternate")); + let note = note.as_deref().unwrap_or(""); + assert!(note.contains("was not read") && note.contains("what RustGIS read"), "{note}"); + } + } + + #[test] + fn details_opens_the_formatted_page_of_the_items_own_document_and_the_json_tab_shows_its_text() { + let _turn = crate::fetching::turn(); + use egui_kittest::kittest::Queryable; + cache::set_fetcher(|_, done| { + // More properties than the page draws, and a link RustGIS drops from an item. + let props: serde_json::Map = (0..250).map(|n| (format!("p{n:03}"), json!(n))).collect(); + let doc = json!({ + "type": "Feature", "id": "scene-1", "collection": "c", "properties": props, + "links": [{"rel": "alternate", "href": "https://stac.example/page"}], + }); + done(Ok(doc.to_string().into_bytes())); + }); + let mut app = RustGisApp::with_sample(); + app.ui.stac.chosen = vec![String::new()]; + app.ui.stac.items = vec![json_test_item(true)]; + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 900.0)) + .build_ui_state(|ui, app: &mut RustGisApp| results(app, ui), app); + h.step(); + assert!(h.query_by_label("Formatted").is_none(), "nothing is read until Details is opened"); + h.get_by_label("Details").click(); + h.step(); + let ctx = h.ctx.clone(); + poll_json(h.state_mut(), &ctx); + h.step(); + h.step(); + h.get_by_label("alternate"); + h.get_by_label("50 more are not shown: see JSON"); + assert!(h.state().ui.stac.json.as_ref().is_some_and(|j| !j.text_tab)); + h.get_by_label("JSON").click(); + h.step(); + assert!(h.state().ui.stac.json.as_ref().is_some_and(|j| j.text_tab)); + h.step(); + h.get_by_label("Copy JSON"); + } + + #[test] + fn an_assets_row_adds_it_to_the_map_and_offers_a_download_only_for_a_web_address() { + let _turn = crate::fetching::turn(); + use egui_kittest::kittest::Queryable; + cache::set_fetcher(|_, done| { + let doc = json!({ + "type": "Feature", "id": "scene-1", "collection": "c", + "assets": { + "visual": {"href": "https://stac.example/a.tif", "type": "image/tiff"}, + "bucket": {"href": "s3://stac-bucket/b.tif"}, + }, + }); + done(Ok(doc.to_string().into_bytes())); + }); + let mut app = RustGisApp::with_sample(); + app.ui.stac.chosen = vec![String::new()]; + app.ui.stac.items = vec![json_test_item(true)]; + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 900.0)) + .build_ui_state(|ui, app: &mut RustGisApp| results(app, ui), app); + h.step(); + h.get_by_label("Details").click(); + h.step(); + let ctx = h.ctx.clone(); + poll_json(h.state_mut(), &ctx); + h.step(); + h.step(); + // Both assets can be added and copied; only the https one is a download link. + assert_eq!(h.get_all_by_label("Add to map").count(), 2); + assert_eq!(h.get_all_by_label("Copy link").count(), 2); + assert_eq!(h.get_all_by_label("Download").count(), 1); + // The document's keys come out in order: bucket, then visual. + let first = h.get_all_by_label("Add to map").nth(1).unwrap(); + first.click(); + h.step(); + h.step(); + let said = h.state().ui.stac.error.clone(); + assert!(said.is_none(), "{said:?}"); + // The https asset was read (the s3 one wasn't asked for). + let notices = h.state().session.notices.iter().map(|n| n.text.clone()).collect::>(); + assert!(notices.iter().any(|n| n.contains("Reading https://stac.example/a.tif")), "{notices:?}"); + } } diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index f214ee76e3..e0f7b464ca 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -60,8 +60,14 @@ beside it, and other APIs with GET item search work. **Collections** lists what and **Find Items** shows up to 50 items as cards (with "Showing 50 of 1234 items" when the API says how many match) and draws their footprints as a layer. Each card has the item's preview picture when it has one, its id, a collection · date · -cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **Details** (the item's -properties). The asset chosen at first is `visual` (true colour) when there is one, else the first +cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **Details**. Details +reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, +its properties, its assets and its links, up to 200 rows a section with +the rest counted; each asset has **Add to map**, **Download** (a link to its web address, not offered for +an address that needs signing, such as Planetary Computer's) and **Copy link**) and **JSON** (the document as the catalog sent it, with **Copy JSON**; the first +200,000 bytes are drawn and Copy takes all of it). An item with no address of its own, or one the +network reach it was found with doesn't allow reading, shows what RustGIS read of it instead (the first 100 +plain properties, long text cut), with a line saying so. The asset chosen at first is `visual` (true colour) when there is one, else the first GeoTIFF, else the first point cloud, else the first data asset, preferring HTTP(S) assets. Cloud-optimised GeoTIFF, GeoParquet and FlatGeobuf assets are read in place, and PMTiles a tile at a time; other assets download whole (see [Files on the web](data-formats.md#files-on-the-web)). From 8c612b93f36c4b8f0c1cd3d1538b7229b0008781 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 15:46:33 -0500 Subject: [PATCH 02/33] fix(STAC): the inspector's asset links come from the fetched document, and an opened item link clears the old inspector Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/ui-egui/src/stacui.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index c3c0b17267..46249edcd8 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -343,7 +343,9 @@ enum Raw { Loading(Answer), /// Ready: the whole text (what Copy takes), how much of it the pane draws, and a line saying /// what is not the catalog's whole document or why not (read failed, text cut). - Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value }, + /// `base` is the address the document was read from (its relative links resolve against it); + /// none when the pane shows what RustGIS read instead. + Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value, base: Option }, } /// An item's preview picture: being fetched, shown, or not to be had. @@ -886,6 +888,8 @@ fn landed_link(app: &mut RustGisApp, requested_url: &str, r: Result { let note = raw_note(&text, drawn, None); - Raw::Shown { text, drawn, note, doc } + Raw::Shown { text, drawn, note, doc, base } } Err(e) => { let (text, drawn, doc) = trimmed_text(&item); @@ -2346,7 +2351,7 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { &[("e", &e)], ); let note = raw_note(&text, drawn, Some(why)); - Raw::Shown { text, drawn, note, doc } + Raw::Shown { text, drawn, note, doc, base: None } } }; app.ui.stac.json = Some(JsonView { item: i, text_tab, raw }); @@ -2386,7 +2391,7 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { did.cancel = ui.button(tl!("Cancel")).clicked(); }); } - Raw::Shown { text, drawn, note, doc } => { + Raw::Shown { text, drawn, note, doc, base } => { if let Some(note) = note { ui.label(egui::RichText::new(note).small().weak()); } @@ -2396,7 +2401,7 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { ui.add(egui::TextEdit::multiline(&mut shown).code_editor().desired_width(f32::INFINITY).interactive(true)); }); } else { - did.add = formatted(ui, view.item, doc, item); + did.add = formatted(ui, view.item, doc, base.as_deref(), item); } } } @@ -2442,7 +2447,7 @@ fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: /// An item's document laid out as a page: what it is, its properties, its assets and its links. /// Only what the document holds is drawn; a section it lacks is left out. -fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, item: &Item) -> Option { +fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option<&str>, item: &Item) -> Option { let field = |k: &str| doc.get(k).filter(|v| !v.is_null()).map(short_value); let head: Vec<(String, String)> = [ (tl!("ID"), field("id")), @@ -2467,8 +2472,11 @@ fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, item: &Item) for (key, a) in assets.iter().take(FORMATTED_ROWS) { let part = |k: &str| a.get(k).filter(|v| !v.is_null()).map(short_value); let detail = [part("title"), part("type"), part("roles")].into_iter().flatten().collect::>().join(" · "); - // The address as the item resolves it (a relative one against the item), else as written. - let href = item.assets.iter().find(|x| &x.key == key).map(|x| x.href.clone()).or_else(|| part("href")); + // The document's own address for the asset, a relative one resolved against the address + // the document was read from (as written when it can't be). The full address, not the + // shortened label, is what Copy link takes. + let href = + a.get("href").and_then(|h| h.as_str()).map(|h| base.and_then(|b| stac::resolve(b, h)).unwrap_or_else(|| h.to_string())); // Offered to the browser only where the item may read it from and it needs no signing. let web = item .asset_href(Some(key)) From a1a72fbaa4e36c186fc26baad4dd1f3d28685a04 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 16:45:59 -0500 Subject: [PATCH 03/33] fix(STAC): the inspector's Download and Add to map use the address its row shows Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/tiles/src/stac.rs | 16 +++++++++----- crates/ui-egui/src/stacui.rs | 42 ++++++++++++++++++++++++------------ 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index b4dd88b69e..06e2d809b2 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1010,19 +1010,25 @@ impl Item { /// may point to, not one that needs signing or a cloud store's own protocol. pub fn asset_href(&self, key: Option<&str>) -> Result<(String, String), String> { let a = self.pick(key)?; - let lower = crate::logins::inner(&a.href).to_ascii_lowercase(); + self.check_asset_href(&a.key, &a.href)?; + Ok((a.key.clone(), a.href.clone())) + } + + /// Checks an address given for asset `key` as [`Item::asset_href`] checks the item's own: a + /// web or s3:// address that the item's origin and reach allow. + pub fn check_asset_href(&self, key: &str, href: &str) -> Result<(), String> { + let lower = crate::logins::inner(href).to_ascii_lowercase(); if !(lower.starts_with("https://") || lower.starts_with("http://") || crate::s3::is_s3(&lower)) { let scheme = lower.split("://").next().unwrap_or(""); return Err(format!( - "{}: asset '{}' is at {} (a {scheme}:// address); RustGIS adds assets by their web or s3:// address", - self.id, a.key, a.href + "{}: asset '{key}' is at {href} (a {scheme}:// address); RustGIS adds assets by their web or s3:// address", + self.id )); } // Judged by where the item came from; an item given whole may only point at public // addresses (as a document on the web may). A Planetary Computer asset is signed by the // caller ([`needs_signing`]). - self.check_href(&a.href)?; - Ok((a.key.clone(), a.href.clone())) + self.check_href(href) } } diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 46249edcd8..2b40ab81a9 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -847,6 +847,17 @@ fn add_item_asset(app: &mut RustGisApp, item: &Item, key: Option<&str>) { } } +/// Adds the asset `key` at `href`, the address its document shows, under the item's name, after +/// the checks [`Item::asset_href`] makes. +fn add_document_asset(app: &mut RustGisApp, item: &Item, key: &str, href: &str) { + let from = item_document_origin(app, item); + let public = item.origin_reach == Reach::Public; + match item.check_asset_href(key, href) { + Ok(()) => add_signed(app, href, &format!("{} {key}", item.id), &from, public), + Err(e) => app.ui.stac.error = Some(e), + } +} + /// Opens the dialog on an item's or a collection's address (a `?stac=` link), fetching it off /// the frame. pub fn open_link(app: &mut RustGisApp, url: &str) -> Result<(), String> { @@ -2015,7 +2026,7 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { // The view picked on an open card (true: JSON), whether Copy was clicked, and whether Cancel. let (mut view, mut copy, mut cancel) = (None::, false, false); // The asset picked in an open card's Formatted tab: its item's place and its key. - let mut asset: Option<(usize, String)> = None; + let mut asset: Option<(usize, String, String)> = None; // The band combination picked on a card: its item's place and the combination's id. #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] let mut bands: Option<(usize, &'static str)> = None; @@ -2134,8 +2145,8 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { let did = inspector(ui, j, item); view = view.or(did.tab); (copy, cancel) = (copy || did.copy, cancel || did.cancel); - if let Some(key) = did.add { - asset = Some((i, key)); + if let Some((key, href)) = did.add { + asset = Some((i, key, href)); } } }); @@ -2154,9 +2165,9 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { if let (Some(text_tab), Some(j)) = (view, app.ui.stac.json.as_mut()) { j.text_tab = text_tab; } - if let Some((i, key)) = asset { + if let Some((i, key, href)) = asset { let Some(item) = app.ui.stac.items.get(i).cloned() else { return }; - add_item_asset(app, &item, Some(key.as_str())); + add_document_asset(app, &item, &key, &href); } if cancel { // Stops the read, and with it the card's details: nothing else is there to show. @@ -2363,8 +2374,8 @@ struct Inspected { /// A tab: true for the JSON text. tab: Option, copy: bool, - /// The key of an asset to add to the map. - add: Option, + /// The key and the shown address of an asset to add to the map. + add: Option<(String, String)>, cancel: bool, } @@ -2447,7 +2458,7 @@ fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: /// An item's document laid out as a page: what it is, its properties, its assets and its links. /// Only what the document holds is drawn; a section it lacks is left out. -fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option<&str>, item: &Item) -> Option { +fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option<&str>, item: &Item) -> Option<(String, String)> { let field = |k: &str| doc.get(k).filter(|v| !v.is_null()).map(short_value); let head: Vec<(String, String)> = [ (tl!("ID"), field("id")), @@ -2478,10 +2489,9 @@ fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option let href = a.get("href").and_then(|h| h.as_str()).map(|h| base.and_then(|b| stac::resolve(b, h)).unwrap_or_else(|| h.to_string())); // Offered to the browser only where the item may read it from and it needs no signing. - let web = item - .asset_href(Some(key)) - .ok() - .map(|(_, h)| h) + let web = href + .clone() + .filter(|h| item.check_asset_href(key, h).is_ok()) .filter(|h| h.starts_with("https://") || h.starts_with("http://")) .filter(|h| !stac::needs_signing(h)); ui.push_id(("stac_asset", id, key), |ui| { @@ -2496,8 +2506,12 @@ fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option .on_hover_text(h); } ui.horizontal(|ui| { - if ui.add(egui::Button::new(tl!("Add to map")).small()).on_hover_text(tl!("Add this asset to the map")).clicked() { - add = Some(key.clone()); + // The address added is the one shown in this row; a row with none has nothing to add. + let button = egui::Button::new(tl!("Add to map")).small(); + if ui.add_enabled(href.is_some(), button).on_hover_text(tl!("Add this asset to the map")).clicked() + && let Some(h) = &href + { + add = Some((key.clone(), h.clone())); } if let Some(h) = &web { ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(h); From bc42c36f8caa2f2c9ec1937c985ab830d45117d2 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 18:16:55 -0500 Subject: [PATCH 04/33] test(STAC): an inspector row acts on the document's own address, relative or not in the search item Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/ui-egui/src/stacui.rs | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 2b40ab81a9..3c42f34549 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -3957,4 +3957,51 @@ mod tests { let notices = h.state().session.notices.iter().map(|n| n.text.clone()).collect::>(); assert!(notices.iter().any(|n| n.contains("Reading https://stac.example/a.tif")), "{notices:?}"); } + + #[test] + fn an_assets_row_acts_on_the_address_the_documents_row_shows_even_when_the_search_item_has_none() { + let _turn = crate::fetching::turn(); + use egui_kittest::kittest::Queryable; + cache::set_fetcher(|_, done| { + // `extra` is only in the document (a relative address); `visual` is at another + // address than the search item gave it. + let doc = json!({ + "type": "Feature", "id": "scene-1", "collection": "c", + "assets": { + "extra": {"href": "./extra.tif", "type": "image/tiff"}, + "visual": {"href": "https://stac.example/doc/visual.tif", "type": "image/tiff"}, + }, + }); + done(Ok(doc.to_string().into_bytes())); + }); + let mut app = RustGisApp::with_sample(); + app.ui.stac.chosen = vec![String::new()]; + app.ui.stac.items = vec![json_test_item(true)]; + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 900.0)) + .build_ui_state(|ui, app: &mut RustGisApp| results(app, ui), app); + h.step(); + h.get_by_label("Details").click(); + h.step(); + let ctx = h.ctx.clone(); + poll_json(h.state_mut(), &ctx); + h.step(); + h.step(); + // Both rows offer a download, though the search item has no `extra` asset. + assert_eq!(h.get_all_by_label("Download").count(), 2); + // The keys come out in order: extra, then visual. + h.get_all_by_label("Add to map").next().unwrap().click(); + h.step(); + h.step(); + h.get_all_by_label("Add to map").nth(1).unwrap().click(); + h.step(); + h.step(); + let said = h.state().ui.stac.error.clone(); + assert!(said.is_none(), "{said:?}"); + let notices = h.state().session.notices.iter().map(|n| n.text.clone()).collect::>(); + let read = |url: &str| notices.iter().any(|n| n.contains(&format!("Reading {url}"))); + assert!(read("https://stac.example/api/collections/c/items/extra.tif"), "{notices:?}"); + assert!(read("https://stac.example/doc/visual.tif"), "{notices:?}"); + assert!(!read("https://stac.example/a.tif"), "the search item's address was used: {notices:?}"); + } } From 0ffd550e91d32c71515387cd36d242decb3ff26f Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 19:05:57 -0500 Subject: [PATCH 05/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/ui-egui/src/stacui.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 3c42f34549..4bd0f7ef6b 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2165,8 +2165,9 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { if let (Some(text_tab), Some(j)) = (view, app.ui.stac.json.as_mut()) { j.text_tab = text_tab; } - if let Some((i, key, href)) = asset { - let Some(item) = app.ui.stac.items.get(i).cloned() else { return }; + if let Some((i, key, href)) = asset + && let Some(item) = app.ui.stac.items.get(i).cloned() + { add_document_asset(app, &item, &key, &href); } if cancel { From c3f73983895d99e90b84a885468fb61d737e56db Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 19:06:13 -0500 Subject: [PATCH 06/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/ui-egui/src/stacui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 4bd0f7ef6b..ceff1d1008 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2303,7 +2303,7 @@ fn raw_note(text: &str, drawn: usize, why: Option) -> Option { ) }); match (why, cut) { - (Some(why), Some(cut)) => Some(format!("{why} {cut}")), + (Some(why), Some(cut)) => Some(i18n::fmt("{why} {cut}", &[("why", &why), ("cut", &cut)])), (why, cut) => why.or(cut), } } From 060daac1c6de6b4985e69f94c30f8d43a605d132 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 19:54:31 -0500 Subject: [PATCH 07/33] fix(STAC): the inspector reads an item's document within 16 MB, off the frame, holds its assets to its reach, and says what it is Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/tiles/src/stac.rs | 23 ++-- crates/ui-egui/src/stacui.rs | 224 ++++++++++++++++++++++++++++++----- 2 files changed, 211 insertions(+), 36 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 06e2d809b2..8dba2e8b5f 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1017,19 +1017,26 @@ impl Item { /// Checks an address given for asset `key` as [`Item::asset_href`] checks the item's own: a /// web or s3:// address that the item's origin and reach allow. pub fn check_asset_href(&self, key: &str, href: &str) -> Result<(), String> { - let lower = crate::logins::inner(href).to_ascii_lowercase(); - if !(lower.starts_with("https://") || lower.starts_with("http://") || crate::s3::is_s3(&lower)) { - let scheme = lower.split("://").next().unwrap_or(""); - return Err(format!( - "{}: asset '{key}' is at {href} (a {scheme}:// address); RustGIS adds assets by their web or s3:// address", - self.id - )); - } + self.check_asset_scheme(key, href)?; // Judged by where the item came from; an item given whole may only point at public // addresses (as a document on the web may). A Planetary Computer asset is signed by the // caller ([`needs_signing`]). self.check_href(href) } + + /// The scheme half of [`Item::check_asset_href`], for an address judged against another + /// document's origin: a web or s3:// address, else an error naming what it is. + pub fn check_asset_scheme(&self, key: &str, href: &str) -> Result<(), String> { + let lower = crate::logins::inner(href).to_ascii_lowercase(); + if lower.starts_with("https://") || lower.starts_with("http://") || crate::s3::is_s3(&lower) { + return Ok(()); + } + let what = match lower.split_once("://") { + Some((scheme, _)) => format!("a {scheme}:// address"), + None => "a relative address that couldn't be made absolute".to_string(), + }; + Err(format!("{}: asset '{key}' is at {href} ({what}); RustGIS adds assets by their web or s3:// address", self.id)) + } } /// The host of a web address, lower-cased. diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index ceff1d1008..11439a7f32 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -326,6 +326,44 @@ fn post_service(app: &mut RustGisApp, url: &str, body: String) -> Answer { } } +/// Reads an item's own document off the frame, at most [`cache::MAX_BYTES`] (an item is far below +/// it), and has it parsed and printed there too, so the window only takes the finished text. The +/// document must be this item (a `Feature` with its id), else it is refused with the reason. The +/// read can't be stopped once started: an abandoned one runs to its end and its answer is dropped. +fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str) -> DocAnswer { + let from_document = from_document || app.ui.stac.api_from_document; + let connection = selected_connection(app); + let base = app.ui.stac.api.clone(); + let url = match crate::serviceui::request_from(app, connection.as_deref(), &base, url) { + Ok(url) => url, + Err(e) => return Slot::new(std::sync::Mutex::new(Some(Err(crate::connectionui::translated(&e))))), + }; + let slot: DocAnswer = Slot::default(); + let land = slot.clone(); + let id = id.to_string(); + let done = Box::new(move |r: Result| { + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r.and_then(|f| land_document(f, &id))); + }); + let ceiling = if from_document { Reach::Public } else { Reach::Local }; + cache::download_limited_reaching_with_origin(&url, cache::MAX_BYTES, None, ceiling, done); + slot +} + +/// A fetched document as the inspector shows it, if it is the item `id`. +fn land_document(f: cache::Fetched, id: &str) -> Result { + if f.bytes.len() > cache::MAX_BYTES { + return Err(i18n::fmt("larger than {n} MB", &[("n", &(cache::MAX_BYTES >> 20).to_string())])); + } + let (text, drawn, doc) = raw_text(&f.bytes)?; + let is = doc.get("type").and_then(|t| t.as_str()) == Some("Feature"); + let found = doc.get("id").and_then(|i| i.as_str()); + if !is || found != Some(id) { + let found = found.map(|f| f.chars().take(100).collect::()).unwrap_or_default(); + return Err(i18n::fmt("the address answered with a document that is not this item ({found})", &[("found", &found)])); + } + Ok(Landed { text, drawn, doc, source: (f.origin.url().to_string(), f.origin.reach()) }) +} + /// The most of an item's JSON the pane draws: more is cut from the view (Copy still takes it all). const JSON_SHOWN_BYTES: usize = 200_000; @@ -337,15 +375,27 @@ struct JsonView { raw: Raw, } -/// An item's own document as the catalog sent it, for the JSON view. +/// An item's own document, read and made ready off the frame. +struct Landed { + text: String, + drawn: usize, + doc: serde_json::Value, + /// The address it was read from and the reach it was read under. + source: (String, Reach), +} + +type DocAnswer = Slot>; + +/// An item's own document as the catalog sent it (its keys sorted), for the JSON view. enum Raw { /// Being read from the item's own address. - Loading(Answer), + Loading(DocAnswer), /// Ready: the whole text (what Copy takes), how much of it the pane draws, and a line saying /// what is not the catalog's whole document or why not (read failed, text cut). - /// `base` is the address the document was read from (its relative links resolve against it); - /// none when the pane shows what RustGIS read instead. - Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value, base: Option }, + /// `source` is the address the document was read from, with the reach it was read under: its + /// relative links resolve against the address, and its asset addresses are held to the reach. + /// None when the pane shows what RustGIS read instead. + Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value, source: Option<(String, Reach)> }, } /// An item's preview picture: being fetched, shown, or not to be had. @@ -847,12 +897,37 @@ fn add_item_asset(app: &mut RustGisApp, item: &Item, key: Option<&str>) { } } +/// Whether the asset `key` at `href`, an address a document gave, may be added: the checks +/// [`Item::asset_href`] makes, held to where the document was read and the reach it was read +/// under (`source`), or to the item's own when the pane shows only what RustGIS read. +fn document_asset_allowed(item: &Item, key: &str, href: &str, source: Option<(&str, Reach)>) -> Result<(), String> { + match source { + Some((base, reach)) => { + item.check_asset_scheme(key, href)?; + Origin::with_observed_reach(base, reach)?.check(href) + } + None => item.check_asset_href(key, href), + } +} + +/// The address and reach the open inspector's document was read under, if it was read. +fn document_source(app: &RustGisApp) -> Option<(String, Reach)> { + match &app.ui.stac.json { + Some(JsonView { raw: Raw::Shown { source, .. }, .. }) => source.clone(), + _ => None, + } +} + /// Adds the asset `key` at `href`, the address its document shows, under the item's name, after -/// the checks [`Item::asset_href`] makes. +/// the checks [`Item::asset_href`] makes, held to the document's own reach. fn add_document_asset(app: &mut RustGisApp, item: &Item, key: &str, href: &str) { - let from = item_document_origin(app, item); - let public = item.origin_reach == Reach::Public; - match item.check_asset_href(key, href) { + let source = document_source(app); + let allowed = document_asset_allowed(item, key, href, source.as_ref().map(|(b, r)| (b.as_str(), *r))); + let (from, public) = match source { + Some((base, reach)) => (base, reach == Reach::Public), + None => (item_document_origin(app, item), item.origin_reach == Reach::Public), + }; + match allowed { Ok(()) => add_signed(app, href, &format!("{} {key}", item.id), &from, public), Err(e) => app.ui.stac.error = Some(e), } @@ -2171,7 +2246,8 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { add_document_asset(app, &item, &key, &href); } if cancel { - // Stops the read, and with it the card's details: nothing else is there to show. + // Drops the read (a download can't be stopped once started: it runs to its end, at most + // 16 MB, and its answer is not kept) and with it the card's details. app.ui.stac.json = None; app.ui.stac.details = None; } @@ -2315,7 +2391,7 @@ fn start_json(app: &mut RustGisApp, i: usize) { let trimmed = |why: String| { let (text, drawn, doc) = trimmed_text(&item); let note = raw_note(&text, drawn, Some(why)); - Raw::Shown { text, drawn, note, doc, base: None } + Raw::Shown { text, drawn, note, doc, source: None } }; let Some(url) = item.url.clone() else { let why = tl!( @@ -2329,7 +2405,7 @@ fn start_json(app: &mut RustGisApp, i: usize) { let from = item_document_origin(app, &item); let ceiling = rustgis_engine::cmd::layer::origin_ceiling(Some(&from), public); let raw = match address::check_reach(&url, ceiling) { - Ok(()) => Raw::Loading(fetch_service(app, &url, public)), + Ok(()) => Raw::Loading(fetch_document(app, &url, public, &item.id)), Err(e) => trimmed(i18n::fmt( "{url} was not read: {e}. This is what RustGIS read of the item instead: the first 100 plain properties, long text cut.", &[("url", &rustgis_engine::sources::address_in_message(&url)), ("e", &e)], @@ -2350,11 +2426,10 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { app.ui.stac.json = None; return; }; - let base = r.as_ref().ok().map(|f| f.origin.url().to_string()); - let raw = match r.and_then(|f| raw_text(&f.bytes)) { - Ok((text, drawn, doc)) => { + let raw = match r { + Ok(Landed { text, drawn, doc, source }) => { let note = raw_note(&text, drawn, None); - Raw::Shown { text, drawn, note, doc, base } + Raw::Shown { text, drawn, note, doc, source: Some(source) } } Err(e) => { let (text, drawn, doc) = trimmed_text(&item); @@ -2363,7 +2438,7 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { &[("e", &e)], ); let note = raw_note(&text, drawn, Some(why)); - Raw::Shown { text, drawn, note, doc, base: None } + Raw::Shown { text, drawn, note, doc, source: None } } }; app.ui.stac.json = Some(JsonView { item: i, text_tab, raw }); @@ -2403,17 +2478,25 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { did.cancel = ui.button(tl!("Cancel")).clicked(); }); } - Raw::Shown { text, drawn, note, doc, base } => { + Raw::Shown { text, drawn, note, doc, source } => { if let Some(note) = note { ui.label(egui::RichText::new(note).small().weak()); } if view.text_tab { + if source.is_some() { + // The document is read into a tree of sorted keys, so it is not shown as written. + ui.label( + egui::RichText::new(tl!("Keys are listed in alphabetical order, and a repeated key keeps its last value.")) + .small() + .weak(), + ); + } egui::ScrollArea::both().id_salt(("stac_json", view.item)).max_height(260.0).show(ui, |ui| { let mut shown = text.get(..*drawn).unwrap_or_default(); ui.add(egui::TextEdit::multiline(&mut shown).code_editor().desired_width(f32::INFINITY).interactive(true)); }); } else { - did.add = formatted(ui, view.item, doc, base.as_deref(), item); + did.add = formatted(ui, view.item, doc, source.as_ref().map(|(b, r)| (b.as_str(), *r)), item); } } } @@ -2423,16 +2506,43 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { /// The most rows a section of the formatted page draws; the rest is said, not dropped. const FORMATTED_ROWS: usize = 200; -/// A value as one short line: text as it is, anything else as JSON, cut at 160 characters. +/// Takes bytes up to a limit and then refuses more, so printing a large value stops at the limit +/// (the page draws every frame, and a value can be as large as the document). +struct Bounded(Vec); + +impl std::io::Write for Bounded { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + // Four bytes a character at most: the first 160 characters are within it. + let room = (4 * SHORT_VALUE_CHARS).saturating_sub(self.0.len()); + self.0.extend_from_slice(buf.get(..room.min(buf.len())).unwrap_or_default()); + if buf.len() > room { Err(std::io::Error::other("full")) } else { Ok(buf.len()) } + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// The most characters of a value the formatted page shows on a line. +const SHORT_VALUE_CHARS: usize = 160; + +/// A value as one short line: text as it is, anything else as JSON, cut at 160 characters. Work +/// is bounded by the cut, not by the value's size. fn short_value(v: &serde_json::Value) -> String { - let text = match v { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), + let (text, whole): (String, bool) = match v { + serde_json::Value::String(s) => (s.chars().take(SHORT_VALUE_CHARS + 1).collect(), true), + other => { + let mut out = Bounded(Vec::new()); + let whole = serde_json::to_writer(&mut out, other).is_ok(); + (String::from_utf8_lossy(&out.0).chars().take(SHORT_VALUE_CHARS + 1).collect(), whole) + } }; - let mut short: String = text.chars().take(160).collect(); - if short.len() < text.len() { - short.push('…'); + // Past the line, or cut by the limit on the way: ends in an ellipsis. + if whole && text.chars().count() <= SHORT_VALUE_CHARS { + return text; } + let mut short: String = text.chars().take(SHORT_VALUE_CHARS).collect(); + short.push('…'); short } @@ -2459,7 +2569,14 @@ fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: /// An item's document laid out as a page: what it is, its properties, its assets and its links. /// Only what the document holds is drawn; a section it lacks is left out. -fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option<&str>, item: &Item) -> Option<(String, String)> { +fn formatted( + ui: &mut egui::Ui, + id: usize, + doc: &serde_json::Value, + source: Option<(&str, Reach)>, + item: &Item, +) -> Option<(String, String)> { + let base = source.map(|(b, _)| b); let field = |k: &str| doc.get(k).filter(|v| !v.is_null()).map(short_value); let head: Vec<(String, String)> = [ (tl!("ID"), field("id")), @@ -2492,7 +2609,7 @@ fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, base: Option // Offered to the browser only where the item may read it from and it needs no signing. let web = href .clone() - .filter(|h| item.check_asset_href(key, h).is_ok()) + .filter(|h| document_asset_allowed(item, key, h, source).is_ok()) .filter(|h| h.starts_with("https://") || h.starts_with("http://")) .filter(|h| !stac::needs_signing(h)); ui.push_id(("stac_asset", id, key), |ui| { @@ -3959,6 +4076,57 @@ mod tests { assert!(notices.iter().any(|n| n.contains("Reading https://stac.example/a.tif")), "{notices:?}"); } + #[test] + fn a_document_that_is_not_this_item_or_is_over_the_cap_falls_back_with_the_reason() { + let _turn = crate::fetching::turn(); + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + app.ui.stac.items = vec![json_test_item(true)]; + // Another item, a collection, and a document with no id: none is this item's own. + for doc in [json!({"type": "Feature", "id": "other"}), json!({"type": "Collection", "id": "scene-1"}), json!({"type": "Feature"})] { + cache::set_fetcher(move |_, done| done(Ok(doc.to_string().into_bytes()))); + start_json(&mut app, 0); + poll_json(&mut app, &ctx); + let Some(JsonView { raw: Raw::Shown { note, source, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; + let note = note.as_deref().unwrap_or(""); + assert!(note.contains("not this item") && source.is_none(), "{note}"); + } + // More than the cap: said, and the trimmed copy shown, not the document. + cache::set_fetcher(|_, done| done(Ok(vec![b' '; cache::MAX_BYTES + 1]))); + start_json(&mut app, 0); + poll_json(&mut app, &ctx); + let Some(JsonView { raw: Raw::Shown { note, source, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; + assert!(note.as_deref().unwrap_or("").contains("larger than 16 MB") && source.is_none(), "{note:?}"); + } + + #[test] + fn a_value_is_cut_at_a_line_without_printing_all_of_it() { + let line = SHORT_VALUE_CHARS; + let exact = "é".repeat(line); + assert_eq!(short_value(&json!(exact)), exact, "a value that fits is shown as it is"); + assert_eq!(short_value(&json!(format!("{exact}x"))), format!("{exact}…")); + // A nested value far larger than the line: a line of it, and the cut said. + let big = json!({"k": (0..100_000).collect::>()}); + let short = short_value(&big); + assert!(short.chars().count() == line + 1 && short.ends_with('…') && short.starts_with("{\"k\":[0,1,2"), "{short}"); + assert_eq!(short_value(&json!([1, 2])), "[1,2]"); + } + + #[test] + fn an_assets_address_from_a_document_is_held_to_the_documents_reach_and_a_relative_one_is_named() { + let item = json_test_item(true); + let public = Some(("https://stac.example/api/items/scene-1", Reach::Public)); + assert!(document_asset_allowed(&item, "k", "https://stac.example/a.tif", public).is_ok()); + // A document read from the public web may not point at the user's own machine. + for local in ["http://localhost/a.tif", "http://127.0.0.1:8080/a.tif", "http://192.168.1.5/a.tif"] { + assert!(document_asset_allowed(&item, "k", local, public).is_err(), "{local}"); + } + let said = document_asset_allowed(&item, "k", "./extra.tif", public).unwrap_err(); + assert!(said.contains("relative address") && !said.contains(":// "), "{said}"); + let said = document_asset_allowed(&item, "k", "ftp://x/a.tif", public).unwrap_err(); + assert!(said.contains("a ftp:// address"), "{said}"); + } + #[test] fn an_assets_row_acts_on_the_address_the_documents_row_shows_even_when_the_search_item_has_none() { let _turn = crate::fetching::turn(); From b290c603017155a715e935c8f546b1659314afb6 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Fri, 27 Nov 2026 20:22:16 -0500 Subject: [PATCH 08/33] fix(STAC): the item's own document is read under the item's reach, and a scheme without // is named Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/tiles/src/stac.rs | 9 ++++++--- crates/ui-egui/src/stacui.rs | 10 ++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 8dba2e8b5f..ed5b83525a 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1031,9 +1031,12 @@ impl Item { if lower.starts_with("https://") || lower.starts_with("http://") || crate::s3::is_s3(&lower) { return Ok(()); } - let what = match lower.split_once("://") { - Some((scheme, _)) => format!("a {scheme}:// address"), - None => "a relative address that couldn't be made absolute".to_string(), + // The scheme is the letters before the first colon (`data:` and `mailto:` have no `//`). + let scheme = lower.split_once(':').map(|(s, _)| s).filter(|s| s.len() > 1 && s.bytes().all(|b| b.is_ascii_alphabetic())); + let what = match (scheme, lower.contains("://")) { + (Some(scheme), true) => format!("a {scheme}:// address"), + (Some(scheme), false) => format!("a {scheme}: address"), + (None, _) => "a relative address that couldn't be made absolute".to_string(), }; Err(format!("{}: asset '{key}' is at {href} ({what}); RustGIS adds assets by their web or s3:// address", self.id)) } diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 11439a7f32..62fb685d0a 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -331,7 +331,8 @@ fn post_service(app: &mut RustGisApp, url: &str, body: String) -> Answer { /// document must be this item (a `Feature` with its id), else it is refused with the reason. The /// read can't be stopped once started: an abandoned one runs to its end and its answer is dropped. fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str) -> DocAnswer { - let from_document = from_document || app.ui.stac.api_from_document; + // Read under the reach `start_json` checked the address under (the item's own), not widened + // by whether the dialog's API came from a document. let connection = selected_connection(app); let base = app.ui.stac.api.clone(); let url = match crate::serviceui::request_from(app, connection.as_deref(), &base, url) { @@ -386,7 +387,8 @@ struct Landed { type DocAnswer = Slot>; -/// An item's own document as the catalog sent it (its keys sorted), for the JSON view. +/// An item's own document, pretty-printed with its keys sorted (a repeated key keeps its last +/// value), for the JSON view. enum Raw { /// Being read from the item's own address. Loading(DocAnswer), @@ -4125,6 +4127,10 @@ mod tests { assert!(said.contains("relative address") && !said.contains(":// "), "{said}"); let said = document_asset_allowed(&item, "k", "ftp://x/a.tif", public).unwrap_err(); assert!(said.contains("a ftp:// address"), "{said}"); + for (href, named) in [("data:text/plain;base64,AAAA", "a data: address"), ("mailto:a@b.c", "a mailto: address")] { + let said = document_asset_allowed(&item, "k", href, public).unwrap_err(); + assert!(said.contains(named) && !said.contains("relative"), "{said}"); + } } #[test] From de0db17f8c71ea138976d2a9c413b71c3898371d Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 10:42:51 -0500 Subject: [PATCH 09/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/ui-egui/src/stacui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 62fb685d0a..4f77dd3161 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2612,7 +2612,7 @@ fn formatted( let web = href .clone() .filter(|h| document_asset_allowed(item, key, h, source).is_ok()) - .filter(|h| h.starts_with("https://") || h.starts_with("http://")) + .filter(|h| address::is_https(h) || h.get(..7).is_some_and(|s| s.eq_ignore_ascii_case("http://"))) .filter(|h| !stac::needs_signing(h)); ui.push_id(("stac_asset", id, key), |ui| { ui.label(egui::RichText::new(key).small().strong()); From 8db17fe47f6cea3da9d814d4c4a80e8c1777c39d Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 10:43:19 -0500 Subject: [PATCH 10/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/tiles/src/stac.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index ed5b83525a..f6192bf98b 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1033,7 +1033,8 @@ impl Item { } // The scheme is the letters before the first colon (`data:` and `mailto:` have no `//`). let scheme = lower.split_once(':').map(|(s, _)| s).filter(|s| s.len() > 1 && s.bytes().all(|b| b.is_ascii_alphabetic())); - let what = match (scheme, lower.contains("://")) { + let slashes = lower.split_once(':').is_some_and(|(_, rest)| rest.starts_with("//")); + let what = match (scheme, slashes) { (Some(scheme), true) => format!("a {scheme}:// address"), (Some(scheme), false) => format!("a {scheme}: address"), (None, _) => "a relative address that couldn't be made absolute".to_string(), From 67122cb8006f1f3c3f7f16b932e1d7896ce0157a Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 13:04:46 -0500 Subject: [PATCH 11/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- docs/user-guide/web-data.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index 96a8d16f52..49e4f713cf 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -64,7 +64,7 @@ cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **De reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, its properties, its assets and its links, up to 200 rows a section with the rest counted; each asset has **Add to map**, **Download** (a link to its web address, not offered for -an address that needs signing, such as Planetary Computer's) and **Copy link**) and **JSON** (the document as the catalog sent it, with **Copy JSON**; the first +an address that needs signing, such as Planetary Computer's) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first 200,000 bytes are drawn and Copy takes all of it). An item with no address of its own, or one the network reach it was found with doesn't allow reading, shows what RustGIS read of it instead (the first 100 plain properties, long text cut), with a line saying so. The asset chosen at first is `visual` (true colour) when there is one, else the first From b7a33fd177c6fa5b69c0b672a0b46181b4fe7300 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 13:21:41 -0500 Subject: [PATCH 12/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/ui-egui/src/stacui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 4f77dd3161..be15c8db13 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2593,7 +2593,7 @@ fn formatted( let n = head.len(); section(ui, ("stac_head", id), tl!("Item"), head, n); if let Some(props) = doc.get("properties").and_then(|p| p.as_object()) { - let rows = props.iter().take(FORMATTED_ROWS).map(|(k, v)| (k.clone(), short_value(v))).collect(); + let rows = props.iter().take(FORMATTED_ROWS).map(|(k, v)| (short_value(&serde_json::Value::String(k.chars().take(SHORT_VALUE_CHARS + 1).collect())), short_value(v))).collect(); section(ui, ("stac_props", id), tl!("Properties"), rows, props.len()); } let mut add = None; From 0dab90609e9953e3abb96ed7837f15e22af2db01 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 14:29:00 -0500 Subject: [PATCH 13/33] fix(STAC): an item's document is read within 4 MB, one helper cuts the shown text, and the format check passes Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01425amtdfYrrAXoQdy6q7ZD --- crates/ui-egui/src/stacui.rs | 50 ++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index be15c8db13..20645d2ea0 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -326,7 +326,7 @@ fn post_service(app: &mut RustGisApp, url: &str, body: String) -> Answer { } } -/// Reads an item's own document off the frame, at most [`cache::MAX_BYTES`] (an item is far below +/// Reads an item's own document off the frame, at most [`DOCUMENT_BYTES`] (an item is far below /// it), and has it parsed and printed there too, so the window only takes the finished text. The /// document must be this item (a `Feature` with its id), else it is refused with the reason. The /// read can't be stopped once started: an abandoned one runs to its end and its answer is dropped. @@ -346,14 +346,14 @@ fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r.and_then(|f| land_document(f, &id))); }); let ceiling = if from_document { Reach::Public } else { Reach::Local }; - cache::download_limited_reaching_with_origin(&url, cache::MAX_BYTES, None, ceiling, done); + cache::download_limited_reaching_with_origin(&url, DOCUMENT_BYTES, None, ceiling, done); slot } /// A fetched document as the inspector shows it, if it is the item `id`. fn land_document(f: cache::Fetched, id: &str) -> Result { - if f.bytes.len() > cache::MAX_BYTES { - return Err(i18n::fmt("larger than {n} MB", &[("n", &(cache::MAX_BYTES >> 20).to_string())])); + if f.bytes.len() > DOCUMENT_BYTES { + return Err(i18n::fmt("larger than {n} MB", &[("n", &(DOCUMENT_BYTES >> 20).to_string())])); } let (text, drawn, doc) = raw_text(&f.bytes)?; let is = doc.get("type").and_then(|t| t.as_str()) == Some("Feature"); @@ -365,6 +365,20 @@ fn land_document(f: cache::Fetched, id: &str) -> Result { Ok(Landed { text, drawn, doc, source: (f.origin.url().to_string(), f.origin.reach()) }) } +/// How many bytes of `text` the pane draws: up to [`JSON_SHOWN_BYTES`], cut where a character ends. +fn shown_bytes(text: &str) -> usize { + let mut drawn = text.len().min(JSON_SHOWN_BYTES); + while !text.is_char_boundary(drawn) { + drawn -= 1; + } + drawn +} + +/// The most bytes read of an item's own document. An item is a few kilobytes, rarely a megabyte; +/// the limit is small because the document is held as text and as a parsed tree (a tree of +/// numbers is several times the bytes it came from) for as long as its card is open. +const DOCUMENT_BYTES: usize = 4 << 20; + /// The most of an item's JSON the pane draws: more is cut from the view (Copy still takes it all). const JSON_SHOWN_BYTES: usize = 200_000; @@ -2249,7 +2263,7 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { } if cancel { // Drops the read (a download can't be stopped once started: it runs to its end, at most - // 16 MB, and its answer is not kept) and with it the card's details. + // 4 MB, and its answer is not kept) and with it the card's details. app.ui.stac.json = None; app.ui.stac.details = None; } @@ -2352,10 +2366,7 @@ fn add_item_index(app: &mut RustGisApp, _item: &Item, _index: &str) { fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> { let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]))?; let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?; - let mut drawn = text.len().min(JSON_SHOWN_BYTES); - while !text.is_char_boundary(drawn) { - drawn -= 1; - } + let drawn = shown_bytes(&text); Ok((text, drawn, value)) } @@ -2364,10 +2375,7 @@ fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> fn trimmed_text(item: &Item) -> (String, usize, serde_json::Value) { let doc = stac::item_json_with(item, true); let text = serde_json::to_string_pretty(&doc).unwrap_or_default(); - let mut drawn = text.len().min(JSON_SHOWN_BYTES); - while !text.is_char_boundary(drawn) { - drawn -= 1; - } + let drawn = shown_bytes(&text); (text, drawn, doc) } @@ -2593,7 +2601,11 @@ fn formatted( let n = head.len(); section(ui, ("stac_head", id), tl!("Item"), head, n); if let Some(props) = doc.get("properties").and_then(|p| p.as_object()) { - let rows = props.iter().take(FORMATTED_ROWS).map(|(k, v)| (short_value(&serde_json::Value::String(k.chars().take(SHORT_VALUE_CHARS + 1).collect())), short_value(v))).collect(); + let rows = props + .iter() + .take(FORMATTED_ROWS) + .map(|(k, v)| (short_value(&serde_json::Value::String(k.chars().take(SHORT_VALUE_CHARS + 1).collect())), short_value(v))) + .collect(); section(ui, ("stac_props", id), tl!("Properties"), rows, props.len()); } let mut add = None; @@ -4067,8 +4079,8 @@ mod tests { assert_eq!(h.get_all_by_label("Copy link").count(), 2); assert_eq!(h.get_all_by_label("Download").count(), 1); // The document's keys come out in order: bucket, then visual. - let first = h.get_all_by_label("Add to map").nth(1).unwrap(); - first.click(); + let visual = h.get_all_by_label("Add to map").nth(1).unwrap(); + visual.click(); h.step(); h.step(); let said = h.state().ui.stac.error.clone(); @@ -4094,11 +4106,11 @@ mod tests { assert!(note.contains("not this item") && source.is_none(), "{note}"); } // More than the cap: said, and the trimmed copy shown, not the document. - cache::set_fetcher(|_, done| done(Ok(vec![b' '; cache::MAX_BYTES + 1]))); + cache::set_fetcher(|_, done| done(Ok(vec![b' '; DOCUMENT_BYTES + 1]))); start_json(&mut app, 0); poll_json(&mut app, &ctx); let Some(JsonView { raw: Raw::Shown { note, source, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; - assert!(note.as_deref().unwrap_or("").contains("larger than 16 MB") && source.is_none(), "{note:?}"); + assert!(note.as_deref().unwrap_or("").contains("larger than 4 MB") && source.is_none(), "{note:?}"); } #[test] @@ -4124,7 +4136,7 @@ mod tests { assert!(document_asset_allowed(&item, "k", local, public).is_err(), "{local}"); } let said = document_asset_allowed(&item, "k", "./extra.tif", public).unwrap_err(); - assert!(said.contains("relative address") && !said.contains(":// "), "{said}"); + assert!(said.contains("relative address"), "{said}"); let said = document_asset_allowed(&item, "k", "ftp://x/a.tif", public).unwrap_err(); assert!(said.contains("a ftp:// address"), "{said}"); for (href, named) in [("data:text/plain;base64,AAAA", "a data: address"), ("mailto:a@b.c", "a mailto: address")] { From 97cf3ac98d7ff67e48dbf8319a925742baa7bf94 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 14:55:19 -0500 Subject: [PATCH 14/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/tiles/src/stac.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index f6192bf98b..ce2a45ef27 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1032,7 +1032,11 @@ impl Item { return Ok(()); } // The scheme is the letters before the first colon (`data:` and `mailto:` have no `//`). - let scheme = lower.split_once(':').map(|(s, _)| s).filter(|s| s.len() > 1 && s.bytes().all(|b| b.is_ascii_alphabetic())); + let scheme = lower + .split_once(':') + .map(|(s, _)| s) + .filter(|s| s.len() > 1 && s.starts_with(|c: char| c.is_ascii_alphabetic())) + .filter(|s| s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))); let slashes = lower.split_once(':').is_some_and(|(_, rest)| rest.starts_with("//")); let what = match (scheme, slashes) { (Some(scheme), true) => format!("a {scheme}:// address"), From a6e0049d7b8ed6e304d6aecf850c39db6820af21 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 14:55:31 -0500 Subject: [PATCH 15/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/tiles/src/stac.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index ce2a45ef27..319576bf70 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1043,7 +1043,9 @@ impl Item { (Some(scheme), false) => format!("a {scheme}: address"), (None, _) => "a relative address that couldn't be made absolute".to_string(), }; - Err(format!("{}: asset '{key}' is at {href} ({what}); RustGIS adds assets by their web or s3:// address", self.id)) + let cut = href.chars().count() > 200; + let shown: String = href.chars().take(200).chain(cut.then_some('…')).collect(); + Err(format!("{}: asset '{key}' is at {shown} ({what}); RustGIS adds assets by their web or s3:// address", self.id)) } } From bab9cad5456a2173661496176195b370d0b39a1e Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 18:10:16 -0500 Subject: [PATCH 16/33] fix(STAC): the laid-out document is bounded, a scheme-bearing asset address is kept, and hovers show the cut address Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 14 +++++++- crates/ui-egui/src/stacui.rs | 64 +++++++++++++++++++++++++++++++----- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 319576bf70..42ec160e80 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -905,12 +905,20 @@ pub fn resolve(base: &str, href: &str) -> Option { Some(crate::logins::inherit(base, &resolved)) } +/// Whether `href` begins with a URI scheme (`data:`, `mailto:`): a letter, then letters, digits, +/// `+`, `-` or `.`, then a colon. Such an address is not relative to anything. +fn has_scheme(href: &str) -> bool { + let mut chars = href.chars(); + chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))) == Some(':') +} + fn resolve_plain(base: &str, href: &str) -> Option { let href = href.trim(); if href.is_empty() || href.len() > MAX_TEXT || href.chars().any(char::is_control) { return None; } - if href.contains("://") { + if href.contains("://") || has_scheme(href) { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; @@ -1670,6 +1678,10 @@ mod tests { assert_eq!(resolve("https://x.org/a", "//y.org/d.tif").as_deref(), Some("https://y.org/d.tif")); assert_eq!(resolve("https://x.org/a", "s3://b/k").as_deref(), Some("s3://b/k")); assert_eq!(resolve("https://x.org/a", ""), None); + // An address with a scheme of its own is not relative to anything. + assert_eq!(resolve("https://x.org/a/b.json", "data:text/plain,hi").as_deref(), Some("data:text/plain,hi")); + assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("mailto:me@x.org")); + assert_eq!(resolve("https://x.org/a/b.json", "d.tif").as_deref(), Some("https://x.org/a/d.tif")); } /// JAXA Earth's codes for a failed retrieval: read whole, or the asset says they weren't. diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 20645d2ea0..1de0aba8b4 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2365,11 +2365,40 @@ fn add_item_index(app: &mut RustGisApp, _item: &Item, _index: &str) { /// character boundary). Not JSON is an error: it is not shown as the item. fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> { let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]))?; - let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?; + let text = pretty_within(&value, PRETTY_BYTES)?; let drawn = shown_bytes(&text); Ok((text, drawn, value)) } +/// The most bytes the pretty-printed document may take. Indentation can multiply a small document +/// (deeply nested arrays of numbers), so the printing stops here instead of at the end. +const PRETTY_BYTES: usize = 16 << 20; + +/// `value` pretty-printed, or an error once the text passes `limit` bytes. +fn pretty_within(value: &serde_json::Value, limit: usize) -> Result { + struct Limited { + out: Vec, + limit: usize, + } + impl std::io::Write for Limited { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.out.len().saturating_add(buf.len()) > self.limit { + return Err(std::io::Error::other("over the limit")); + } + self.out.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut w = Limited { out: Vec::new(), limit }; + let mut ser = serde_json::Serializer::with_formatter(&mut w, serde_json::ser::PrettyFormatter::new()); + serde::Serialize::serialize(value, &mut ser) + .map_err(|_| i18n::fmt("the document is more than {n} MB once laid out", &[("n", &(limit >> 20).to_string())]))?; + String::from_utf8(w.out).map_err(|e| e.to_string()) +} + /// What the pane keeps of an item when it can't show the catalog's own document: its properties /// (the first hundred plain ones, long text cut), assets and footprint as RustGIS read them. fn trimmed_text(item: &Item) -> (String, usize, serde_json::Value) { @@ -2631,11 +2660,11 @@ fn formatted( if !detail.is_empty() { ui.add(egui::Label::new(egui::RichText::new(detail).small().weak()).wrap()); } - if let Some(h) = &href { - ui.add( - egui::Label::new(egui::RichText::new(short_value(&serde_json::Value::String(h.clone()))).small().weak()).truncate(), - ) - .on_hover_text(h); + // Hovers show the cut form too: laying out an address as long as the read cap each + // frame would cost more than the row is worth. Copy link takes the whole address. + let cut = href.as_ref().map(|h| short_value(&serde_json::Value::String(h.clone()))); + if let Some(c) = &cut { + ui.add(egui::Label::new(egui::RichText::new(c).small().weak()).truncate()).on_hover_text(c); } ui.horizontal(|ui| { // The address added is the one shown in this row; a row with none has nothing to add. @@ -2646,10 +2675,10 @@ fn formatted( add = Some((key.clone(), h.clone())); } if let Some(h) = &web { - ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(h); + ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(cut.as_deref().unwrap_or_default()); } if let Some(h) = &href - && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(h).clicked() + && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(cut.as_deref().unwrap_or_default()).clicked() { ui.ctx().copy_text(h.clone()); } @@ -4113,6 +4142,25 @@ mod tests { assert!(note.as_deref().unwrap_or("").contains("larger than 4 MB") && source.is_none(), "{note:?}"); } + #[test] + fn a_document_that_grows_when_laid_out_is_refused_instead_of_printed() { + // Nested arrays of zeros are small as written and huge once each element has its own line. + let depth = 60; + let leaf = format!("[{}]", ["0"; 200].join(",")); + let mut text = leaf; + for _ in 0..depth { + text = format!("[{}]", [text.as_str(); 2].join(",")); + if text.len() > 1 << 20 { + break; + } + } + let value: serde_json::Value = serde_json::from_str(&text).unwrap(); + let err = pretty_within(&value, 1 << 20).unwrap_err(); + assert!(err.contains("more than 1 MB"), "{err}"); + let small = serde_json::json!({"id": "a", "n": [1, 2]}); + assert!(pretty_within(&small, 1 << 20).unwrap().contains("\"id\": \"a\"")); + } + #[test] fn a_value_is_cut_at_a_line_without_printing_all_of_it() { let line = SHORT_VALUE_CHARS; From 3e286377dc52f43f04e191aff0910e44179f6ba8 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 18:53:59 -0500 Subject: [PATCH 17/33] fix(STAC): long asset addresses resolve, asset keys are cut, and rounded whole numbers are named Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 23 +++++++++++-- crates/ui-egui/src/stacui.rs | 64 ++++++++++++++++++++++++++++++++---- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 42ec160e80..4d95b63bc5 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -898,10 +898,23 @@ fn footprint_size(g: &Value) -> usize { /// An address relative to another, as a browser would resolve it (`s3://` and others are kept /// as they are, so they can be refused by name). pub fn resolve(base: &str, href: &str) -> Option { + resolve_up_to(base, href, MAX_TEXT) +} + +/// [`resolve`] for an address from an item's own document, which is not cut to the parsed item's +/// text limit: up to [`MAX_DOCUMENT_HREF`] bytes, so a long relative address still resolves. +pub fn resolve_document_href(base: &str, href: &str) -> Option { + resolve_up_to(base, href, MAX_DOCUMENT_HREF) +} + +/// The most bytes of an address taken from an item's own document. +pub const MAX_DOCUMENT_HREF: usize = 1 << 20; + +fn resolve_up_to(base: &str, href: &str, limit: usize) -> Option { // A login binding rides along only to an address on the base's own origin (`inherit`). let plain_base = rustgis_data::login_address::parse(base).ok()?.map_or(base, |b| b.url); rustgis_data::login_address::parse(href).ok()?; - let resolved = resolve_plain(plain_base, crate::logins::inner(href))?; + let resolved = resolve_plain(plain_base, crate::logins::inner(href), limit)?; Some(crate::logins::inherit(base, &resolved)) } @@ -913,9 +926,9 @@ fn has_scheme(href: &str) -> bool { && chars.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))) == Some(':') } -fn resolve_plain(base: &str, href: &str) -> Option { +fn resolve_plain(base: &str, href: &str, limit: usize) -> Option { let href = href.trim(); - if href.is_empty() || href.len() > MAX_TEXT || href.chars().any(char::is_control) { + if href.is_empty() || href.len() > limit || href.chars().any(char::is_control) { return None; } if href.contains("://") || has_scheme(href) { @@ -1682,6 +1695,10 @@ mod tests { assert_eq!(resolve("https://x.org/a/b.json", "data:text/plain,hi").as_deref(), Some("data:text/plain,hi")); assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("mailto:me@x.org")); assert_eq!(resolve("https://x.org/a/b.json", "d.tif").as_deref(), Some("https://x.org/a/d.tif")); + // A document's own address may be longer than a parsed item's text limit. + let long = "d".repeat(MAX_TEXT + 500); + assert_eq!(resolve("https://x.org/a/b.json", &long), None); + assert_eq!(resolve_document_href("https://x.org/a/b.json", &long), Some(format!("https://x.org/a/{long}"))); } /// JAXA Earth's codes for a failed retrieval: read whole, or the asset says they weren't. diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 1de0aba8b4..136624258c 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -362,7 +362,8 @@ fn land_document(f: cache::Fetched, id: &str) -> Result { let found = found.map(|f| f.chars().take(100).collect::()).unwrap_or_default(); return Err(i18n::fmt("the address answered with a document that is not this item ({found})", &[("found", &found)])); } - Ok(Landed { text, drawn, doc, source: (f.origin.url().to_string(), f.origin.reach()) }) + let rounded = rounded_numbers(&f.bytes); + Ok(Landed { text, drawn, doc, rounded, source: (f.origin.url().to_string(), f.origin.reach()) }) } /// How many bytes of `text` the pane draws: up to [`JSON_SHOWN_BYTES`], cut where a character ends. @@ -395,6 +396,8 @@ struct Landed { text: String, drawn: usize, doc: serde_json::Value, + /// How many whole numbers were too large for a 64-bit integer and are shown rounded. + rounded: usize, /// The address it was read from and the reach it was read under. source: (String, Reach), } @@ -2370,6 +2373,40 @@ fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> Ok((text, drawn, value)) } +/// How many whole numbers in a document are outside what a 64-bit integer holds. Reading takes +/// each as a floating-point number, so the text shown has a rounded value for it (`1.2e22`). +/// A number is counted where it is an integer written with no fraction or exponent. +fn rounded_numbers(bytes: &[u8]) -> usize { + let (mut count, mut i, mut in_string) = (0, 0, false); + while let Some(&b) = bytes.get(i) { + if in_string { + match b { + b'\\' => i += 1, + b'"' => in_string = false, + _ => {} + } + i += 1; + } else if b == b'"' { + in_string = true; + i += 1; + } else if b == b'-' || b.is_ascii_digit() { + let start = i; + i += 1; + while bytes.get(i).is_some_and(u8::is_ascii_digit) { + i += 1; + } + let whole = !matches!(bytes.get(i), Some(b'.' | b'e' | b'E')); + let text = bytes.get(start..i).and_then(|t| std::str::from_utf8(t).ok()).unwrap_or(""); + if whole && text.parse::().is_err() && text.parse::().is_err() && text.trim_start_matches('-').len() > 1 { + count += 1; + } + } else { + i += 1; + } + } + count +} + /// The most bytes the pretty-printed document may take. Indentation can multiply a small document /// (deeply nested arrays of numbers), so the printing stops here instead of at the end. const PRETTY_BYTES: usize = 16 << 20; @@ -2466,8 +2503,11 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { return; }; let raw = match r { - Ok(Landed { text, drawn, doc, source }) => { - let note = raw_note(&text, drawn, None); + Ok(Landed { text, drawn, doc, rounded, source }) => { + let why = (rounded > 0).then(|| { + i18n::fmt("{n} whole numbers are too large for a 64-bit integer and are shown rounded.", &[("n", &rounded.to_string())]) + }); + let note = raw_note(&text, drawn, why); Raw::Shown { text, drawn, note, doc, source: Some(source) } } Err(e) => { @@ -2647,8 +2687,10 @@ fn formatted( // The document's own address for the asset, a relative one resolved against the address // the document was read from (as written when it can't be). The full address, not the // shortened label, is what Copy link takes. - let href = - a.get("href").and_then(|h| h.as_str()).map(|h| base.and_then(|b| stac::resolve(b, h)).unwrap_or_else(|| h.to_string())); + let href = a + .get("href") + .and_then(|h| h.as_str()) + .map(|h| base.and_then(|b| stac::resolve_document_href(b, h)).unwrap_or_else(|| h.to_string())); // Offered to the browser only where the item may read it from and it needs no signing. let web = href .clone() @@ -2656,7 +2698,9 @@ fn formatted( .filter(|h| address::is_https(h) || h.get(..7).is_some_and(|s| s.eq_ignore_ascii_case("http://"))) .filter(|h| !stac::needs_signing(h)); ui.push_id(("stac_asset", id, key), |ui| { - ui.label(egui::RichText::new(key).small().strong()); + // A key can be as long as the document; the whole one stays the row's identity. + let shown = short_value(&serde_json::Value::String(key.chars().take(SHORT_VALUE_CHARS + 1).collect())); + ui.label(egui::RichText::new(shown).small().strong()); if !detail.is_empty() { ui.add(egui::Label::new(egui::RichText::new(detail).small().weak()).wrap()); } @@ -4142,6 +4186,14 @@ mod tests { assert!(note.as_deref().unwrap_or("").contains("larger than 4 MB") && source.is_none(), "{note:?}"); } + #[test] + fn whole_numbers_too_large_for_an_integer_are_counted() { + let doc = br#"{"a": 12345678901234567890123, "b": [9223372036854775807, -9223372036854775808, 18446744073709551615], + "c": 1.5e300, "d": "99999999999999999999999", "e": -123456789012345678901234, "f": 0}"#; + assert_eq!(rounded_numbers(doc), 2, "only whole numbers outside i64 and u64 count"); + assert_eq!(rounded_numbers(br#"{"a": 1, "b": "text \" 99999999999999999999999"}"#), 0); + } + #[test] fn a_document_that_grows_when_laid_out_is_refused_instead_of_printed() { // Nested arrays of zeros are small as written and huge once each element has its own line. From ec2258e99265b8f2c2dcca1b4500c443f3f714cf Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 19:25:34 -0500 Subject: [PATCH 18/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/tiles/src/stac.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 4d95b63bc5..c2f84a775b 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -1066,7 +1066,7 @@ impl Item { }; let cut = href.chars().count() > 200; let shown: String = href.chars().take(200).chain(cut.then_some('…')).collect(); - Err(format!("{}: asset '{key}' is at {shown} ({what}); RustGIS adds assets by their web or s3:// address", self.id)) + Err(format!("{}: asset '{}' is at {shown} ({what}); RustGIS adds assets by their web or s3:// address", self.id, key.chars().take(200).collect::())) } } From 02b13ec54c2459dea00577212e9c2ed66e15c5a4 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 19:39:22 -0500 Subject: [PATCH 19/33] fix(STAC): the number scan reads whole tokens, a scheme is kept only for a document's address, and the format check passes Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 40 +++++++++++++++++----------- crates/ui-egui/src/stacui.rs | 51 +++++++++++++++++++++++++++--------- 2 files changed, 64 insertions(+), 27 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index c2f84a775b..76df0d12db 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -898,40 +898,43 @@ fn footprint_size(g: &Value) -> usize { /// An address relative to another, as a browser would resolve it (`s3://` and others are kept /// as they are, so they can be refused by name). pub fn resolve(base: &str, href: &str) -> Option { - resolve_up_to(base, href, MAX_TEXT) + resolve_up_to(base, href, MAX_TEXT, false) } /// [`resolve`] for an address from an item's own document, which is not cut to the parsed item's -/// text limit: up to [`MAX_DOCUMENT_HREF`] bytes, so a long relative address still resolves. +/// text limit: up to [`MAX_DOCUMENT_HREF`] bytes (64 KB), so a long relative address still resolves. pub fn resolve_document_href(base: &str, href: &str) -> Option { - resolve_up_to(base, href, MAX_DOCUMENT_HREF) + resolve_up_to(base, href, MAX_DOCUMENT_HREF, true) } /// The most bytes of an address taken from an item's own document. -pub const MAX_DOCUMENT_HREF: usize = 1 << 20; +pub const MAX_DOCUMENT_HREF: usize = 64 << 10; -fn resolve_up_to(base: &str, href: &str, limit: usize) -> Option { +fn resolve_up_to(base: &str, href: &str, limit: usize, schemes: bool) -> Option { // A login binding rides along only to an address on the base's own origin (`inherit`). let plain_base = rustgis_data::login_address::parse(base).ok()?.map_or(base, |b| b.url); rustgis_data::login_address::parse(href).ok()?; - let resolved = resolve_plain(plain_base, crate::logins::inner(href), limit)?; + let resolved = resolve_plain(plain_base, crate::logins::inner(href), limit, schemes)?; Some(crate::logins::inherit(base, &resolved)) } /// Whether `href` begins with a URI scheme (`data:`, `mailto:`): a letter, then letters, digits, -/// `+`, `-` or `.`, then a colon. Such an address is not relative to anything. +/// `+`, `-` or `.`, then a colon. Such an address is not relative to anything. A single letter +/// (`c:/a.tif`) is a drive, not a scheme, which matches what `check_asset_scheme` names. fn has_scheme(href: &str) -> bool { - let mut chars = href.chars(); - chars.next().is_some_and(|c| c.is_ascii_alphabetic()) - && chars.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))) == Some(':') + href.split_once(':').is_some_and(|(s, _)| { + s.len() > 1 + && s.starts_with(|c: char| c.is_ascii_alphabetic()) + && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) } -fn resolve_plain(base: &str, href: &str, limit: usize) -> Option { +fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option { let href = href.trim(); if href.is_empty() || href.len() > limit || href.chars().any(char::is_control) { return None; } - if href.contains("://") || has_scheme(href) { + if href.contains("://") || (schemes && has_scheme(href)) { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; @@ -1066,7 +1069,11 @@ impl Item { }; let cut = href.chars().count() > 200; let shown: String = href.chars().take(200).chain(cut.then_some('…')).collect(); - Err(format!("{}: asset '{}' is at {shown} ({what}); RustGIS adds assets by their web or s3:// address", self.id, key.chars().take(200).collect::())) + Err(format!( + "{}: asset '{}' is at {shown} ({what}); RustGIS adds assets by their web or s3:// address", + self.id, + key.chars().take(200).collect::() + )) } } @@ -1692,9 +1699,12 @@ mod tests { assert_eq!(resolve("https://x.org/a", "s3://b/k").as_deref(), Some("s3://b/k")); assert_eq!(resolve("https://x.org/a", ""), None); // An address with a scheme of its own is not relative to anything. - assert_eq!(resolve("https://x.org/a/b.json", "data:text/plain,hi").as_deref(), Some("data:text/plain,hi")); - assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("mailto:me@x.org")); + assert_eq!(resolve_document_href("https://x.org/a/b.json", "data:text/plain,hi").as_deref(), Some("data:text/plain,hi")); + assert_eq!(resolve_document_href("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("mailto:me@x.org")); assert_eq!(resolve("https://x.org/a/b.json", "d.tif").as_deref(), Some("https://x.org/a/d.tif")); + // Only an address from a document keeps a scheme as written; an item's own link is joined as before. + assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("https://x.org/a/mailto:me@x.org")); + assert_eq!(resolve_document_href("https://x.org/a/b.json", "c:/a.tif").as_deref(), Some("https://x.org/a/c:/a.tif")); // A document's own address may be longer than a parsed item's text limit. let long = "d".repeat(MAX_TEXT + 500); assert_eq!(resolve("https://x.org/a/b.json", &long), None); diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 136624258c..28579b3809 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -396,7 +396,7 @@ struct Landed { text: String, drawn: usize, doc: serde_json::Value, - /// How many whole numbers were too large for a 64-bit integer and are shown rounded. + /// How many numbers have more digits than reading keeps and are shown rounded. rounded: usize, /// The address it was read from and the reach it was read under. source: (String, Reach), @@ -2367,15 +2367,22 @@ fn add_item_index(app: &mut RustGisApp, _item: &Item, _index: &str) { /// The catalog's document pretty-printed, and how many of its bytes the pane draws (a cut on a /// character boundary). Not JSON is an error: it is not shown as the item. fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> { - let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]))?; + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| { + if e.to_string().contains("number out of range") { + // Valid JSON, but a number no floating-point value holds (`1e400`). + i18n::fmt("a number is too large to read ({e})", &[("e", &e.to_string())]) + } else { + i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]) + } + })?; let text = pretty_within(&value, PRETTY_BYTES)?; let drawn = shown_bytes(&text); Ok((text, drawn, value)) } -/// How many whole numbers in a document are outside what a 64-bit integer holds. Reading takes -/// each as a floating-point number, so the text shown has a rounded value for it (`1.2e22`). -/// A number is counted where it is an integer written with no fraction or exponent. +/// How many numbers in a document hold more than reading keeps. Reading takes a whole number +/// outside a 64-bit integer, and any number with more than 17 significant digits, as a +/// floating-point number, so the text shown has a rounded value for it (`1.2e22`, `0.1`). fn rounded_numbers(bytes: &[u8]) -> usize { let (mut count, mut i, mut in_string) = (0, 0, false); while let Some(&b) = bytes.get(i) { @@ -2390,14 +2397,14 @@ fn rounded_numbers(bytes: &[u8]) -> usize { in_string = true; i += 1; } else if b == b'-' || b.is_ascii_digit() { + // The whole token: sign, digits, fraction and exponent. let start = i; i += 1; - while bytes.get(i).is_some_and(u8::is_ascii_digit) { + while bytes.get(i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'.' | b'e' | b'E' | b'+' | b'-')) { i += 1; } - let whole = !matches!(bytes.get(i), Some(b'.' | b'e' | b'E')); - let text = bytes.get(start..i).and_then(|t| std::str::from_utf8(t).ok()).unwrap_or(""); - if whole && text.parse::().is_err() && text.parse::().is_err() && text.trim_start_matches('-').len() > 1 { + let token = bytes.get(start..i).and_then(|t| std::str::from_utf8(t).ok()).unwrap_or(""); + if is_rounded(token) { count += 1; } } else { @@ -2407,6 +2414,19 @@ fn rounded_numbers(bytes: &[u8]) -> usize { count } +/// Whether the number written as `token` is not kept exactly: a whole number outside `i64` and +/// `u64`, or one with more than 17 significant digits in its mantissa. +fn is_rounded(token: &str) -> bool { + let plain = token.trim_start_matches('-'); + let mantissa = plain.split(['e', 'E']).next().unwrap_or(""); + let written = !plain.contains(['.', 'e', 'E']); + if written { + return plain.len() > 1 && token.parse::().is_err() && token.parse::().is_err(); + } + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + digits.trim_matches('0').len() > 17 +} + /// The most bytes the pretty-printed document may take. Indentation can multiply a small document /// (deeply nested arrays of numbers), so the printing stops here instead of at the end. const PRETTY_BYTES: usize = 16 << 20; @@ -2504,9 +2524,8 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { }; let raw = match r { Ok(Landed { text, drawn, doc, rounded, source }) => { - let why = (rounded > 0).then(|| { - i18n::fmt("{n} whole numbers are too large for a 64-bit integer and are shown rounded.", &[("n", &rounded.to_string())]) - }); + let why = (rounded > 0) + .then(|| i18n::fmt("{n} numbers have more digits than are kept and are shown rounded.", &[("n", &rounded.to_string())])); let note = raw_note(&text, drawn, why); Raw::Shown { text, drawn, note, doc, source: Some(source) } } @@ -4192,6 +4211,14 @@ mod tests { "c": 1.5e300, "d": "99999999999999999999999", "e": -123456789012345678901234, "f": 0}"#; assert_eq!(rounded_numbers(doc), 2, "only whole numbers outside i64 and u64 count"); assert_eq!(rounded_numbers(br#"{"a": 1, "b": "text \" 99999999999999999999999"}"#), 0); + // A decimal is one token: its fraction digits are not a whole number of their own, and + // it counts only when it has more digits than an f64 keeps. + assert_eq!(rounded_numbers(b"[0.5, 1.5e300, 0.1000000000000000000, 123456789.12345]"), 0); + assert_eq!(rounded_numbers(b"[0.12345678901234567890123]"), 1); + assert_eq!(rounded_numbers(b"[0.1000000000000000055511151231257827, 1.2345678901234567890e5]"), 2); + // Valid JSON with a number no float holds is named, not called "not JSON". + let err = raw_text(br#"{"a": 1e400}"#).unwrap_err(); + assert!(err.contains("too large to read") && !err.contains("not JSON"), "{err}"); } #[test] From 76436547179e5f249cfb3f5ee3c118f82ba0cb33 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 19:52:09 -0500 Subject: [PATCH 20/33] fix(STAC): a number with more than 15 digits is named as rounded, the not-this-item reasons are told apart, and the guide lists why the pane falls back Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/stacui.rs | 33 +++++++++++++++++++++++---------- docs/user-guide/web-data.md | 7 ++++--- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 28579b3809..1c61226ce1 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -358,9 +358,17 @@ fn land_document(f: cache::Fetched, id: &str) -> Result { let (text, drawn, doc) = raw_text(&f.bytes)?; let is = doc.get("type").and_then(|t| t.as_str()) == Some("Feature"); let found = doc.get("id").and_then(|i| i.as_str()); - if !is || found != Some(id) { - let found = found.map(|f| f.chars().take(100).collect::()).unwrap_or_default(); - return Err(i18n::fmt("the address answered with a document that is not this item ({found})", &[("found", &found)])); + if !is { + return Err(tl!("the address answered with a document that is not a single item (its type is not Feature)").to_string()); + } + if found != Some(id) { + return Err(match found { + Some(f) => { + let f = f.chars().take(100).collect::(); + i18n::fmt("the address answered with a document that is not this item ({found})", &[("found", &f)]) + } + None => tl!("the address answered with a document that is not this item (it has no id)").to_string(), + }); } let rounded = rounded_numbers(&f.bytes); Ok(Landed { text, drawn, doc, rounded, source: (f.origin.url().to_string(), f.origin.reach()) }) @@ -2381,8 +2389,8 @@ fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> } /// How many numbers in a document hold more than reading keeps. Reading takes a whole number -/// outside a 64-bit integer, and any number with more than 17 significant digits, as a -/// floating-point number, so the text shown has a rounded value for it (`1.2e22`, `0.1`). +/// outside a 64-bit integer, and any number with more than 15 significant digits, as a +/// floating-point number, so the text shown has a rounded value for it (`1.2e22`, `0.1`); a double keeps 15 digits for certain. fn rounded_numbers(bytes: &[u8]) -> usize { let (mut count, mut i, mut in_string) = (0, 0, false); while let Some(&b) = bytes.get(i) { @@ -2415,7 +2423,7 @@ fn rounded_numbers(bytes: &[u8]) -> usize { } /// Whether the number written as `token` is not kept exactly: a whole number outside `i64` and -/// `u64`, or one with more than 17 significant digits in its mantissa. +/// `u64`, or one with more than 15 significant digits in its mantissa. fn is_rounded(token: &str) -> bool { let plain = token.trim_start_matches('-'); let mantissa = plain.split(['e', 'E']).next().unwrap_or(""); @@ -2424,7 +2432,7 @@ fn is_rounded(token: &str) -> bool { return plain.len() > 1 && token.parse::().is_err() && token.parse::().is_err(); } let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); - digits.trim_matches('0').len() > 17 + digits.trim_matches('0').len() > 15 } /// The most bytes the pretty-printed document may take. Indentation can multiply a small document @@ -4189,13 +4197,17 @@ mod tests { let mut app = RustGisApp::with_sample(); app.ui.stac.items = vec![json_test_item(true)]; // Another item, a collection, and a document with no id: none is this item's own. - for doc in [json!({"type": "Feature", "id": "other"}), json!({"type": "Collection", "id": "scene-1"}), json!({"type": "Feature"})] { + for (doc, said) in [ + (json!({"type": "Feature", "id": "other"}), "not this item (other)"), + (json!({"type": "Collection", "id": "scene-1"}), "not a single item"), + (json!({"type": "Feature"}), "it has no id"), + ] { cache::set_fetcher(move |_, done| done(Ok(doc.to_string().into_bytes()))); start_json(&mut app, 0); poll_json(&mut app, &ctx); let Some(JsonView { raw: Raw::Shown { note, source, .. }, .. }) = &app.ui.stac.json else { panic!("landed") }; let note = note.as_deref().unwrap_or(""); - assert!(note.contains("not this item") && source.is_none(), "{note}"); + assert!(note.contains(said) && source.is_none(), "{note}"); } // More than the cap: said, and the trimmed copy shown, not the document. cache::set_fetcher(|_, done| done(Ok(vec![b' '; DOCUMENT_BYTES + 1]))); @@ -4214,7 +4226,8 @@ mod tests { // A decimal is one token: its fraction digits are not a whole number of their own, and // it counts only when it has more digits than an f64 keeps. assert_eq!(rounded_numbers(b"[0.5, 1.5e300, 0.1000000000000000000, 123456789.12345]"), 0); - assert_eq!(rounded_numbers(b"[0.12345678901234567890123]"), 1); + assert_eq!(rounded_numbers(b"[0.12345678901234567890123, 0.1234567890123456]"), 2); + assert_eq!(rounded_numbers(b"[0.123456789012345]"), 0, "15 digits are kept"); assert_eq!(rounded_numbers(b"[0.1000000000000000055511151231257827, 1.2345678901234567890e5]"), 2); // Valid JSON with a number no float holds is named, not called "not JSON". let err = raw_text(br#"{"a": 1e400}"#).unwrap_err(); diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index e9c73bd011..b605ee78d7 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -65,9 +65,10 @@ reads the item's own document from its address and shows it in two tabs: **Forma its properties, its assets and its links, up to 200 rows a section with the rest counted; each asset has **Add to map**, **Download** (a link to its web address, not offered for an address that needs signing, such as Planetary Computer's) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first -200,000 bytes are drawn and Copy takes all of it). An item with no address of its own, or one the -network reach it was found with doesn't allow reading, shows what RustGIS read of it instead (the first 100 -plain properties, long text cut), with a line saying so. The asset chosen at first is `visual` (true colour) when there is one, else the first +200,000 bytes are drawn and Copy takes all of it). When the document can't be shown (the item has no address of its own, the +network reach it was found with doesn't allow reading, the read fails, the answer isn't JSON or isn't +this item, or it is over 4 MB, or over 16 MB once laid out), the pane shows what RustGIS read of the item instead (the first 100 +plain properties, long text cut), with a line above the text giving the reason. The asset chosen at first is `visual` (true colour) when there is one, else the first GeoTIFF, else the first point cloud, else the first data asset, preferring HTTP(S) assets. Cloud-optimised GeoTIFF, GeoParquet and FlatGeobuf assets are read in place, and PMTiles a tile at a time; other assets download whole (see [Files on the web](data-formats.md#files-on-the-web)). From 9704b2ef171e854916c7bbd0355bfe66677b072b Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 21:40:56 -0500 Subject: [PATCH 21/33] fix(STAC): a document's address is absolute only by its leading scheme, a query-only address keeps the item's path, and an asset keeps its document's reach as Details closes Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 19 ++++++++++++++++++- crates/ui-egui/src/stacui.rs | 18 +++++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 76df0d12db..0bd268ff45 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -934,10 +934,18 @@ fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option< if href.is_empty() || href.len() > limit || href.chars().any(char::is_control) { return None; } - if href.contains("://") || (schemes && has_scheme(href)) { + // A document's address is absolute only by its own leading scheme: another address inside its + // query (`download?url=https://…`) does not make it one. An item's link keeps the older test. + let absolute = if schemes { has_scheme(href) } else { href.contains("://") }; + if absolute { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; + // A reference of only a query or a fragment keeps the base's own path (RFC 3986 §5.2.2). + if href.starts_with('?') || href.starts_with('#') { + let cut: &[char] = if href.starts_with('?') { &['?', '#'] } else { &['#'] }; + return Some(format!("{}{href}", base.split(cut).next().unwrap_or(base))); + } let host_end = rest.find('/').unwrap_or(rest.len()); let origin = format!("{scheme}://{}", rest.get(..host_end)?); if let Some(abs) = href.strip_prefix("//") { @@ -1704,6 +1712,15 @@ mod tests { assert_eq!(resolve("https://x.org/a/b.json", "d.tif").as_deref(), Some("https://x.org/a/d.tif")); // Only an address from a document keeps a scheme as written; an item's own link is joined as before. assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("https://x.org/a/mailto:me@x.org")); + // A query or a fragment alone keeps the base's path; an address inside a query is not absolute. + let base = "https://x.org/items/scene.json?v=1#top"; + assert_eq!(resolve_document_href(base, "?asset=b04").as_deref(), Some("https://x.org/items/scene.json?asset=b04")); + assert_eq!(resolve(base, "?asset=b04").as_deref(), Some("https://x.org/items/scene.json?asset=b04")); + assert_eq!(resolve_document_href(base, "#b04").as_deref(), Some("https://x.org/items/scene.json?v=1#b04")); + assert_eq!( + resolve_document_href(base, "download?url=https://store.example/b04.tif").as_deref(), + Some("https://x.org/items/download?url=https://store.example/b04.tif") + ); assert_eq!(resolve_document_href("https://x.org/a/b.json", "c:/a.tif").as_deref(), Some("https://x.org/a/c:/a.tif")); // A document's own address may be longer than a parsed item's text limit. let long = "d".repeat(MAX_TEXT + 500); diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 1c61226ce1..27e08c589e 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -947,8 +947,7 @@ fn document_source(app: &RustGisApp) -> Option<(String, Reach)> { /// Adds the asset `key` at `href`, the address its document shows, under the item's name, after /// the checks [`Item::asset_href`] makes, held to the document's own reach. -fn add_document_asset(app: &mut RustGisApp, item: &Item, key: &str, href: &str) { - let source = document_source(app); +fn add_document_asset(app: &mut RustGisApp, item: &Item, key: &str, href: &str, source: Option<(String, Reach)>) { let allowed = document_asset_allowed(item, key, href, source.as_ref().map(|(b, r)| (b.as_str(), *r))); let (from, public) = match source { Some((base, reach)) => (base, reach == Reach::Public), @@ -2254,6 +2253,9 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { }); } }); + // The document an asset came from is kept before Details can close it in this same frame, so + // the asset is still held to that document's reach. + let from_document = asset.as_ref().and_then(|_| document_source(app)); if let Some(i) = details { let open = app.ui.stac.details != Some(i); app.ui.stac.details = open.then_some(i); @@ -2270,7 +2272,7 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { if let Some((i, key, href)) = asset && let Some(item) = app.ui.stac.items.get(i).cloned() { - add_document_asset(app, &item, &key, &href); + add_document_asset(app, &item, &key, &href, from_document); } if cancel { // Drops the read (a download can't be stopped once started: it runs to its end, at most @@ -4285,6 +4287,16 @@ mod tests { } } + #[test] + fn an_asset_added_as_details_closes_keeps_the_documents_reach() { + let item = json_test_item(true); + let mut app = RustGisApp::with_sample(); + // The document was public; the view that held it is gone (Details closed this frame). + assert!(document_source(&app).is_none()); + let public = Some(("https://stac.example/api/items/scene-1".to_string(), Reach::Public)); + add_document_asset(&mut app, &item, "k", "http://127.0.0.1:8080/a.tif", public); + assert!(app.ui.stac.error.is_some(), "a loopback address from a public document is refused"); + } #[test] fn an_assets_row_acts_on_the_address_the_documents_row_shows_even_when_the_search_item_has_none() { let _turn = crate::fetching::turn(); From 5475351e508bd4b675552bd35d5112f8a882c1e4 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 22:14:50 -0500 Subject: [PATCH 22/33] fix(STAC): a document's item must agree on its collection, an address is resolved by its path alone, an underflowed number is named, and Copy and Cancel act before Details changes the card Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 11 ++++++--- crates/ui-egui/src/stacui.rs | 45 ++++++++++++++++++++++++------------ docs/user-guide/web-data.md | 4 ++-- 3 files changed, 40 insertions(+), 20 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 0bd268ff45..5fa4b27db5 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -946,7 +946,7 @@ fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option< let cut: &[char] = if href.starts_with('?') { &['?', '#'] } else { &['#'] }; return Some(format!("{}{href}", base.split(cut).next().unwrap_or(base))); } - let host_end = rest.find('/').unwrap_or(rest.len()); + let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let origin = format!("{scheme}://{}", rest.get(..host_end)?); if let Some(abs) = href.strip_prefix("//") { return Some(format!("{scheme}://{abs}")); @@ -960,7 +960,9 @@ fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option< if !path.ends_with('/') { parts.pop(); } - for seg in href.split('/') { + // Only the path is worked out; its query and fragment ride along as written. + let (relative, tail) = href.split_at(href.find(['?', '#']).unwrap_or(href.len())); + for seg in relative.split('/') { match seg { "." => {} ".." => { @@ -969,7 +971,7 @@ fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option< s => parts.push(s), } } - Some(format!("{origin}/{}", parts.join("/"))) + Some(format!("{origin}/{}{tail}", parts.join("/"))) } impl Asset { @@ -1712,6 +1714,9 @@ mod tests { assert_eq!(resolve("https://x.org/a/b.json", "d.tif").as_deref(), Some("https://x.org/a/d.tif")); // Only an address from a document keeps a scheme as written; an item's own link is joined as before. assert_eq!(resolve("https://x.org/a/b.json", "mailto:me@x.org").as_deref(), Some("https://x.org/a/mailto:me@x.org")); + // A host ends at a query or fragment too; a query is not worked out as a path. + assert_eq!(resolve("https://x.org?a=1", "d.tif").as_deref(), Some("https://x.org/d.tif")); + assert_eq!(resolve("https://x.org/a/b.json", "../d.tif?p=x/../y#f").as_deref(), Some("https://x.org/d.tif?p=x/../y#f")); // A query or a fragment alone keeps the base's path; an address inside a query is not absolute. let base = "https://x.org/items/scene.json?v=1#top"; assert_eq!(resolve_document_href(base, "?asset=b04").as_deref(), Some("https://x.org/items/scene.json?asset=b04")); diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 27e08c589e..afc4ade32d 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -330,7 +330,7 @@ fn post_service(app: &mut RustGisApp, url: &str, body: String) -> Answer { /// it), and has it parsed and printed there too, so the window only takes the finished text. The /// document must be this item (a `Feature` with its id), else it is refused with the reason. The /// read can't be stopped once started: an abandoned one runs to its end and its answer is dropped. -fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str) -> DocAnswer { +fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str, collection: &str) -> DocAnswer { // Read under the reach `start_json` checked the address under (the item's own), not widened // by whether the dialog's API came from a document. let connection = selected_connection(app); @@ -341,9 +341,9 @@ fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str }; let slot: DocAnswer = Slot::default(); let land = slot.clone(); - let id = id.to_string(); + let (id, collection) = (id.to_string(), collection.to_string()); let done = Box::new(move |r: Result| { - *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r.and_then(|f| land_document(f, &id))); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r.and_then(|f| land_document(f, &id, &collection))); }); let ceiling = if from_document { Reach::Public } else { Reach::Local }; cache::download_limited_reaching_with_origin(&url, DOCUMENT_BYTES, None, ceiling, done); @@ -351,7 +351,7 @@ fn fetch_document(app: &mut RustGisApp, url: &str, from_document: bool, id: &str } /// A fetched document as the inspector shows it, if it is the item `id`. -fn land_document(f: cache::Fetched, id: &str) -> Result { +fn land_document(f: cache::Fetched, id: &str, collection: &str) -> Result { if f.bytes.len() > DOCUMENT_BYTES { return Err(i18n::fmt("larger than {n} MB", &[("n", &(DOCUMENT_BYTES >> 20).to_string())])); } @@ -370,6 +370,13 @@ fn land_document(f: cache::Fetched, id: &str) -> Result { None => tl!("the address answered with a document that is not this item (it has no id)").to_string(), }); } + // The same id can be in two collections: when both say which, they must agree. + if let Some(theirs) = + doc.get("collection").and_then(|c| c.as_str()).filter(|c| !c.is_empty() && !collection.is_empty() && *c != collection) + { + let theirs = theirs.chars().take(100).collect::(); + return Err(i18n::fmt("the address answered with an item of another collection ({found})", &[("found", &theirs)])); + } let rounded = rounded_numbers(&f.bytes); Ok(Landed { text, drawn, doc, rounded, source: (f.origin.url().to_string(), f.origin.reach()) }) } @@ -1199,6 +1206,8 @@ pub(crate) fn switch_api(st: &mut State, url: &str) { fn drop_listing(st: &mut State) { st.collections.clear(); st.items.clear(); + // The open inspector belongs to a card of the list, and so does a read still going for it. + (st.details, st.json) = (None, None); st.collection.clear(); (st.node, st.node_title, st.node_reach) = (String::new(), String::new(), None); st.trail.clear(); @@ -2256,6 +2265,17 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { // The document an asset came from is kept before Details can close it in this same frame, so // the asset is still held to that document's reach. let from_document = asset.as_ref().and_then(|_| document_source(app)); + // Copy and Cancel act on the card they were pressed on, before Details can open another. + if copy && let Some(JsonView { raw: Raw::Shown { text, .. }, .. }) = &app.ui.stac.json { + ui.ctx().copy_text(text.clone()); + } + if cancel { + // Drops the read (a download can't be stopped once started: it runs to its end, at most + // 4 MB, and its answer is not kept) and with it the card's details. + app.ui.stac.json = None; + app.ui.stac.details = None; + details = None; + } if let Some(i) = details { let open = app.ui.stac.details != Some(i); app.ui.stac.details = open.then_some(i); @@ -2274,15 +2294,6 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { { add_document_asset(app, &item, &key, &href, from_document); } - if cancel { - // Drops the read (a download can't be stopped once started: it runs to its end, at most - // 4 MB, and its answer is not kept) and with it the card's details. - app.ui.stac.json = None; - app.ui.stac.details = None; - } - if copy && let Some(JsonView { raw: Raw::Shown { text, .. }, .. }) = &app.ui.stac.json { - ui.ctx().copy_text(text.clone()); - } if let Some(e) = zoom.and_then(|i| app.ui.stac.items.get(i)).and_then(|i| i.bbox) { app.session.zoom_to(&rustgis_engine::geom::Extent::new(e[0], e[1], e[2], e[3])); app.map.invalidate(); @@ -2434,7 +2445,9 @@ fn is_rounded(token: &str) -> bool { return plain.len() > 1 && token.parse::().is_err() && token.parse::().is_err(); } let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); - digits.trim_matches('0').len() > 15 + // A number with a nonzero digit that reads as zero (`1e-400`) has lost everything. + let to_zero = !digits.trim_matches('0').is_empty() && token.parse::().is_ok_and(|v| v == 0.0); + to_zero || digits.trim_matches('0').len() > 15 } /// The most bytes the pretty-printed document may take. Indentation can multiply a small document @@ -2511,7 +2524,7 @@ fn start_json(app: &mut RustGisApp, i: usize) { let from = item_document_origin(app, &item); let ceiling = rustgis_engine::cmd::layer::origin_ceiling(Some(&from), public); let raw = match address::check_reach(&url, ceiling) { - Ok(()) => Raw::Loading(fetch_document(app, &url, public, &item.id)), + Ok(()) => Raw::Loading(fetch_document(app, &url, public, &item.id, &item.collection)), Err(e) => trimmed(i18n::fmt( "{url} was not read: {e}. This is what RustGIS read of the item instead: the first 100 plain properties, long text cut.", &[("url", &rustgis_engine::sources::address_in_message(&url)), ("e", &e)], @@ -4203,6 +4216,7 @@ mod tests { (json!({"type": "Feature", "id": "other"}), "not this item (other)"), (json!({"type": "Collection", "id": "scene-1"}), "not a single item"), (json!({"type": "Feature"}), "it has no id"), + (json!({"type": "Feature", "id": "scene-1", "collection": "elsewhere"}), "another collection (elsewhere)"), ] { cache::set_fetcher(move |_, done| done(Ok(doc.to_string().into_bytes()))); start_json(&mut app, 0); @@ -4230,6 +4244,7 @@ mod tests { assert_eq!(rounded_numbers(b"[0.5, 1.5e300, 0.1000000000000000000, 123456789.12345]"), 0); assert_eq!(rounded_numbers(b"[0.12345678901234567890123, 0.1234567890123456]"), 2); assert_eq!(rounded_numbers(b"[0.123456789012345]"), 0, "15 digits are kept"); + assert_eq!(rounded_numbers(b"[1e-400, 0.0, 0e5, 0.000]"), 1, "only the nonzero number that reads as zero counts"); assert_eq!(rounded_numbers(b"[0.1000000000000000055511151231257827, 1.2345678901234567890e5]"), 2); // Valid JSON with a number no float holds is named, not called "not JSON". let err = raw_text(br#"{"a": 1e400}"#).unwrap_err(); diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index b605ee78d7..f33f695927 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -63,8 +63,8 @@ a layer. Each card has the item's preview picture when it has one, its id, a col cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **Details**. Details reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, its properties, its assets and its links, up to 200 rows a section with -the rest counted; each asset has **Add to map**, **Download** (a link to its web address, not offered for -an address that needs signing, such as Planetary Computer's) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first +the rest counted; each asset has **Add to map**, **Download** (a link to its web address, offered only for an +http or https address the item may read from and that needs no signing, such as Planetary Computer's does; an asset can still be added or copied without it) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first 200,000 bytes are drawn and Copy takes all of it). When the document can't be shown (the item has no address of its own, the network reach it was found with doesn't allow reading, the read fails, the answer isn't JSON or isn't this item, or it is over 4 MB, or over 16 MB once laid out), the pane shows what RustGIS read of the item instead (the first 100 From 5f2a8a9b2b27699d3293d5c68c301b428bfffc1b Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 22:19:19 -0500 Subject: [PATCH 23/33] fix(STAC): an asset's layer name cuts its key, and a document address that can't be resolved offers no action Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/stacui.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index afc4ade32d..cf34fdc522 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -961,7 +961,7 @@ fn add_document_asset(app: &mut RustGisApp, item: &Item, key: &str, href: &str, None => (item_document_origin(app, item), item.origin_reach == Reach::Public), }; match allowed { - Ok(()) => add_signed(app, href, &format!("{} {key}", item.id), &from, public), + Ok(()) => add_signed(app, href, &format!("{} {}", item.id, key.chars().take(200).collect::()), &from, public), Err(e) => app.ui.stac.error = Some(e), } } @@ -2727,12 +2727,14 @@ fn formatted( let part = |k: &str| a.get(k).filter(|v| !v.is_null()).map(short_value); let detail = [part("title"), part("type"), part("roles")].into_iter().flatten().collect::>().join(" · "); // The document's own address for the asset, a relative one resolved against the address - // the document was read from (as written when it can't be). The full address, not the + // the document was read from (as written when the document has no address). The full address, not the // shortened label, is what Copy link takes. - let href = a - .get("href") - .and_then(|h| h.as_str()) - .map(|h| base.and_then(|b| stac::resolve_document_href(b, h)).unwrap_or_else(|| h.to_string())); + let href = a.get("href").and_then(|h| h.as_str()).and_then(|h| match base { + // A document read from an address names its assets by it: one that can't be resolved + // (too long, or not an address) has none, so no action is offered for it. + Some(b) => stac::resolve_document_href(b, h), + None => Some(h.to_string()), + }); // Offered to the browser only where the item may read it from and it needs no signing. let web = href .clone() From 3bf90cf8669ad053e83d7f5c6a62b8bd83906c47 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 22:31:18 -0500 Subject: [PATCH 24/33] fix(STAC): the merged address resolver takes its limit and a document's own schemes again Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 4d2ad3b425..5c253fda2b 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -925,12 +925,24 @@ fn has_scheme(s: &str) -> bool { bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')) } -fn resolve_plain(base: &str, href: &str) -> Option { +/// Whether `href` begins with a URI scheme even without `//` (`data:`, `mailto:`): a letter, then +/// letters, digits, `+`, `-` or `.`, then a colon. A single letter (`c:/a.tif`) is a drive, not a +/// scheme, which matches what `check_asset_scheme` names. +fn has_uri_scheme(href: &str) -> bool { + href.split_once(':').is_some_and(|(s, _)| { + s.len() > 1 + && s.starts_with(|c: char| c.is_ascii_alphabetic()) + && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) +} + +fn resolve_plain(base: &str, href: &str, limit: usize, schemes: bool) -> Option { let href = href.trim(); if href.is_empty() || href.len() > limit || href.chars().any(char::is_control) { return None; } - if has_scheme(href) { + // A document's address with a scheme of its own (`data:`, `mailto:`) is kept as written too. + if has_scheme(href) || (schemes && has_uri_scheme(href)) { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; From c4c7905bfa9104a9c2708b18a5e460f4399228d0 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 22:36:36 -0500 Subject: [PATCH 25/33] fix(STAC): signing an asset keeps a search under way, the fallback JSON is bounded, and an id cut by the parser is not compared Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 2 +- crates/ui-egui/src/stacui.rs | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 5c253fda2b..4aa7d9d66d 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -29,7 +29,7 @@ const MAX_COLLECTIONS: usize = 2000; /// The most assets read from an item. const MAX_ASSETS: usize = 100; /// The longest text kept (titles, ids, addresses). -const MAX_TEXT: usize = 2000; +pub const MAX_TEXT: usize = 2000; /// The most coordinates a footprint keeps. const MAX_FOOTPRINT: usize = 20_000; /// The most properties kept with an item. diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index cf34fdc522..335960c11f 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -361,6 +361,10 @@ fn land_document(f: cache::Fetched, id: &str, collection: &str) -> Result= stac::MAX_TEXT || collection.chars().count() >= stac::MAX_TEXT { + return Err(tl!("the item's id or collection is too long to check against its document").to_string()); + } if found != Some(id) { return Err(match found { Some(f) => { @@ -858,6 +862,11 @@ fn add_signed(app: &mut RustGisApp, href: &str, name: &str, from: &str, public: add_url(app, &signed, name, from, public); } None => { + // One request is waited for at a time: signing must not drop a search under way. + if app.ui.stac.waiting.is_some() { + app.ui.stac.error = Some(tl!("Wait for the search to finish, then add the asset").to_string()); + return; + } if let Err(e) = address::check_reach(&token_url, ceiling) { app.ui.stac.error = Some(e); return; @@ -2483,7 +2492,8 @@ fn pretty_within(value: &serde_json::Value, limit: usize) -> Result (String, usize, serde_json::Value) { let doc = stac::item_json_with(item, true); - let text = serde_json::to_string_pretty(&doc).unwrap_or_default(); + // Pretty-printed within the budget; past it, the compact form (no larger than the tree itself). + let text = pretty_within(&doc, PRETTY_BYTES).unwrap_or_else(|_| serde_json::to_string(&doc).unwrap_or_default()); let drawn = shown_bytes(&text); (text, drawn, doc) } From 3b3c79d1b80069c3093ddccdc8fe9ddebb6033dc Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 23:07:34 -0500 Subject: [PATCH 26/33] Apply batched suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/ui-egui/src/stacui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 335960c11f..48a535d2f7 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -864,7 +864,7 @@ fn add_signed(app: &mut RustGisApp, href: &str, name: &str, from: &str, public: None => { // One request is waited for at a time: signing must not drop a search under way. if app.ui.stac.waiting.is_some() { - app.ui.stac.error = Some(tl!("Wait for the search to finish, then add the asset").to_string()); + app.ui.stac.error = Some(tl!("Wait for the request under way to finish, then add the asset").to_string()); return; } if let Err(e) = address::check_reach(&token_url, ceiling) { From 67c3f2e8b19105f7952c1ae9d126f5b2e3da6e2d Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sat, 28 Nov 2026 23:42:42 -0500 Subject: [PATCH 27/33] fix(STAC): a document nested too deeply says so, an asset row with no address says why, and the Download note no longer inverts signing Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/stacui.rs | 14 ++++++++++++++ docs/user-guide/web-data.md | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 48a535d2f7..5fb26b609a 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2401,6 +2401,9 @@ fn raw_text(bytes: &[u8]) -> Result<(String, usize, serde_json::Value), String> if e.to_string().contains("number out of range") { // Valid JSON, but a number no floating-point value holds (`1e400`). i18n::fmt("a number is too large to read ({e})", &[("e", &e.to_string())]) + } else if e.to_string().contains("recursion limit") { + // Valid JSON, nested deeper than the reader follows (128 levels). + i18n::fmt("the document is nested too deeply to read ({e})", &[("e", &e.to_string())]) } else { i18n::fmt("not JSON: {e}", &[("e", &e.to_string())]) } @@ -2775,6 +2778,14 @@ fn formatted( if let Some(h) = &web { ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(cut.as_deref().unwrap_or_default()); } + if href.is_none() && a.get("href").is_some() { + // Never silent: say why the row has no actions. + ui.label( + egui::RichText::new(tl!("No address: it can't be read or resolved against the document's address")) + .small() + .weak(), + ); + } if let Some(h) = &href && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(cut.as_deref().unwrap_or_default()).clicked() { @@ -4081,6 +4092,9 @@ mod tests { let note = raw_note(&text, drawn, Some("why.".into())).unwrap(); assert!(note.starts_with("why.") && note.contains("Showing the first"), "{note}"); assert!(raw_text(b"not a document").unwrap_err().contains("not JSON")); + let deep = format!("{}{}", "[".repeat(200), "]".repeat(200)); + let said = raw_text(deep.as_bytes()).unwrap_err(); + assert!(said.contains("nested too deeply") && !said.contains("not JSON"), "{said}"); } #[test] diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index f33f695927..f8a8d63367 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -64,7 +64,7 @@ cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **De reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, its properties, its assets and its links, up to 200 rows a section with the rest counted; each asset has **Add to map**, **Download** (a link to its web address, offered only for an -http or https address the item may read from and that needs no signing, such as Planetary Computer's does; an asset can still be added or copied without it) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first +http or https address the item may read from and that needs no signing (Planetary Computer's assets need it, so they get no Download link); an asset can still be added or copied without it) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first 200,000 bytes are drawn and Copy takes all of it). When the document can't be shown (the item has no address of its own, the network reach it was found with doesn't allow reading, the read fails, the answer isn't JSON or isn't this item, or it is over 4 MB, or over 16 MB once laid out), the pane shows what RustGIS read of the item instead (the first 100 From 225366b0e9b756cef5a074a6168d2f8373586f2f Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 10:11:17 -0500 Subject: [PATCH 28/33] fix(STAC): signing an asset also waits while a search is being prepared Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/stacui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 5fb26b609a..bd98d2be23 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -863,7 +863,7 @@ fn add_signed(app: &mut RustGisApp, href: &str, name: &str, from: &str, public: } None => { // One request is waited for at a time: signing must not drop a search under way. - if app.ui.stac.waiting.is_some() { + if app.ui.stac.waiting.is_some() || app.ui.stac.preparing.is_some() { app.ui.stac.error = Some(tl!("Wait for the request under way to finish, then add the asset").to_string()); return; } From 714397a3617a24917cb9a555a95fd08f35947a81 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 10:54:32 -0500 Subject: [PATCH 29/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- docs/user-guide/web-data.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index f8a8d63367..91c607ef5d 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -64,7 +64,7 @@ cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **De reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, its properties, its assets and its links, up to 200 rows a section with the rest counted; each asset has **Add to map**, **Download** (a link to its web address, offered only for an -http or https address the item may read from and that needs no signing (Planetary Computer's assets need it, so they get no Download link); an asset can still be added or copied without it) and **Copy link**) and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first +http or https address the item may read from and that needs no signing (Planetary Computer's assets need it, so they get no Download link); an asset can still be added or copied without it) and **Copy link** and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first 200,000 bytes are drawn and Copy takes all of it). When the document can't be shown (the item has no address of its own, the network reach it was found with doesn't allow reading, the read fails, the answer isn't JSON or isn't this item, or it is over 4 MB, or over 16 MB once laid out), the pane shows what RustGIS read of the item instead (the first 100 From 466fc2dd8e7f0c81eb865386b3a2207a38f42941 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 11:46:13 -0500 Subject: [PATCH 30/33] fix(STAC): an item's own address is kept up to 64 KB so a long one is read, and the download note reads right Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 16 +++++++++++++--- docs/user-guide/web-data.md | 2 +- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 4aa7d9d66d..097ab0e9b8 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -697,12 +697,18 @@ pub fn item_from_json(v: &Value, from: Option<&str>) -> Option { /// A link's address by its relation, resolved against `from`. fn link(v: &Value, rel: &str, from: &str) -> Option { + link_up_to(v, rel, from, MAX_TEXT) +} + +/// [`link`] with its own address limit: an item's self link is kept up to [`MAX_DOCUMENT_HREF`], so +/// the inspector can read a document whose address is long. +fn link_up_to(v: &Value, rel: &str, from: &str, limit: usize) -> Option { let l = v.get("links")?.as_array()?.iter().take(100).find(|l| l.get("rel").and_then(Value::as_str) == Some(rel))?; // A POST link needs its body: only a plain GET is followed. if l.get("method").and_then(Value::as_str).is_some_and(|m| !m.eq_ignore_ascii_case("GET")) { return None; } - resolve(from, l.get("href")?.as_str()?) + resolve_up_to(from, l.get("href")?.as_str()?, limit, false) } fn item(f: &Value, from: Option<&str>) -> Option { @@ -719,8 +725,8 @@ pub(crate) fn item_with_reach(f: &Value, from: Option<&str>, reach: Option link(f, "self", from), - None => link(f, "self", "").filter(|u| is_web(u)), + Some(from) => link_up_to(f, "self", from, MAX_DOCUMENT_HREF), + None => link_up_to(f, "self", "", MAX_DOCUMENT_HREF).filter(|u| is_web(u)), }; let base = url.clone().or_else(|| from.map(str::to_string)); let props = f.get("properties"); @@ -1710,6 +1716,10 @@ mod tests { let i = item_from_json(&f("item.json", "https://data.example.org/x.tif"), None).unwrap(); assert!(i.asset_href(None).is_ok()); assert!(item_from_json(&f("item.json", "x.tif"), None).unwrap().assets.is_empty()); + // A self address past the 2,000-byte text limit is still the item's address (up to 64 KB). + let long = format!("https://stac.example.org/items/{}", "a".repeat(3000)); + let i = item_from_json(&f(&long, "https://data.example.org/x.tif"), None).unwrap(); + assert_eq!(i.url.as_deref(), Some(long.as_str())); // Dates: each side a date, a date and time, or open. for good in ["2024-06-01", "2024-06-01/2024-06-30", "2024-06-01/..", "../2024-06-30", "2024-06-01T10:00:00Z/.."] { assert!(datetime(good).is_ok(), "{good}"); diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index 91c607ef5d..b387784673 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -64,7 +64,7 @@ cloud cover line, and **Zoom** (to the item), the asset to add, **Add** and **De reads the item's own document from its address and shows it in two tabs: **Formatted** (what it is, its properties, its assets and its links, up to 200 rows a section with the rest counted; each asset has **Add to map**, **Download** (a link to its web address, offered only for an -http or https address the item may read from and that needs no signing (Planetary Computer's assets need it, so they get no Download link); an asset can still be added or copied without it) and **Copy link** and **JSON** (the document, pretty-printed with its keys sorted (a repeated key keeps its last value), with **Copy JSON**; the first +http or https address the item may read from and that needs no signing; Planetary Computer's assets need signing, so they get no link, but an asset can still be added or copied without one) and **Copy link**, and **JSON** (the document, pretty-printed with its keys sorted, a repeated key keeping its last value, with **Copy JSON**; the first 200,000 bytes are drawn and Copy takes all of it). When the document can't be shown (the item has no address of its own, the network reach it was found with doesn't allow reading, the read fails, the answer isn't JSON or isn't this item, or it is over 4 MB, or over 16 MB once laid out), the pane shows what RustGIS read of the item instead (the first 100 From 2c0a1da81e9d4f93b00b325caa886be97a6b712d Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 12:03:01 -0500 Subject: [PATCH 31/33] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- crates/tiles/src/stac.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index 097ab0e9b8..e1b2cbd7e0 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -935,10 +935,10 @@ fn has_scheme(s: &str) -> bool { /// letters, digits, `+`, `-` or `.`, then a colon. A single letter (`c:/a.tif`) is a drive, not a /// scheme, which matches what `check_asset_scheme` names. fn has_uri_scheme(href: &str) -> bool { - href.split_once(':').is_some_and(|(s, _)| { - s.len() > 1 - && s.starts_with(|c: char| c.is_ascii_alphabetic()) + href.split_once(':').is_some_and(|(s, rest)| { + s.starts_with(|c: char| c.is_ascii_alphabetic()) && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + && (s.len() > 1 || !rest.starts_with(['/', '\\'])) }) } From b659f4a1e84cfa89ae496449319c13154e615e1f Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 13:08:30 -0500 Subject: [PATCH 32/33] fix(STAC): an item's long own address is not kept per item and the pane says it is too long; one-letter schemes read right Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 16 ++++++++++++---- crates/ui-egui/src/stacui.rs | 20 +++++++++++++++++--- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index e1b2cbd7e0..f24b67b85d 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -273,6 +273,8 @@ pub struct Item { pub assets: Vec, /// Its own address (its `self` link), which relative asset addresses are resolved against. pub url: Option, + /// It has a `self` link, but one longer than [`MAX_TEXT`], which is not kept (so `url` is `None`). + pub url_too_long: bool, /// The address it was fetched from, which its asset addresses are judged by (never its own /// `self` link, which it could point anywhere); `None` for an item given whole, whose assets /// may then only be public web addresses. @@ -724,10 +726,13 @@ pub(crate) fn item_with_reach(f: &Value, from: Option<&str>, reach: Option link_up_to(f, "self", from, MAX_DOCUMENT_HREF), None => link_up_to(f, "self", "", MAX_DOCUMENT_HREF).filter(|u| is_web(u)), }; + // Kept on every item of a search, so only up to the text limit; a longer one is said to be so. + let url_too_long = own.as_ref().is_some_and(|u| u.len() > MAX_TEXT); + let url = own.filter(|u| u.len() <= MAX_TEXT); let base = url.clone().or_else(|| from.map(str::to_string)); let props = f.get("properties"); let bbox = f.get("bbox").and_then(Value::as_array).and_then(|b| { @@ -832,6 +837,7 @@ pub(crate) fn item_with_reach(f: &Value, from: Option<&str>, reach: Option 1 || !rest.starts_with(['/', '\\'])) .map(|(s, _)| s) - .filter(|s| s.len() > 1 && s.starts_with(|c: char| c.is_ascii_alphabetic())) + .filter(|s| s.starts_with(|c: char| c.is_ascii_alphabetic())) .filter(|s| s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))); let slashes = lower.split_once(':').is_some_and(|(_, rest)| rest.starts_with("//")); let what = match (scheme, slashes) { @@ -1716,10 +1723,11 @@ mod tests { let i = item_from_json(&f("item.json", "https://data.example.org/x.tif"), None).unwrap(); assert!(i.asset_href(None).is_ok()); assert!(item_from_json(&f("item.json", "x.tif"), None).unwrap().assets.is_empty()); - // A self address past the 2,000-byte text limit is still the item's address (up to 64 KB). + // A self address past the 2,000-byte text limit is not kept, and the item says so. let long = format!("https://stac.example.org/items/{}", "a".repeat(3000)); let i = item_from_json(&f(&long, "https://data.example.org/x.tif"), None).unwrap(); - assert_eq!(i.url.as_deref(), Some(long.as_str())); + assert!(i.url.is_none() && i.url_too_long); + assert!(!item_from_json(&f("item.json", "https://data.example.org/x.tif"), None).unwrap().url_too_long); // Dates: each side a date, a date and time, or open. for good in ["2024-06-01", "2024-06-01/2024-06-30", "2024-06-01/..", "../2024-06-30", "2024-06-01T10:00:00Z/.."] { assert!(datetime(good).is_ok(), "{good}"); diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index bd98d2be23..85f027ddcf 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2526,9 +2526,15 @@ fn start_json(app: &mut RustGisApp, i: usize) { Raw::Shown { text, drawn, note, doc, source: None } }; let Some(url) = item.url.clone() else { - let why = tl!( - "This item has no address of its own to read, so this is what RustGIS read of it: the first 100 plain properties, long text cut." - ); + let why = if item.url_too_long { + tl!( + "This item's own address is too long to read (over 2,000 characters), so this is what RustGIS read of it: the first 100 plain properties, long text cut." + ) + } else { + tl!( + "This item has no address of its own to read, so this is what RustGIS read of it: the first 100 plain properties, long text cut." + ) + }; app.ui.stac.json = Some(JsonView { item: i, text_tab: false, raw: trimmed(why.to_string()) }); return; }; @@ -4112,6 +4118,14 @@ mod tests { assert!(text.contains("scene-1")); assert!(note.as_deref().unwrap_or("").contains("no address of its own"), "{note:?}"); assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 0); + // An address too long to keep is said to be too long, not missing. + app.ui.stac.items[0].url_too_long = true; + start_json(&mut app, 0); + let Some(JsonView { raw: Raw::Shown { note, .. }, .. }) = &app.ui.stac.json else { panic!("shown at once") }; + assert!( + note.as_deref().unwrap_or("").contains("too long to read") && !note.as_deref().unwrap_or("").contains("no address"), + "{note:?}" + ); } #[test] From 6d1a7b178a8a3f84737790b035a5a54a0b5e04d3 Mon Sep 17 00:00:00 2001 From: Ian Horn Date: Sun, 29 Nov 2026 15:23:53 -0500 Subject: [PATCH 33/33] fix(STAC): an own address over any limit is said to be too long, and a login-bound asset address is judged and copied as the address itself Co-Authored-By: Claude Sonnet 5.5 --- crates/tiles/src/stac.rs | 41 ++++++++++++++++++++---------------- crates/ui-egui/src/stacui.rs | 5 ++++- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index f24b67b85d..a1363eb511 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -697,20 +697,24 @@ pub fn item_from_json(v: &Value, from: Option<&str>) -> Option { item(v, from) } -/// A link's address by its relation, resolved against `from`. -fn link(v: &Value, rel: &str, from: &str) -> Option { - link_up_to(v, rel, from, MAX_TEXT) -} - -/// [`link`] with its own address limit: an item's self link is kept up to [`MAX_DOCUMENT_HREF`], so -/// the inspector can read a document whose address is long. -fn link_up_to(v: &Value, rel: &str, from: &str, limit: usize) -> Option { +/// A link by its relation: its plain GET entry, if it has one. +fn link_entry<'a>(v: &'a Value, rel: &str) -> Option<&'a Value> { let l = v.get("links")?.as_array()?.iter().take(100).find(|l| l.get("rel").and_then(Value::as_str) == Some(rel))?; // A POST link needs its body: only a plain GET is followed. if l.get("method").and_then(Value::as_str).is_some_and(|m| !m.eq_ignore_ascii_case("GET")) { return None; } - resolve_up_to(from, l.get("href")?.as_str()?, limit, false) + Some(l) +} + +/// A link's address by its relation, resolved against `from`. +fn link(v: &Value, rel: &str, from: &str) -> Option { + resolve(from, link_entry(v, rel)?.get("href")?.as_str()?) +} + +/// Whether a link has an address longer than the text limit, which [`link`] refuses. +fn link_too_long(v: &Value, rel: &str) -> bool { + link_entry(v, rel).and_then(|l| l.get("href")?.as_str()).is_some_and(|h| h.trim().len() > MAX_TEXT) } fn item(f: &Value, from: Option<&str>) -> Option { @@ -726,13 +730,12 @@ pub(crate) fn item_with_reach(f: &Value, from: Option<&str>, reach: Option link_up_to(f, "self", from, MAX_DOCUMENT_HREF), - None => link_up_to(f, "self", "", MAX_DOCUMENT_HREF).filter(|u| is_web(u)), + let url = match from { + Some(from) => link(f, "self", from), + None => link(f, "self", "").filter(|u| is_web(u)), }; - // Kept on every item of a search, so only up to the text limit; a longer one is said to be so. - let url_too_long = own.as_ref().is_some_and(|u| u.len() > MAX_TEXT); - let url = own.filter(|u| u.len() <= MAX_TEXT); + // Kept on every item of a search only up to the text limit; a longer one is said to be so. + let url_too_long = url.is_none() && link_too_long(f, "self"); let base = url.clone().or_else(|| from.map(str::to_string)); let props = f.get("properties"); let bbox = f.get("bbox").and_then(Value::as_array).and_then(|b| { @@ -1724,9 +1727,11 @@ mod tests { assert!(i.asset_href(None).is_ok()); assert!(item_from_json(&f("item.json", "x.tif"), None).unwrap().assets.is_empty()); // A self address past the 2,000-byte text limit is not kept, and the item says so. - let long = format!("https://stac.example.org/items/{}", "a".repeat(3000)); - let i = item_from_json(&f(&long, "https://data.example.org/x.tif"), None).unwrap(); - assert!(i.url.is_none() && i.url_too_long); + for n in [3000, 100_000] { + let long = format!("https://stac.example.org/items/{}", "a".repeat(n)); + let i = item_from_json(&f(&long, "https://data.example.org/x.tif"), None).unwrap(); + assert!(i.url.is_none() && i.url_too_long, "{n}"); + } assert!(!item_from_json(&f("item.json", "https://data.example.org/x.tif"), None).unwrap().url_too_long); // Dates: each side a date, a date and time, or open. for good in ["2024-06-01", "2024-06-01/2024-06-30", "2024-06-01/..", "../2024-06-30", "2024-06-01T10:00:00Z/.."] { diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 85f027ddcf..8bca33a3ca 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -2758,6 +2758,8 @@ fn formatted( let web = href .clone() .filter(|h| document_asset_allowed(item, key, h, source).is_ok()) + // Judged, and linked, by the address itself: a login binding wraps it. + .map(|h| rustgis_engine::data::login_address::inner(&h).to_string()) .filter(|h| address::is_https(h) || h.get(..7).is_some_and(|s| s.eq_ignore_ascii_case("http://"))) .filter(|h| !stac::needs_signing(h)); ui.push_id(("stac_asset", id, key), |ui| { @@ -2795,7 +2797,8 @@ fn formatted( if let Some(h) = &href && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(cut.as_deref().unwrap_or_default()).clicked() { - ui.ctx().copy_text(h.clone()); + // A login binding is not part of the address. + ui.ctx().copy_text(rustgis_engine::data::login_address::inner(h).to_string()); } }); });