diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index ac2c7b3987..97fd4b5eb7 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -32,7 +32,7 @@ pub struct GpkgSource { rtree: Option, reproject: Reproject, /// A copy written for a file opened from memory, removed when the source is dropped. - temp: Option, + temp: Option, /// The database file and its identity when opened ([`file_identity`]), for a traversal on a /// connection of its own to check it reads the same file. file: Option<(PathBuf, Option<(u64, u64)>)>, @@ -44,9 +44,6 @@ impl Drop for GpkgSource { if let Ok(c) = self.conn.get_mut() { drop(c.take()); } - if let Some(p) = &self.temp { - let _ = std::fs::remove_file(p); - } } } @@ -58,7 +55,11 @@ pub fn layers(path: &Path) -> Result> { /// Unsupported contents omitted when the GeoPackage is added as feature layers, by type. pub fn unsupported_table_counts(path: &Path) -> Result> { - let conn = open_db(path)?; + unsupported_counts(&open_db(path)?) +} + +/// Counts on the same connection used to open an uploaded feature table. +fn unsupported_counts(conn: &Connection) -> Result> { let invalid: i64 = conn .query_row("SELECT count(*) FROM gpkg_contents WHERE typeof(table_name) <> 'text' OR typeof(data_type) <> 'text'", [], |row| { row.get(0) @@ -69,7 +70,7 @@ pub fn unsupported_table_counts(path: &Path) -> Result> { "GeoPackage: {invalid} invalid gpkg_contents entry/entries: table_name and data_type must be text" ))); } - let registered_filter = if has_geometry_columns(&conn)? { + let registered_filter = if has_geometry_columns(conn)? { "WHERE lower(table_name) NOT IN (SELECT lower(table_name) FROM gpkg_geometry_columns WHERE table_name IS NOT NULL)" } else { "" @@ -89,11 +90,39 @@ pub fn unsupported_table_counts(path: &Path) -> Result> { /// Count a desktop upload with SQLite, matching the reader used to open its feature table. pub fn unsupported_table_counts_bytes(bytes: &[u8]) -> Result> { - use std::io::Write; - let mut copy = tempfile::NamedTempFile::new()?; - copy.write_all(bytes)?; - copy.flush()?; - crate::provenance::without(|| unsupported_table_counts(copy.path())) + GpkgUpload::new(bytes)?.unsupported_table_counts() +} + +/// One private desktop copy and connection, shared by upload inspection and opening. +/// The connection closes before the temporary file is removed, including on Windows. +pub struct GpkgUpload { + conn: Connection, + copy: tempfile::NamedTempFile, +} + +impl GpkgUpload { + /// Writes the upload once; inspection and the eventual source use this same database. + pub fn new(bytes: &[u8]) -> Result { + use std::io::Write; + let mut copy = tempfile::Builder::new().prefix("rustgis-").suffix(".gpkg").tempfile()?; + copy.write_all(bytes)?; + copy.flush()?; + let conn = crate::provenance::without(|| open_db(copy.path()))?; + Ok(Self { conn, copy }) + } + + pub fn unsupported_table_counts(&self) -> Result> { + unsupported_counts(&self.conn) + } + + /// Transfers the connection and its private copy to the selected feature source. + pub fn open(self, layer: Option<&str>) -> Result { + let Self { conn, copy } = self; + let path = copy.path().to_path_buf(); + let mut source = GpkgSource::open_conn(conn, &path, layer, file_identity(&path))?; + source.temp = Some(copy); + Ok(source) + } } fn open_db(path: &Path) -> Result { @@ -142,55 +171,22 @@ impl GpkgSource { // if the working directory changes in between. let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); let id = file_identity(&path); - Self::open_conn(open_db(&path)?, &path, layer, None, id) + Self::open_conn(open_db(&path)?, &path, layer, id) } /// Opens a GeoPackage held in memory, through a temporary copy (SQLite reads files). The copy /// is a new file with a name no one can guess, so another user can't plant one in its place. pub fn open_bytes(bytes: &[u8], layer: Option<&str>) -> Result { - use std::io::Write; - use std::sync::atomic::{AtomicU64, Ordering}; - static N: AtomicU64 = AtomicU64::new(0); - let mut tries = 0; - let (p, mut f) = loop { - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); - let salt = std::collections::hash_map::RandomState::new(); - let tag = std::hash::BuildHasher::hash_one(&salt, (nanos, N.fetch_add(1, Ordering::Relaxed))); - let p = std::path::absolute(std::env::temp_dir()) - .unwrap_or_else(|_| std::env::temp_dir()) - .join(format!("rustgis-{}-{tag:016x}.gpkg", std::process::id())); - let mut o = std::fs::OpenOptions::new(); - o.write(true).create_new(true); - // Readable by this user only: the copy holds their data, in a shared folder. - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); - match o.open(&p) { - Ok(f) => break (p, f), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && tries < 8 => tries += 1, - Err(e) => return Err(e.into()), - } - }; - if let Err(e) = f.write_all(bytes).and_then(|_| f.sync_all()) { - let _ = std::fs::remove_file(&p); - return Err(e.into()); - } - drop(f); - let id = file_identity(&p); - match crate::provenance::without(|| open_db(&p)).and_then(|c| Self::open_conn(c, &p, layer, Some(p.clone()), id)) { - Ok(s) => Ok(s), - Err(e) => { - let _ = std::fs::remove_file(&p); - Err(e) - } - } + GpkgUpload::new(bytes)?.open(layer) } /// Opens a feature table (`layer`, else the first) on an open database from its metadata, /// noting what reading changes: an unknown coordinate system, other tables, Z or M values - /// dropped. `id` is the file's identity taken before it was opened. + /// dropped. `id` identifies the file for later traversals. On-disk sources capture it before + /// opening; an upload identifies its private copy. /// `path` is the file as the caller named it, made absolute. SQLite's own name for it resolves symbolic links /// (macOS's temporary folder `/var` is `/private/var`), so it isn't the path to record. - fn open_conn(conn: Connection, path: &Path, layer: Option<&str>, temp: Option, id: Option<(u64, u64)>) -> Result { + fn open_conn(conn: Connection, path: &Path, layer: Option<&str>, id: Option<(u64, u64)>) -> Result { let tables = feature_tables(&conn)?; let table = match layer { Some(l) => tables @@ -316,7 +312,7 @@ impl GpkgSource { zm_dropped: false, }; let file = Some((path.to_path_buf(), id)); - let mut src = GpkgSource { info, conn: Mutex::new(Some(conn)), table, geom, pk, rtree, reproject, temp, file }; + let mut src = GpkgSource { info, conn: Mutex::new(Some(conn)), table, geom, pk, rtree, reproject, temp: None, file }; if src.info.geometry_type == GeometryType::None { src.info.geometry_type = src.peek_kind(); } @@ -1321,6 +1317,22 @@ mod tests { use super::source_date_epoch; use std::ffi::OsStr; + /// Inspection, opening and later traversal all retain the one uploaded database. + #[test] + fn upload_reuses_one_copy_and_removes_it_on_drop() { + let dir = tempfile::tempdir().unwrap(); + let original = dir.path().join("input.gpkg"); + super::super::tests::write_gpkg(&original, true); + let upload = super::GpkgUpload::new(&std::fs::read(original).unwrap()).unwrap(); + let path = upload.copy.path().to_path_buf(); + assert!(upload.unsupported_table_counts().unwrap().is_empty()); + let source = upload.open(None).unwrap(); + assert_eq!(source.temp.as_ref().unwrap().path(), path); + assert!(path.is_file()); + drop(source); + assert!(!path.exists()); + } + /// Whole seconds from 1970 to the end of year 9999 pin the time; unset or blank leaves it the /// export's; anything else, text that isn't Unicode included, refuses the export. #[test] diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 9f910b2bed..f554a376bb 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -395,8 +395,9 @@ fn geopackage_provenance_excludes_temporary_copies() { write_gpkg(&path, true); let captured = crate::provenance::Capture::start(); let bytes = crate::provenance::read(&path).unwrap(); - assert!(gpkg::unsupported_table_counts_bytes(&bytes).unwrap().is_empty()); - let source = open_bytes("upload.gpkg", bytes, None).unwrap(); + let upload = gpkg::GpkgUpload::new(&bytes).unwrap(); + assert!(upload.unsupported_table_counts().unwrap().is_empty()); + let source = upload.open(None).unwrap(); assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); assert_eq!(captured.inputs().len(), 1); assert_eq!(captured.inputs()[0].path, path.display().to_string()); @@ -595,7 +596,7 @@ fn write_fgb(path: &Path) { } /// A GeoPackage of the points in Web Mercator, with an R-tree index (or without). -fn write_gpkg(path: &Path, rtree: bool) { +pub(super) fn write_gpkg(path: &Path, rtree: bool) { let _ = std::fs::remove_file(path); let c = rusqlite::Connection::open(path).unwrap(); c.execute_batch( diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index ff4bad23f9..931189cd75 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2067,14 +2067,12 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { if rustgis_data::source::is_source_name(path) { return add_source(s, p, Origin::Path(path), None); } - // A CityJSON model named .json, in the coordinate system given or with a layer picked: as a - // .city.json, all its layers (a .city.json is added below, as a file of several layers). It is - // read whole to tell, here on the calling thread, so only up to the size every computer reads - // (a larger model is named `.city.json` to be read as one). + // Only a possible city model is read whole; ordinary GeoJSON keeps its streaming path. if path.to_ascii_lowercase().ends_with(".json") && !rustgis_data::cityjson::is_cityjson_name(path) && ["crs", "layer"].iter().any(|k| ps(p, k).is_some_and(|c| !c.trim().is_empty())) && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() <= rustgis_data::io::BYTES_FLOOR) + && may_be_city_model_path(path) { let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; if rustgis_data::io::is_cityjson(path, &bytes) { @@ -2604,9 +2602,8 @@ fn in_place_key(path: &str, crs: Option<&str>) -> String { /// The opening of a large Shapefile or GeoJSON file that Add Data reads in place, made ahead on a /// thread of its own (#2446): it reads the whole file once, to index a Shapefile's records or /// find a GeoJSON file's features, which takes minutes for a file of millions. As [`add_data`] -/// decides ([`streams_geojson`], [`streams_shapefile`]), but a `.json` of at most 256 MiB given a -/// coordinate system or a layer, which may be a city model told as it is added, so it is opened -/// there as before. +/// decides ([`streams_geojson`], [`streams_shapefile`]); a possible city model is sniffed from +/// its head and left for the city-model path. /// Cancel is looked at every few thousand features or records; reading a GeoJSON file of at most /// 256 MiB into memory, before its text is scanned, is one step without a look. #[cfg(not(target_arch = "wasm32"))] @@ -2617,11 +2614,11 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { let given = |k: &str| ps(p, k).is_some_and(|v| !v.trim().is_empty()); if is_geojson(path) && !rustgis_data::cityjson::is_cityjson_name(path) - // Up to the size every computer reads, add_data reads such a .json whole first to tell a - // city model; a larger one it opens in place, as here. + // Match add_data's bounded city-model probe before opening GeoJSON in place. && !(lower.ends_with(".json") && (given("crs") || given("layer")) - && std::fs::metadata(path).is_ok_and(|m| m.len() <= rustgis_data::io::BYTES_FLOOR)) + && std::fs::metadata(path).is_ok_and(|m| m.len() <= rustgis_data::io::BYTES_FLOOR) + && may_be_city_model_path(path)) && streams_geojson(p, path) { let (path, may_load) = (path.to_string(), b(p, "stream").is_none()); @@ -2654,8 +2651,8 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { /// Shapefile or GeoJSON file opened in place ([`in_place_ahead`]), or a standalone dBASE table. /// `None` for any other file, which [`add_data`] reads as it adds it. Each is picked only where /// `add_data` takes that read, so a read made is never wasted; a few it makes whole are left to it -/// (a `.json` with a coordinate system or layer given, a large GeoJSON that isn't a -/// FeatureCollection). +/// (a possible CityJSON `.json` with a coordinate system or layer given, or a large GeoJSON +/// that isn't a FeatureCollection). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn add_data_ahead(p: &Value) -> Option { use super::reads::ahead; @@ -2699,11 +2696,11 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { let lower = path.to_ascii_lowercase(); // A GeoJSON read whole: small with no "stream" given (which add_data decides by), or any size // (within the reader's limit) with `"stream": false`; and not a CityJSON model (named so, or a - // .json with a coordinate system or a layer given). + // .json whose head could identify CityJSON, with a coordinate system or a layer given). let geojson = is_geojson(&path) && !rustgis_data::cityjson::is_cityjson_name(&path) && b(p, "stream") != Some(true) - && !(lower.ends_with(".json") && (given("crs") || given("layer"))) + && !(lower.ends_with(".json") && (given("crs") || given("layer")) && may_be_city_model_path(&path)) && std::fs::metadata(&path) .is_ok_and(|m| m.is_file() && (b(p, "stream") == Some(false) || m.len() <= rustgis_data::source::geojson::IN_PLACE_ABOVE)); // A ZIP, a city model, a GML or a GPX file: its layers, read whole. A model named `.json` (not @@ -3132,11 +3129,11 @@ fn file_layers(s: &mut Session, p: &Value) -> CmdResult { let layers = rustgis_data::dxf::layers(path, &bytes).map_err(err)?; return Ok(json!({"count": layers.len(), "layers": layers})); } - // A CityJSON model named .json: all its layers, as Add Data adds them by name. Read whole to - // tell, so only up to the size every computer reads, as Add Data does. + // Sniff a plain .json before considering a whole-file city-model read. let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()); let model_json = path.to_ascii_lowercase().ends_with(".json") - && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() <= rustgis_data::io::BYTES_FLOOR); + && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() <= rustgis_data::io::BYTES_FLOOR) + && may_be_city_model_path(path); if rustgis_data::io::is_multi_layer_name(path) || model_json { let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; // Listed within the size Add Data takes it at. @@ -3177,6 +3174,54 @@ fn file_layers(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"count": 1, "layers": [name]})) } +/// Reads at most 64 KiB to route a plain .json without allocating the whole file. +/// An inconclusive head keeps the existing whole-file fallback (within its size cap), so a +/// CityJSON root type after a large metadata value or extension member still works. A root type +/// or CityObjects key lets us stop before its payload. A features key alone is inconclusive: +/// CityJSON permits extension members, and its root type may follow them. +fn may_be_city_model_path(path: &str) -> bool { + use std::io::Read; + let mut head = Vec::new(); + match rustgis_data::provenance::open(path).and_then(|f| f.take(64 << 10).read_to_end(&mut head)) { + Ok(_) => json_city_model_head(&head), + Err(_) => true, // The existing reader reports the I/O error. + } +} + +/// Inspects root keys only; nested properties and strings cannot identify a city model. +fn json_city_model_head(head: &[u8]) -> bool { + use serde::Deserializer; + use serde::de::{IgnoredAny, MapAccess, Visitor}; + struct Head<'a>(&'a std::cell::Cell>); + impl<'de> Visitor<'de> for Head<'_> { + type Value = bool; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a JSON document's root object") + } + fn visit_map>(self, mut map: M) -> Result { + while let Some(key) = map.next_key::()? { + match key.as_str() { + "type" => self.0.set(Some(map.next_value::()? == "CityJSON")), + "CityObjects" => self.0.set(Some(true)), + _ => { + map.next_value::()?; + continue; + } + } + // Stop without consuming the payload. serde otherwise requires the closing + // brace after visit_map; the decision deliberately survives this sentinel error. + return Err(serde::de::Error::custom("JSON format decided")); + } + self.0.set(Some(false)); + Ok(false) + } + } + let head = head.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(head); + let decided = std::cell::Cell::new(None); + let _ = serde_json::Deserializer::from_slice(head).deserialize_map(Head(&decided)); + decided.get().unwrap_or(true) +} + /// Whether a file name is GeoJSON's (`.geojson` or `.json`). #[cfg(not(target_arch = "wasm32"))] fn is_geojson(path: &str) -> bool { @@ -3247,6 +3292,14 @@ fn add_source_read( let mut skipped: Vec = Vec::new(); let mut total = None; let selected = ps(p, "layer").map(str::trim).filter(|t| !t.is_empty()); + // A desktop upload is copied once; inspection and opening share its SQLite connection. + #[cfg(not(target_arch = "wasm32"))] + let upload = match &origin { + Origin::Bytes(name, bytes) if name.to_ascii_lowercase().ends_with(".gpkg") && opened.is_none() => { + Some(source::gpkg::GpkgUpload::new(bytes.as_slice()).map_err(err)?) + } + _ => None, + }; // Report unsupported contents for a whole-file add, not a deliberate table selection. let contents = match (&origin, selected.is_none()) { #[cfg(not(target_arch = "wasm32"))] @@ -3254,9 +3307,10 @@ fn add_source_read( source::gpkg::unsupported_table_counts(Path::new(path)).map_err(err)? } #[cfg(not(target_arch = "wasm32"))] - (Origin::Bytes(name, bytes), true) if name.to_ascii_lowercase().ends_with(".gpkg") => { - source::gpkg::unsupported_table_counts_bytes(bytes.as_slice()).map_err(err)? - } + (Origin::Bytes(name, bytes), true) if name.to_ascii_lowercase().ends_with(".gpkg") => match &upload { + Some(upload) => upload.unsupported_table_counts().map_err(err)?, + None => source::gpkg::unsupported_table_counts_bytes(bytes.as_slice()).map_err(err)?, + }, #[cfg(target_arch = "wasm32")] (Origin::Bytes(name, bytes), true) if name.to_ascii_lowercase().ends_with(".gpkg") => { source::gpkg_mem::unsupported_table_counts(source::Shared(bytes.clone())).map_err(err)? @@ -3276,6 +3330,13 @@ fn add_source_read( }) .collect(); let attribute_note = (!omitted.is_empty()).then(|| omitted.join("; ")); + #[cfg(not(target_arch = "wasm32"))] + if let Some(upload) = upload { + opened = Some(Box::new(upload.open(selected).map_err(|e| match &attribute_note { + Some(note) => format!("{}; {note}", err(e)), + None => err(e), + })?)); + } let tables: Vec> = match (selected, &origin) { (Some(t), _) => vec![Some(t.to_string())], (None, Origin::Path(path)) if path.to_ascii_lowercase().ends_with(".gpkg") => { @@ -3287,8 +3348,8 @@ fn add_source_read( all.into_iter().map(Some).collect() } // In the browser an uploaded GeoPackage adds every table, listed by the pure-Rust reader. - // (The desktop opens uploads with SQLite, one temporary copy per table, so it adds the - // first; files on disk add them all.) + // The desktop adds the first feature table from one private SQLite copy shared with + // inspection, reporting other tables through the source notes; files on disk add all. #[cfg(target_arch = "wasm32")] (None, Origin::Bytes(name, bytes)) if name.to_ascii_lowercase().ends_with(".gpkg") => { let mut all = source::gpkg_mem::layers(source::Shared(bytes.clone())).map_err(err)?; @@ -7571,6 +7632,59 @@ mod tests { use crate::Session; use serde_json::json; + /// A payload can start beyond the sniff budget; only root keys decide the route. + #[test] + fn json_head_stops_before_payloads() { + for head in [ + br#"{"type":"FeatureCollection","features":["#.as_slice(), + br#"{"metadata":{"type":"CityJSON","CityObjects":{}},"type":"FeatureCollection""#, + ] { + assert!(!super::json_city_model_head(head)); + } + for head in [ + br#"{"type":"CityJSON","CityObjects":{"#.as_slice(), + br#"{"CityObjects":{"#, + br#"{"features":["#, + br#"{"metadata":{"description":"unfinished"#, + ] { + assert!(super::json_city_model_head(head)); + } + } + + /// A CityJSON extension named features cannot decide the format before its root type. + #[test] + fn json_head_preserves_cityjson_extension_members() { + let text = r#"{"features":[],"type":"CityJSON","CityObjects":{},"version":"2.0","vertices":[]}"#; + assert!(rustgis_data::cityjson::looks_like_cityjson(text)); + assert!(super::json_city_model_head(text.as_bytes())); + let large_extension = format!("{{\"features\":[\"{}", "x".repeat(64 << 10)); + assert!(super::json_city_model_head(large_extension.as_bytes().get(..64 << 10).unwrap())); + } + + /// Listing GeoJSON never reads its full payload merely to rule out a city model. + #[test] + fn listing_json_layers_only_reads_the_head() { + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = Dir(std::env::temp_dir().join(format!("rustgis-json-head-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let path = dir.0.join("points.json"); + let mut bytes = br#"{"type":"FeatureCollection","features":[]}"#.to_vec(); + bytes.resize(128 << 10, b' '); + std::fs::write(&path, bytes).unwrap(); + let capture = rustgis_data::provenance::Capture::start(); + let mut s = crate::Session::new(Default::default()); + let out = s.run("info.fileLayers", &serde_json::json!({"path":path})).unwrap(); + assert_eq!(out["layers"], serde_json::json!(["points"])); + let inputs = capture.inputs(); + assert_eq!(inputs.len(), 1); + assert!(inputs[0].sha256.is_none(), "a whole-file read was captured"); + } + /// Overlays left out for their pictures' size are said, with the budget; none, nothing said. #[test] fn overlays_left_out_for_their_pictures_are_said_and_none_otherwise() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8619de53b1..6dad15ffb7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25688,6 +25688,18 @@ fn geopackage_omission_counts_match_unregistered_tables_with_bounded_kinds() { "{}", notice.text ); + let bytes = std::sync::Arc::new(std::fs::read(&path).unwrap()); + for stream in [false, true] { + for selected in [false, true] { + let mut uploaded = Session::new(Project::default()); + let params = json!({"stream": stream, "layer": selected.then_some("A")}); + crate::cmd::layer::add_source(&mut uploaded, ¶ms, crate::cmd::layer::Origin::Bytes("kinds.gpkg", bytes.clone()), None) + .unwrap(); + assert_eq!(uploaded.map().layers.len(), 1); + let notes: Vec<_> = uploaded.notices.iter().filter(|n| n.text.contains("the first of 2 feature tables")).collect(); + assert_eq!(notes.len(), usize::from(!selected), "stream={stream}, selected={selected}"); + } + } std::fs::remove_dir_all(dir).unwrap(); }