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
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/cube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1191,7 +1191,7 @@ pub fn add_outputs(s: &mut Session, rasters: Vec<Raster>, dates: usize) -> CmdRe
let name = r.name.clone();
let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect();
let layer = rustgis_map::raster::RasterLayer::from_bytes(r, format!("{file}.tif"), tif);
let layer = rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif);
let out = super::raster::add_raster(s, &name, layer)?;
layers.push(out["layer"].clone());
}
Expand Down
12 changes: 7 additions & 5 deletions crates/engine/src/cmd/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,9 +526,10 @@ fn add_zones(s: &mut Session, p: &Value, d: &emb::EmbeddingDataset, name: Option
let year = year(d, p)?;
let b = bands(p, z.bands, tessera::DEFAULT_BANDS)?;
let none = format!("{} has no embeddings there", z.name);
let (r, tif) = match handed(s, p)? {
// Whether `tif` is the file `geotiff::write` wrote of `r`, rather than one handed over.
let (r, tif, written) = match handed(s, p)? {
Some((_, tif)) => match raster::read_bytes(&format!("{}.tif", z.id), &tif) {
Ok(r) if r.bands.iter().any(|band| band.stats.count > 0) => (r, tif),
Ok(r) if r.bands.iter().any(|band| band.stats.count > 0) => (r, tif, false),
Ok(_) => return Err(none),
Err(e) => return Err(e.to_string()),
},
Expand All @@ -550,15 +551,16 @@ fn add_zones(s: &mut Session, p: &Value, d: &emb::EmbeddingDataset, name: Option
s.notify(format!("{}: the view is larger than one read; its centre was read (zoom in for the rest)", z.name), false);
}
let tif = raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?;
(r, tif)
(r, tif, true)
}
}
};
if r.bands.iter().all(|band| band.stats.count == 0) {
return Err(none);
}
let name = name.unwrap_or_else(|| format!("{} {year} ({})", z.name, band_label(b)));
let layer = RasterLayer::from_bytes(r, format!("{}_{year}.tif", z.id), tif);
let file = format!("{}_{year}.tif", z.id);
let layer = if written { RasterLayer::from_written(r, file, tif) } else { RasterLayer::from_bytes(r, file, tif) };
let mut out = super::raster::add_raster(s, &name, layer)?;
if !d.license.is_empty() {
out["license"] = json!(d.license);
Expand Down Expand Up @@ -880,7 +882,7 @@ const IN_THE_BROWSER: &str = "AlphaEarth's similarity and change are worked out
fn made_saying(r: rustgis_data::raster::Raster, notes: Vec<String>, extra: Value) -> Result<super::workflows::Made, String> {
let bytes = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let name = r.name.clone();
let layer = RasterLayer::from_bytes(r, format!("{name}.tif"), bytes);
let layer = RasterLayer::from_written(r, format!("{name}.tif"), bytes);
let said = name.clone();
let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| {
let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok());
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ pub(crate) fn bands_param(p: &Value, r: &Raster) -> Result<Vec<usize>, String> {
fn layer_of(r: Raster) -> Result<rustgis_map::RasterLayer, String> {
let bytes = rustgis_data::raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let fname = format!("{}.tif", r.name);
Ok(rustgis_map::RasterLayer::from_bytes(r, fname, bytes))
Ok(rustgis_map::RasterLayer::from_written(r, fname, bytes))
}

/// Adds a raster layer; classes get unique-value colours.
Expand Down
6 changes: 5 additions & 1 deletion crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6702,7 +6702,11 @@ pub fn read_cog_window_until(asked: &WindowAsked, stop: &std::sync::atomic::Atom
bytes
}
};
let layer = rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes);
let layer = if plain.is_some() {
rustgis_map::RasterLayer::from_written(r, format!("{name}.tif"), bytes)
} else {
rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)
};
let mut notes = vec![read];
notes.extend(plain);
notes.extend(finer);
Expand Down
29 changes: 25 additions & 4 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ fn band(p: &Value, k: &str, r: &Raster) -> Result<Option<usize>, String> {
/// `zoom` is the adding command's `"zoom"`, as for the layers beside it.
pub(crate) fn add_overlay(s: &mut Session, name: &str, r: raster::Raster, zoom: Option<bool>) -> CmdResult {
let tif = raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?;
add_raster_after(s, name, RasterLayer::from_bytes(r, format!("{name}.tif"), tif), zoom)
add_raster_after(s, name, RasterLayer::from_written(r, format!("{name}.tif"), tif), zoom)
}

/// Sets how rasters added from now on are drawn when they hold a single band of continuous values
Expand Down Expand Up @@ -1251,10 +1251,13 @@ fn info(s: &mut Session, p: &Value) -> CmdResult {
/// GeoTIFF bytes of a raster layer (band is 1-based; RGB rasters keep their colour bands; `cog`
/// makes it a cloud-optimised one).
pub fn geotiff_bytes(s: &mut Session, p: &Value) -> Result<(String, Vec<u8>), String> {
let (_, r) = get(s, p)?;
let (id, r) = get(s, p)?;
let bi = band(p, "band", &r)?.unwrap_or(0);
let cog = b(p, "cog") == Some(true);
let bytes = if cog { raster::cogwrite::write(&r, bi) } else { raster::geotiff::write(&r, bi) }.map_err(|e| e.to_string())?;
let bytes = match written_export(s, id, &r, bi, cog) {
Some(bytes) => bytes.to_vec(),

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.

bytes.to_vec() copies the whole embedded file. The browser download (ui.exportRaster → Services::download, which takes an owned Vec<u8>) therefore holds the layer's file and a second file-sized buffer at the same time. The encode it replaces also allocated one file-sized buffer, so this isn't a regression. But the PR's memory note ("no second encoded file the size of the output") holds only for the desktop export, not the browser download. Either say so in the description, or change the download path to take the shared Arc<Vec<u8>> so the copy goes away.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The description now says so: the download copies the file once, as the encode it replaced allocated one. Passing the shared Arc would change the Services::download interface, which is outside this PR.

None => if cog { raster::cogwrite::write(&r, bi) } else { raster::geotiff::write(&r, bi) }.map_err(|e| e.to_string())?,
};
let note = geotiff_note(&r, bi, cog, "give \"band\" for another")?;
if !note.is_empty() {
s.notify(format!("Exported {}.tif{note}", r.name), false);
Expand All @@ -1279,12 +1282,30 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result<super::exports::Work
{
return Err(why.replace("a raster layer", "a raster or tile layer"));
}
let (_, r) = get(s, p)?;
let (id, r) = get(s, p)?;
let bi = band(p, "band", &r)?.unwrap_or(0);
let cog = b(p, "cog") == Some(true);
if let Some(bytes) = written_export(s, id, &r, bi, cog) {
return Ok(Box::new(move || {
// One write of bytes the layer holds, with no look at Cancel inside it: looked at before.
rustgis_data::progress::check().map_err(|e| e.to_string())?;
rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?;
wrote_geotiff(&r, bi, &path, None, "give \"band\" for another")
}));
}
Ok(Box::new(move || write_geotiff(&r, bi, cog, &path)))
}

/// The file layer `id` embeds, when a plain export of `r`'s band `bi` (or its colour bands) would
/// write those same bytes: a raster a command made embeds the GeoTIFF it was written as, and an
/// export of every band writes it again rather than encoding it again.
fn written_export(s: &Session, id: u32, r: &Raster, bi: usize, cog: bool) -> Option<Arc<Vec<u8>>> {
if cog || raster::geotiff::written_bands(r, bi).len() != r.bands.len() {
return None;
}
s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|rl| rl.written_file()).cloned()
}

/// Writes raster `r` (band `bi`, or its colour bands) to `path`, and says what the file holds.
pub(super) fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Result<super::exports::Wrote, String> {
write_geotiff_with_guidance(r, bi, cog, path, "give \"band\" for another")
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/stac_bands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ mod desktop {
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?;
let layer_name = raster.name.clone();
let mut layer = RasterLayer::from_bytes(raster, format!("{layer_name}.tif"), bytes);
let mut layer = RasterLayer::from_written(raster, format!("{layer_name}.tif"), bytes);
// Drawn in colour over the range the index means something in, not grey over this window's own.
let (ramp, min, max) = index_look(id);
layer.style.renderer = RasterRenderer::Stretch { band: 0, ramp, invert: false };
Expand Down Expand Up @@ -674,7 +674,7 @@ mod desktop {
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?;
let name = raster.name.clone();
let mut layer = RasterLayer::from_bytes(raster, format!("{name}.tif"), bytes);
let mut layer = RasterLayer::from_written(raster, format!("{name}.tif"), bytes);
layer.style.renderer = RasterRenderer::Rgb { red: 0, green: 1, blue: 2 };
let then = noted(name.clone(), notes);
Ok(super::super::workflows::made_layer(name, layer, Some(extra), Some(then)))
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ pub(crate) type Then = Box<dyn FnOnce(&mut Session, &mut Value) + Send>;
pub(crate) fn made(raster: Raster, extra: Option<Value>) -> Result<Made, String> {
let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?;
let name = raster.name.clone();
let layer = rustgis_map::RasterLayer::from_bytes(raster, format!("{name}.tif"), bytes);
let layer = rustgis_map::RasterLayer::from_written(raster, format!("{name}.tif"), bytes);

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.

Twins that still take the old path: rasters made with the same geotiff::write_all bytes but wrapped with RasterLayer::from_bytes miss the new export shortcut, so share.exportRaster re-encodes them. These are stac_bands.rs (around line 226, addBands/addIndex), embeddings.rs (made_saying, around line 883) and imagery.rs (layer_of, around line 173). Switching each to from_written keeps the bytes and adds the pairing check. Either extend this PR to them or say in the description why they're left out, since the description scopes the change to workflows::made.

Category: performance

@Mavrick-F Mavrick-F Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in be8f466. The three named sites take from_written, and so do two more that embed write_all's bytes unchanged: stac_bands.rs (index view, around line 677) and cube.rs (add_outputs). I first said the KML overlay, layer.rs and the Zarr sites keep bytes from another writer. That was wrong: they use geotiff::write, and take from_written since 27c3346 and c319c6d. The engine test also drops its copy of the layer before the edit.

Ok(made_layer(name, layer, extra, None))
}

Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/cmd/zarr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
let mut layer = if sel.window.is_some() {
r.source = Some(full.clone());
let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?;
let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&full)), tif);
let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&full)), tif);
layer.path = Some(full);
layer
} else {
Expand Down Expand Up @@ -579,7 +579,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
// The writer refuses systems its keys cannot preserve, as for a directory window or
// a slice handed over by the UI.
let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?;
let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&u)), tif);
let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&u)), tif);
layer.subdataset = Some(sel.label());
// The coordinate system given for a store that doesn't say, kept as a folder's slice
// keeps it, so a time series read from the layer finds it.
Expand Down Expand Up @@ -2025,7 +2025,7 @@ fn reduce(s: &mut Session, p: &Value) -> CmdResult {
let run = reduce_start(s, p)?;
let r = run.run(&std::sync::atomic::AtomicBool::new(false), &std::sync::atomic::AtomicUsize::new(0))?;
let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?;
let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&run.root)), tif);
let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&run.root)), tif);
layer.subdataset = None;
let mut out = super::raster::add_raster(s, &run.name, layer)?;
out["steps"] = serde_json::json!(run.total());
Expand Down
35 changes: 35 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18971,6 +18971,41 @@ fn hillshade_is_made_and_written_as_bytes() {
std::fs::remove_dir_all(&dir).ok();
}

