Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1433,7 +1433,8 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec<Coord>], tr: Option<&Transformer
}

/// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the
/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer.
/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. It doesn't
/// look at Cancel: a caller looping over features does, between them.
pub fn validated_polygon_parts(polys: &[Vec<Vec<Coord>>]) -> Result<Vec<Vec<Vec<Coord>>>, PolygonTransformError> {
transform_feature_polygons_to_lonlat(polys, None)
}
Expand Down
17 changes: 14 additions & 3 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1173,15 +1173,25 @@ pub fn replace_atomic_with<T, E: From<std::io::Error>>(
/// [`StagedWrite::commit`] installs them. Dropping the result discards the staged file.
pub fn stage_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<StagedWrite> {
use std::io::Write;
stage_at(link_target(path)?, |w| w.write_all(bytes)).map(|(staged, ())| staged)
stage_at(link_target(path)?, 8 << 10, |w| w.write_all(bytes)).map(|(staged, ())| staged)
}

/// [`stage_atomic`] for a write that streams: `write` fills the file beside the destination (a
/// symbolic link's target), which [`StagedWrite::commit`] installs; dropping the result discards it.
pub fn stage_streamed<T, E: From<std::io::Error>>(
path: &Path,
write: impl FnOnce(&mut std::io::BufWriter<std::fs::File>) -> std::result::Result<T, E>,
) -> std::result::Result<(StagedWrite, T), E> {
// A streamed write (a raster's tiles) goes through a buffer of a megabyte.
stage_at(link_target(path)?, 1 << 20, write)
}

/// Stages and installs a write, retaining the old file on error or cancellation.
fn atomic_write_at<T, E: From<std::io::Error>>(
path: std::path::PathBuf,
write: impl FnOnce(&mut std::io::BufWriter<std::fs::File>) -> std::result::Result<T, E>,
) -> std::result::Result<T, E> {
let (staged, value) = stage_at(path, write)?;
let (staged, value) = stage_at(path, 8 << 10, write)?;
staged.commit()?;
Ok(value)
}
Expand All @@ -1190,6 +1200,7 @@ fn atomic_write_at<T, E: From<std::io::Error>>(
/// and a directory sync.
fn stage_at<T, E: From<std::io::Error>>(
path: std::path::PathBuf,
buffer: usize,
write: impl FnOnce(&mut std::io::BufWriter<std::fs::File>) -> std::result::Result<T, E>,
) -> std::result::Result<(StagedWrite, T), E> {
use std::io::Write;
Expand All @@ -1215,7 +1226,7 @@ fn stage_at<T, E: From<std::io::Error>>(
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let mut out = std::io::BufWriter::new(file);
let mut out = std::io::BufWriter::with_capacity(buffer, file);
let value = write(&mut out)?;
out.flush()?;
out.get_ref().sync_all()?;
Expand Down
10 changes: 10 additions & 0 deletions crates/data/src/raster/cogwrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,16 @@ pub fn write_file(r: &Raster, band: usize, path: &Path) -> Result<CogInfo> {
res
}

/// [`write_file`]'s file, written and synced beside `path` but not yet in its place: the caller
/// installs it ([`crate::io::StagedWrite::commit`]) once nothing can cancel the result any more,
/// and dropping it leaves `path` as it was.
pub fn write_staged(r: &Raster, band: usize, path: &Path) -> Result<(CogInfo, crate::io::StagedWrite)> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write_staged follows a symbolic link and keeps the file's mode (stage_streamed → stage_at). The synchronous path for the same command still goes through write_file (via write_geotiff_with_guidance), which renames a new file over the link and gives it a default mode. So raster.rasterize with a path now writes different results depending on whether it ran on the app's thread or from the CLI, Assistant or Python:

  • a symlinked destination is written through in the background, but replaced by a regular file in the sync path;
  • a private file (0600) keeps its mode in the background, but gets the default mode in the sync path.

The PR says write_file is unchanged for its other callers, which is true, but the two paths for one command now disagree. Either route the sync COG write through the same staging and add a symlink test for both paths, or say in the doc comment why they differ.

Confidence: medium-high from reading both functions; I did not run this against a real filesystem.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both paths are the same here. raster.rasterize runs rasterize_work's closure in both: on the app's thread, and synchronously through made_or_ran (CLI, Python, the Assistant, the Script pane). That closure always writes through write_cog_staged, and add_made commits it in both cases. So every caller of the command gets the staged write, which follows a symbolic link and keeps the file's mode. write_file is still used by the other commands (Export Raster, Project Raster's path via add_output), unchanged.

let (staged, info) = crate::io::stage_streamed(path, |w| write_to(r, band, Flavour::Auto, w))?;
// The last look while it is written: a Cancel that came meanwhile leaves `path` as it was.
crate::progress::check()?;
Ok((info, staged))
}

#[cfg(test)]
mod tests {
use std::io::Cursor;
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ raster.measurements clear?
raster.mosaic inputs name? path?
raster.process layer operation extent? polygon? selectedOnly? factor? name? ran?
raster.project layer crs? cellSize? origin? extent? grid? resampling? name? path?
raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path?
raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path? ran?
raster.resampling layer? type
raster.rotation layer? angle
raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? resampling? reset?
Expand Down
708 changes: 494 additions & 214 deletions crates/engine/src/cmd/imagery.rs

Large diffs are not rendered by default.

31 changes: 30 additions & 1 deletion crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,13 @@ pub(super) fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Res
}

/// Builds the band instruction before combining the note with any caller-supplied path or name.
fn write_geotiff_with_guidance(r: &Raster, bi: usize, cog: bool, path: &str, band_hint: &str) -> Result<super::exports::Wrote, String> {
pub(super) fn write_geotiff_with_guidance(
r: &Raster,
bi: usize,
cog: bool,
path: &str,
band_hint: &str,
) -> Result<super::exports::Wrote, String> {
let cog = if cog {
// Tiles go to the file as they are made: the whole file is never held in memory.
Some(raster::cogwrite::write_file(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?)
Expand All @@ -1176,6 +1182,29 @@ fn write_geotiff_with_guidance(r: &Raster, bi: usize, cog: bool, path: &str, ban
rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?;
None
};
wrote_geotiff(r, bi, path, cog, band_hint)
}

/// [`write_geotiff_with_guidance`]'s Cloud Optimized GeoTIFF, written beside `path` and put in
/// its place when the returned file is committed (as a background run's raster is added).
pub(super) fn write_cog_staged(
r: &Raster,
bi: usize,
path: &str,
band_hint: &str,
) -> Result<(super::exports::Wrote, rustgis_data::io::StagedWrite), String> {
let (cog, staged) = raster::cogwrite::write_staged(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?;
Ok((wrote_geotiff(r, bi, path, Some(cog), band_hint)?, staged))
}

/// What writing `r`'s band `bi` to `path` says.
fn wrote_geotiff(
r: &Raster,
bi: usize,
path: &str,
cog: Option<raster::cogwrite::CogInfo>,
band_hint: &str,
) -> Result<super::exports::Wrote, String> {
let note = geotiff_note(r, bi, cog.is_some(), band_hint)?;
let mut v = match r.overview {
Some((fw, fh)) => json!({"path": path, "width": r.width, "height": r.height, "overviewOf": [fw, fh]}),
Expand Down
21 changes: 19 additions & 2 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ pub struct Made {
/// Made on another thread: the command's name and the map it was started on.
ran: Option<(&'static str, u64)>,
pub(crate) continuation: Option<crate::policy::Continuation>,
/// The file the work wrote, put in its place as the raster is added: a run cancelled or
/// abandoned before then leaves the file there as it was.
staged: Option<(rustgis_data::io::StagedWrite, Vec<String>)>,
}

impl Made {
/// With `file` to commit as it is added; `said`, what the run had to say, goes with the
/// error when it can't be (its `then` doesn't run).
pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite, said: Vec<String>) -> Made {
self.staged = Some((file, said));
self
}
}

/// A workflow's work once its inputs are read: it reads nothing more of the session, so it runs on
Expand Down Expand Up @@ -170,13 +182,17 @@ pub(crate) fn made_then(raster: Raster, extra: Option<Value>, then: Option<Then>

/// A layer made (styled, say), to be added as `name`.
pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: Option<Value>, then: Option<Then>) -> Made {
Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new() }
Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new(), staged: None }
}

/// Adds a made raster as a layer: the command's answer is the layer's (its id, size and bands) and
/// what the command says besides (`extra`), and what it does then.
pub(crate) fn add_made(s: &mut Session, m: Made) -> CmdResult {
let Made { name, layer, extra, then, inputs, .. } = m;
let Made { name, layer, extra, then, inputs, staged, .. } = m;
if let Some((file, said)) = staged {
let path = file.destination().display().to_string();
file.commit().map_err(|e| if said.is_empty() { format!("{path}: {e}") } else { format!("{path}: {e} ({})", said.join("; ")) })?;
}
rustgis_data::provenance::record(inputs);
let mut v = super::raster::add_raster(s, &name, layer)?;
if let (Some(Value::Object(more)), Some(o)) = (extra, v.as_object_mut()) {
Expand Down Expand Up @@ -237,6 +253,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[
("stac.addBands", "Add STAC Bands", super::stac_bands::bands_work),
("stac.addIndex", "Add STAC Index", super::stac_bands::index_work),
("raster.process", "Process", super::imagery::process_work),
("raster.rasterize", "Polygons to Raster", super::imagery::rasterize_work),
("imagery.mosaic", "Build Mosaic", super::imagery::mosaic_work),
("dl.classify", "Deep Learning", super::deeplearning::classify_work),
("embeddings.similarity", "Satellite Embedding Similarity", super::embeddings::similarity_work),
Expand Down
89 changes: 88 additions & 1 deletion crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28768,6 +28768,45 @@ fn raster_export_paths_report_band_class_and_credit_changes() {
std::fs::remove_dir_all(dir).unwrap();
}

/// Given both an extent and a cellSize, Project Raster takes the grid as given: a source whose
/// footprint can't be placed whole in the output's system (the whole world in the south polar
/// stereographic one, which can't hold the North Pole) is projected onto it, where without them it
/// is refused for want of a footprint.
#[test]
fn raster_project_takes_a_given_grid_without_the_sources_footprint() {
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster};
use rustgis_data::{Coord, Dataset, Geometry, GeometryType};
let mut s = Session::new(Project::default());
let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 };
let r = Raster::new("World", 36, 18, vec![vec![1.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap();
let bytes = rustgis_data::raster::geotiff::write(&r, 0).unwrap();
crate::cmd::raster::add_raster(&mut s, "World", rustgis_map::RasterLayer::from_bytes(r, "World.tif".to_string(), bytes)).unwrap();
let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031})).unwrap_err();
assert!(e.contains("can't be placed in"), "{e}");
let v = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": [-180, -90, 180, -60], "cellSize": 500_000})).unwrap();
assert!(v["width"].as_u64().is_some_and(|w| w > 0), "{v}");
// An extent layer read in place (only the part in view) is refused, as for Polygons to Raster.
let mut part = Dataset::new("part", GeometryType::Polygon, vec![]);
part.push(
Some(Geometry::Polygon(vec![vec![vec![
Coord::new(0.0, -80.0),
Coord::new(10.0, -80.0),
Coord::new(10.0, -70.0),
Coord::new(0.0, -80.0),
]]])),
vec![],
);
part.windowed = true;
crate::cmd::layer::add_dataset(&mut s, part);
let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": "part", "cellSize": 500_000})).unwrap_err();
assert!(e.contains("part: load all its features first"), "{e}");
// The whole world reaches every cell of the grid, as projected: each takes its value.
let id = v["layer"].as_u64().unwrap() as u32;
let out = s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).unwrap();
assert_eq!(out.crs, rustgis_data::raster::Crs::from_epsg(3031).unwrap());
assert!(out.bands[0].data.iter().all(|c| *c == 1.0), "{:?}", &out.bands[0].data[..8]);
}

/// Class labels describe source values; interpolating or averaging those values drops the labels
/// with a notice, while nearest, mode and palette-safe sampling retain them.
#[test]
Expand Down Expand Up @@ -51068,6 +51107,32 @@ fn polygons_burned_onto_a_chosen_grid() {
assert!(e.contains("cellSize is required"), "{e}");
let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err();
assert!(e.contains("no-data value"), "{e}");
// An extent layer read in place holds only the part in view: refused before the run.
let mut part = Dataset::new("part", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]);
part.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 0.0, 1.0, 1.0)]])), vec![V::Text("x".into())]);
part.windowed = true;
crate::cmd::layer::add_dataset(&mut s, part);
let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "part"})).unwrap_err();
assert!(e.contains("part: load all its features first"), "{e}");
let layers = layers + 1;
// An extent layer with no features: refused (as the run sizes its grid), nothing added.
crate::cmd::layer::add_dataset(&mut s, Dataset::new("nothing", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]));
let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "nothing"})).unwrap_err();
assert!(e.contains("nothing has no features to take an extent from"), "{e}");
let layers = layers + 1;
assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run");
// A GeoTIFF that can't be put in its place (a folder holds its name): refused, with what the
// run had to say, and nothing added.
let dir = std::env::temp_dir().join(format!("rustgis-rasterize-commit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let taken = dir.join("soils.tif");
std::fs::create_dir_all(taken.join("inside")).unwrap();
let e =
s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "path": taken.to_string_lossy()})).unwrap_err();
assert!(e.contains("soils.tif") && e.contains("features skipped: 1 with no value"), "{e}");
assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run");
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "the staged file is removed");
std::fs::remove_dir_all(dir).unwrap();
}