/// A made raster embeds the bytes an encode would write, and its plain export writes the file the
/// layer embeds; once its pixels change, the export encodes them.
#[test]
fn exporting_a_made_raster_writes_its_embedded_file_until_its_pixels_change() {
let mut s = world();
s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap();
let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone();
let v = s.run("raster.function", &json!({"layer": dem, "function": "hillshade", "name": "hill"})).unwrap();
let id = v["layer"].as_u64().unwrap() as u32;
let rl = s.map().layer(id).unwrap().raster.clone().unwrap();
let embedded = rl.embedded.clone().unwrap();
assert_eq!(embedded.as_slice(), rustgis_data::raster::geotiff::write(rl.data.as_ref().unwrap(), 0).unwrap().as_slice());
let dir = std::env::temp_dir().join(format!("rustgis-written-export-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// Marked bytes in its place show which file the export writes: a fresh encode wouldn't hold them.
let marked = [embedded.as_slice(), b"written"].concat();
let pixels = rl.data.clone().unwrap();
drop(rl);
s.map_mut().layer_mut(id).unwrap().raster =
Some(rustgis_map::RasterLayer::from_written(std::sync::Arc::unwrap_or_clone(pixels), "hill.tif", marked.clone()));
let tif = dir.join("hill.tif");
s.run("share.exportRaster", &json!({"layer": id, "path": tif.display().to_string()})).unwrap();
assert_eq!(std::fs::read(&tif).unwrap(), marked);
// The browser's download takes the same file; a cloud-optimised one is encoded.
assert_eq!(crate::cmd::raster::geotiff_bytes(&mut s, &json!({"layer": id})).unwrap().1, marked);
assert_ne!(crate::cmd::raster::geotiff_bytes(&mut s, &json!({"layer": id, "cog": true})).unwrap().1, marked);
let rl = s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap();
let band = &mut std::sync::Arc::make_mut(rl.data.as_mut().unwrap()).bands[0];
band.data[0] = if band.data[0] == 7.0 { 8.0 } else { 7.0 };
let changed = band.data[0];
s.run("share.exportRaster", &json!({"layer": id, "path": tif.display().to_string()})).unwrap();
assert_eq!(rustgis_data::raster::read_path(&tif).unwrap().bands[0].data[0], changed);
std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn exporting_a_raster_as_a_cog() {
let mut s = world();
Expand Down
48 changes: 48 additions & 0 deletions crates/map/src/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ pub struct RasterLayer {
/// [`RasterLayer::dropped_unsaid`]).
#[serde(skip)]
dropped: Vec<&'static str>,
/// The pixels and the file that `embedded` was written from them as, while both are still the
/// layer's (see [`RasterLayer::written_file`]): held weakly, so a change to either, which takes
/// a new allocation, breaks the pairing.
#[serde(skip)]
written: Option<(Weak<Raster>, Weak<Vec<u8>>)>,
}

/// Called once with a cloud-optimised GeoTIFF's overview, or why it couldn't be read.
Expand Down Expand Up @@ -333,6 +338,7 @@ impl RasterLayer {
lost_said: false,
look_lost: None,
dropped: Vec::new(),
written: None,
})
}

Expand Down Expand Up @@ -383,6 +389,7 @@ impl RasterLayer {
lost_said: false,
look_lost: None,
dropped: Vec::new(),
written: None,
}
}

Expand All @@ -391,6 +398,24 @@ impl RasterLayer {
Self::from_shared(raster, file_name, Arc::new(bytes))
}

/// A raster with the file [`rustgis_data::raster::geotiff::write_all`] wrote of it (or
/// [`rustgis_data::raster::geotiff::write`] of its first band, the same file when that writes every
/// band), kept in the project: [`RasterLayer::written_file`] gives that file back while neither
/// changes.
pub fn from_written(raster: Raster, file_name: impl Into<String>, bytes: Vec<u8>) -> RasterLayer {

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.

from_written is pub and takes its file on trust: nothing checks that bytes is the geotiff::write or write_all output of raster's pixels. Every current caller passes the bytes it just encoded from the same raster, so nothing is wrong today. But a future caller that passes, say, a cloud-optimised file (or bytes of a different raster) would have the export write those bytes as a plain GeoTIFF while its notes say it encoded the pixels. The doc comment states the contract; a pub(crate) constructor, or a debug assertion that the first band's dimensions match, would make the mistake harder to make.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Left for the release quality pass: every caller passes the bytes it just encoded from the same raster, and the doc states the contract.

let mut layer = Self::from_bytes(raster, file_name, bytes);
layer.written = layer.data.as_ref().map(Arc::downgrade).zip(layer.embedded.as_ref().map(Arc::downgrade));
layer
}

/// The embedded file, when it is the one [`RasterLayer::from_written`] was given for the
/// pixels the layer holds now: an export that writes every band writes those same bytes.
pub fn written_file(&self) -> Option<&Arc<Vec<u8>>> {
let (pixels, file) = self.written.as_ref()?;
let (data, embedded) = (self.data.as_ref()?, self.embedded.as_ref()?);
(Weak::as_ptr(pixels) == Arc::as_ptr(data) && Weak::as_ptr(file) == Arc::as_ptr(embedded)).then_some(embedded)
}

/// Keeps the original shared allocation used to decode an uploaded raster.
pub fn from_shared(raster: Raster, file_name: impl Into<String>, bytes: Arc<Vec<u8>>) -> RasterLayer {
let style = RasterStyle::default_for(&raster);
Expand Down Expand Up @@ -421,6 +446,7 @@ impl RasterLayer {
lost_said: false,
look_lost: None,
dropped: Vec::new(),
written: None,
}
}

Expand Down Expand Up @@ -465,6 +491,7 @@ impl RasterLayer {
lost_said: false,
look_lost: None,
dropped: Vec::new(),
written: None,
}
}