/// A whole number past what a pixel holds is refused with advice that applies: a numeric field can
Expand Down Expand Up @@ -51239,6 +51304,8 @@ fn raster_tools_run_on_another_thread() {
("raster.process", json!({"layer": dem, "operation": "clip", "extent": [10.005, 45.005, 10.02, 45.02]})),
("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})),
("imagery.mosaic", json!({"name": "Valley"})),
("raster.rasterize", json!({"layer": "Training", "value": 3, "cellSize": 0.0005})),
("raster.rasterize", json!({"layer": "Training", "field": "name", "cellSize": 0.0005})),
] {
assert!(runs_in_background(command).is_some(), "{command}");
let here = s.run(command, &p).unwrap();
Expand All @@ -51250,10 +51317,30 @@ fn raster_tools_run_on_another_thread() {
with["ran"] = json!(id);
let there = s.run(command, &with).unwrap();
assert_eq!(pixels(&s, &here), pixels(&s, &there), "{command} {p}");
// The layer, and the names that follow its own (the first run's layer holds the one asked
// for): a class table named after it is there.
let named = ["layer", "name", "classTable"];
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let besides = |v: &Value| {
v.as_object().map(|o| o.iter().filter(|(k, _)| *k != "layer").map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>())
v.as_object()
.map(|o| o.iter().filter(|(k, _)| !named.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>())
};
assert_eq!(besides(&here), besides(&there), "{command} {p}");
// Each run gives the layer's id, and says the names as text, or neither: only their
// values differ.
assert!(here["layer"].is_u64() && there["layer"].is_u64(), "{command}: {here} {there}");
for key in ["name", "classTable"] {
let said = |v: &Value| v.get(key).map(|n| n.as_str().map(|_| ()).ok_or(()));
assert_eq!(said(&here), said(&there), "{command} {key}: {here} {there}");
assert_ne!(said(&here), Some(Err(())), "{command} {key} is not text: {here}");
}
// A name said is the one the layer got.
if let Some(name) = there["name"].as_str() {
let id = there["layer"].as_u64().unwrap() as u32;
assert_eq!(Some(name), s.map().layer(id).map(|l| l.name.as_str()), "{command}: {there}");
}
if let Some(table) = there["classTable"].as_str() {
assert!(s.project.tables.iter().any(|t| t.name == table), "{command}: {table}");
}
// The answer is the added layer's, whatever else the command says.
assert!(there["width"].is_u64() && there["bands"].is_u64(), "{command}: {there}");
let run = raster_start(&mut s, command, &p).unwrap();
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests/cancellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub(super) fn long_commands(boundaries: bool) {
("raster.index", json!({"layer": dem, "index": "ndvi", "nir": 1, "red": 1})),
("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})),
("imagery.mosaic", json!({"name": "Valley"})),
("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005, "path": out("burned.tif")})),
(
"dl.classify",
json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}),
Expand Down
Loading
Loading