Expand Down Expand Up @@ -896,6 +923,7 @@ impl RasterLayer {
lost_said: _,
look_lost: _,
dropped: _,
written: _,
} = self;
if *in_place || *tiled || opening.is_some() || read_still.is_some() || self.casts_shadows() {
return None;
Expand Down Expand Up @@ -2602,6 +2630,7 @@ impl RasterLayer {
lost_said: _,
look_lost: _,
dropped: _,
written: _,
} = self;
let mut out = Vec::new();
if let Some(p) = path {
Expand Down Expand Up @@ -3217,6 +3246,25 @@ mod tests {
assert!(missing.data.is_none());
}

#[test]
fn a_written_file_is_given_back_only_while_its_pixels_and_bytes_are_the_layers() {
let r = dem();
let bytes = rustgis_data::raster::geotiff::write_all(&r).unwrap();
assert!(RasterLayer::from_bytes(r.clone(), "dem.tif", bytes.clone()).written_file().is_none());
let written = RasterLayer::from_written(r, "dem.tif", bytes.clone());
assert_eq!(written.written_file().map(|b| b.as_slice()), Some(bytes.as_slice()));
// A copy shares both, so it gives the file too.
assert!(written.clone().written_file().is_some());
let mut edited = written.clone();
if let Some(band) = edited.data.as_mut().and_then(|d| Arc::make_mut(d).bands.first_mut()) {
band.data[0] += 1.0;
}
assert!(edited.written_file().is_none());
let mut replaced = written.clone();
replaced.embedded = Some(Arc::new(bytes));
assert!(replaced.written_file().is_none());
}

/// A plain web address is read as it was before logins: never downloaded whole on reload.
#[test]
fn reload_downloads_only_s3_and_login_wrapped_addresses() {
Expand Down
Loading