Skip to content
34 changes: 25 additions & 9 deletions crates/engine/src/cmd/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ impl Room {
}

/// What to do about a file too large to download.
pub(crate) const SMALLER: &str =
"make a smaller file (fewer features or layers, a smaller size or fewer pages), use the ribbon's buttons, or use the desktop app";
pub(crate) const SMALLER: &str = "make a smaller file (fewer features or layers, a smaller size or fewer pages), or use the desktop app";

/// The file a command makes at once ([`file_command`]): the path it is for, and, where it is
/// downloaded, the room it has. A file that is written has no limit here but memory.
Expand All @@ -159,6 +158,13 @@ impl<'a> Output<'a> {
/// A file that is written, or kept in the session: nothing limits it here.
pub(crate) const UNLIMITED: Output<'static> = Output { path: "", room: None };

/// A file the front end gets from the session itself, held to the room a download has where
/// files are downloaded. Its name isn't known until it is made, so a refusal calls it `path`,
/// what kind of file it is.
pub(crate) fn here(s: &Session, path: &'a str) -> Result<Output<'a>, String> {
Ok(Output { path, room: s.download_room()? })
}

/// Whether it is made to be downloaded.
pub(crate) fn downloads(self) -> bool {
self.room.is_some()
Expand Down Expand Up @@ -282,13 +288,17 @@ pub(crate) fn mib(bytes: usize) -> usize {
/// most the files waiting for download may hold. The features and the file are held at once, in
/// the browser's memory. A fixed figure: the browser can't say what memory it has free, so
/// `rustgis_data::memory::planned` would give its floor there.
pub(crate) const MAX_DOWNLOAD_BYTES: usize = 256 << 20;
pub const MAX_DOWNLOAD_BYTES: usize = 256 << 20;

/// What [`Session::offer_files`] is given for files that nothing limits but memory.
pub const NO_DOWNLOAD_LIMIT: usize = usize::MAX;

/// Every feature of layer `l`, read in place, for a file made in memory to be downloaded: refused
/// past [`MAX_DOWNLOAD_BYTES`] of features, before any is read when the source's count alone says
/// so. A definition query is applied after the read, so it doesn't make the read smaller.
pub(super) fn read_for_download(l: &rustgis_map::Layer) -> Result<(Dataset, rustgis_map::Unreadable), String> {
read_for_download_after(l, 0)
/// so. A definition query is applied after the read, so it doesn't make the read smaller. Where
/// the file has no limit, neither has the read.
pub(super) fn read_for_download(l: &rustgis_map::Layer, room: Room) -> Result<(Dataset, rustgis_map::Unreadable), String> {
if room.bytes == NO_DOWNLOAD_LIMIT { l.load_all_counted() } else { read_for_download_after(l, 0) }

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.

This fixes the read for share.exportLayer and data.convert, but its sibling in crates/engine/src/cmd/sharing.rs:383 (load_whole) doesn't get the same fix. It calls read_for_download_after(l, *held) whenever out.downloads() is true. On the phone the room is NO_DOWNLOAD_LIMIT, so downloads() is still true and the read stops at 256 MiB of features. load_whole is reached from the web map, web layer, geodata service and web scene items (webMap, webLayer, geodataService, webScene) through item_output and download_share, so the phone's buttons for those now refuse a large streamed layer. Before this PR the phone read them whole. That contradicts the description's "no limit, as before".

Suggested fix, in load_whole in sharing.rs: take the bounded read only when there is a limit, so both readers agree:
let (ds, unread) = if out.downloads() && out.most() != super::exports::NO_DOWNLOAD_LIMIT { super::exports::read_for_download_after(l, *held)? } else { l.load_all_counted()? };

The new tests don't reach this. a_button_over_the_download_limit_offers_nothing uses small fixtures, and the item test runs only with the 10-byte cap. A streamed layer checked under offer_most = Some(usize::MAX) would catch it.

Category: bug

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 phone does not reach this. Its share buttons run ui.saveItem, which calls item_output without offer_files, so Output::here finds no downloads (downloads_files is false off the browser), out.downloads() is false and the layer is read whole, as before. run_offering, the only caller of offer_files, runs no share command. The two readers should agree all the same, so a caller added later cannot meet it: that comes with the next pull request for #3153.

}

/// [`read_for_download`] for a file made of several layers, `held` bytes of whose features were
Expand Down Expand Up @@ -514,12 +524,15 @@ pub(crate) fn download_command(
// Said if the queue refuses the file, as when it isn't made.
let unsent = held.clone();
let Made { bytes, answer, done, taken, .. } = made;
let done = done.unwrap_or_else(|| format!("Download offered: {name}"));
// A front end that offers the file says so itself.
let done = (!s.offers_files()).then(|| done.unwrap_or_else(|| format!("Download offered: {name}")));
let then: Then = Box::new(move |s: &mut Session, _: &mut Value| {
if let Some(taken) = taken {
taken(s);
}
s.notify_written(done);
if let Some(done) = done {
s.notify_written(done);
}
let mark = s.notice_mark();
for notice in held {
s.relay_notice(notice);
Expand Down Expand Up @@ -732,7 +745,10 @@ pub(crate) fn drawn(
// already reported above retain their screen markers, so this cannot duplicate them.
s.notice_landed_pixels();
written?;
s.notify_written(format!("Exported {path}"));
// A front end that offers the file says so itself.
if !s.offers_files() {
s.notify_written(format!("Exported {path}"));
}
Ok(())
});
Ok(Wrote {
Expand Down
25 changes: 22 additions & 3 deletions crates/engine/src/cmd/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,18 @@ pub(crate) fn package(s: &mut Session, p: &Value) -> Result<(String, Vec<u8>), S

/// Construction notes describe the delivered package, so callers emit them after delivery.
pub(crate) fn package_output(s: &mut Session, p: &Value) -> Result<(String, Vec<u8>, rustgis_data::loss::Notes), String> {
package_output_within(s, p, super::exports::Output::UNLIMITED)
}

/// [`package_output`] for the file `out` describes: a downloaded one is stopped as it passes its
/// room.
pub(crate) fn package_output_within(
s: &mut Session,
p: &Value,
out: super::exports::Output<'_>,
) -> Result<(String, Vec<u8>, rustgis_data::loss::Notes), String> {
let mut notes = rustgis_data::loss::Notes::new();
let (name, bytes) = build_package(s, p, &mut notes)?;
let (name, bytes) = build_package(s, p, &mut notes, out)?;
Ok((name, bytes, notes))
}

Expand All @@ -106,7 +116,12 @@ fn legacy_user(s: &Session) -> Result<(), String> {
/// `notes`, said once the package has been delivered. Cancel is checked between streamed
/// chunks, tile archives and the encoding steps. A single archive read or ZIP compression
/// runs through before the next check.
fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Notes) -> Result<(String, Vec<u8>), String> {
fn build_package(
s: &mut Session,
p: &Value,
notes: &mut rustgis_data::loss::Notes,
out: super::exports::Output<'_>,
) -> Result<(String, Vec<u8>), String> {
use rustgis_data::progress;
progress::check().map_err(|e| e.to_string())?;
let mut losses = rustgis_data::loss::Notes::new();
Expand Down Expand Up @@ -582,7 +597,11 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not
if let Some(package) = project.field_origin.as_ref().map(|o| o.package.as_str()).filter(|p| !coming_back && !p.is_empty()) {
entries.push((super::field_changes::GIVEN.into(), super::field_changes::given_entry(package)?));
}
let bytes = rustgis_data::zip::write(&entries)?;
let mut parts = out.parts();
for (name, bytes) in entries {
parts.push(name, bytes)?;
}
let bytes = parts.zip()?;
progress::check().map_err(|e| e.to_string())?;
notes.extend(losses);
Ok((area, bytes))
Expand Down
31 changes: 16 additions & 15 deletions crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3882,27 +3882,28 @@ pub(super) fn queue_export(s: &mut Session, mut wrote: super::exports::Wrote) ->
// Not exported until the download is taken: the claim goes from the pending answer, and what
// follows it (what the file leaves out) stays, under the file's name.
let exported = format!("Exported {file_name}");
let messages: Vec<String> = wrote
.completion_notes()
.into_iter()
.filter_map(|message| match message.strip_prefix(&exported) {
Some("") => None,
Some(note) if note.starts_with([' ', ';']) => Some(format!("{file_name}{note}")),
_ => Some(message),
})
.collect();
let unclaimed = |message: &str| match message.strip_prefix(&exported) {
Some("") => None,
Some(note) if note.starts_with([' ', ';']) => Some(format!("{file_name}{note}")),
_ => Some(message.to_string()),
};
let messages: Vec<String> = wrote.completion_notes().iter().filter_map(|message| unclaimed(message)).collect();
// A front end that offers the file says so itself, and its browser or phone may not save it:
// what follows the claim is all that is said once it is taken.
if s.offers_files() {
wrote.notes = wrote.notes.into_vec().into_iter().filter_map(|n| unclaimed(n.as_str()).map(|text| n.map_text(|_| text))).collect();
}
let mut out = queue(s, file_name, bytes, Delivery::Export(Box::new(wrote)))?;
out["messages"] = json!(messages);
Ok(out)
}

/// Why no more can wait for download, of the `cap` bytes that waiting files may hold in all.
pub(crate) fn queue_full(cap: usize) -> String {
format!(
"file export queue limit reached ({} files or {} MiB); split the task, model, or script into smaller runs",
super::exports::MAX_DOWNLOADS,
super::exports::mib(cap)
)
let files = super::exports::MAX_DOWNLOADS;
// Without a limit on the bytes, only the files can be too many.
let bytes = if cap == super::exports::NO_DOWNLOAD_LIMIT { String::new() } else { format!(" or {} MiB", super::exports::mib(cap)) };
format!("file export queue limit reached ({files} files{bytes}); split the task, model, or script into smaller runs")
}

/// Holds `bytes` for the front end to offer as the download `file_name` and acknowledge with
Expand All @@ -3919,7 +3920,7 @@ fn queue(s: &mut Session, file_name: String, bytes: Arc<Vec<u8>>, from: Delivery
Err(shared) => shared,
};
let cap = s.download_cap();
let held = s.waiting_download_bytes();
let held = if cap == super::exports::NO_DOWNLOAD_LIMIT { 0 } else { s.waiting_download_bytes() };
// An export whose writer takes a limit was stopped at it; this is what holds the others (a
// picture, an SVG, a PDF past its pages, the file a raster layer holds) to it.
// Measured as the queue counts what waits: by what the file holds, its spare room included.
Expand Down
11 changes: 8 additions & 3 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1921,9 +1921,12 @@ pub fn item_bytes(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec
Ok((name, bytes))
}

/// Builds an item and returns construction-loss notes for publication only after delivery.
/// Builds an item and returns construction-loss notes for publication only after delivery. In the
/// browser, where it is downloaded, it is stopped as it passes the room a download has.
pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec<u8>, rustgis_data::loss::Notes), String> {
item_output_within(s, kind, p, Output::UNLIMITED)
let what = ITEMS.iter().find(|i| i.0 == kind).map_or("the file", |i| i.2);
let out = Output::here(s, what)?;

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.

Nit, grouped with the other small points. The refusal reads Web map: stopped once the file passed the 256 MiB ... because the item's label is passed as the path. The file name isn't known until the item is built (safe(&name) at the end of item_output_within), so this message can't name the file the way the other refusals do. That's acceptable, but the label is the only place the user can see what was refused, so the doc comment on Output::here should say so.

Two smaller points, same group. The cap == usize::MAX "no limit" sentinel is now checked in four places (download_cap, download_room, queue, read_for_download), and a named helper would keep them in step. run_offering assigns params["path"], which panics on a non-object Value. Every current caller passes a json! object, so this is safe today.

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.

All three are in the next push: the comment says what the label is, NO_DOWNLOAD_LIMIT names the sentinel, and run_offering refuses parameters that are not an object.

item_output_within(s, kind, p, out)
}

/// [`item_output`] for the file `out` describes: a downloaded one is stopped as it passes its room.
Expand Down Expand Up @@ -2006,7 +2009,7 @@ fn item_output_within(
}
"projectPackage" => (s.project.name.clone(), package_project(s, &mut construction_notes, out)?),
"fieldPackage" => {
let (name, bytes, notes) = super::field::package_output(s, p)?;
let (name, bytes, notes) = super::field::package_output_within(s, p, out)?;
construction_notes.extend(notes);
(name, bytes)
}
Expand Down Expand Up @@ -2072,6 +2075,8 @@ fn item_output_within(
}
k => return Err(format!("unknown item '{k}'")),
};
// A small file's writer, such as the bookmarks', takes no limit.
out.check(bytes.len())?;
let ext = ITEMS.iter().find(|i| i.0 == kind).map_or("json", |i| i.1);
Ok((format!("{}.{ext}", safe(&name)), bytes, construction_notes))
}
Expand Down
5 changes: 4 additions & 1 deletion crates/engine/src/cmd/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,10 @@ fn write_layer(
let mut held = None;
use std::borrow::Cow;
let (mut whole, unreadable) = if l.is_streamed() && chunks.is_none() {
let (dataset, unreadable) = if download.is_some() { super::exports::read_for_download(l)? } else { l.load_all_counted()? };
let (dataset, unreadable) = match download {
Some(room) => super::exports::read_for_download(l, room)?,
None => l.load_all_counted()?,
};
(Cow::Owned(dataset), unreadable)
} else {
(Cow::Borrowed(&l.dataset), rustgis_map::Unreadable::default())
Expand Down
6 changes: 4 additions & 2 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2755,8 +2755,10 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result<super::exports::Wor
(notes, result.null_numbers, result.query)
} else {
let (mut ds, unreadable) = if layer.is_streamed() {
let (ds, unreadable) =
if download.is_some() { super::exports::read_for_download(&layer)? } else { layer.load_all_counted()? };
let (ds, unreadable) = match download {
Some(room) => super::exports::read_for_download(&layer, room)?,
None => layer.load_all_counted()?,
};
(Cow::Owned(ds), unreadable)
} else {
(Cow::Borrowed(&layer.dataset), rustgis_map::Unreadable::default())
Expand Down
6 changes: 0 additions & 6 deletions crates/engine/src/construction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,6 @@ pub(crate) fn forget_feature(s: &mut Session, layer: u32, feature: u64) {
}

impl Session {
/// Counted losses for a layer output, including browser downloads. Call before encoding
/// and present the notes only after the output has been accepted or written.
pub fn layer_construction_output_notes(&self, layer: u32) -> Result<Vec<rustgis_data::loss::Note>, String> {
let l = self.map().layer(layer).ok_or("no such layer")?;
self.constructions.export_notes(self.map().instance_id(), l)
}
/// Counted runtime-construction losses for a whole-project output. Embedders saving the
/// public `Project` directly should present these notes too: `Project` owns no session cache.
/// Explicit save/download paths call this inside their existing durable output transaction;
Expand Down
25 changes: 22 additions & 3 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,9 @@ pub struct Session {
notices_given: u64,
/// While a download's file is made, the notices that wait with it ([`Session::holding_notices`]).
held_notices: Option<Vec<Notice>>,
/// While the front end runs a command whose file it downloads, the most bytes it takes
/// ([`Session::offer_files`]).
offering: Option<usize>,
/// Loss notices given in this session by code, including ones no longer kept, less those a
/// failed command withdrew (see [`Session::losses_given`]).
losses_given: Vec<(rustgis_data::loss::LossCode, u64)>,
Expand Down Expand Up @@ -1538,6 +1541,7 @@ impl Session {
diagnostics: rustgis_data::diagnostics::History::default(),
notices_given: 0,
held_notices: None,
offering: None,
losses_given: Vec::new(),
beyond_said: None,
crs_notes_said: Vec::new(),
Expand Down Expand Up @@ -1854,7 +1858,20 @@ impl Session {
if self.queue_gp_files {
return true;
}
cfg!(target_arch = "wasm32")
self.offering.is_some() || cfg!(target_arch = "wasm32")
}

/// For a front end whose button saves by downloading: until it is set back, a command that
/// takes a path queues its file ([`Session::take_gp_files`]) as a browser's script does, held
/// to `most` bytes ([`cmd::exports::NO_DOWNLOAD_LIMIT`] for no limit but memory). It leaves saying that the file was
/// offered to the front end. Gives what was set before.
pub fn offer_files(&mut self, most: Option<usize>) -> Option<usize> {
std::mem::replace(&mut self.offering, most)
}

/// Whether the front end says itself that a file was offered ([`Session::offer_files`]).
pub(crate) fn offers_files(&self) -> bool {
self.offering.is_some()
}

/// The most bytes the files waiting for download may hold in all.
Expand All @@ -1863,7 +1880,7 @@ impl Session {
if let Some(cap) = self.download_cap {
return cap;
}
cmd::exports::MAX_DOWNLOAD_BYTES
self.offering.unwrap_or(cmd::exports::MAX_DOWNLOAD_BYTES)
}

/// Where files are downloaded, the room for one more; `None` where they are written. Refused
Expand All @@ -1873,7 +1890,9 @@ impl Session {
return Ok(None);
}
let waiting = self.waiting_download_bytes();
let bytes = self.download_cap().saturating_sub(waiting);
// No limit stays none whatever waits.
let cap = self.download_cap();
let bytes = if cap == cmd::exports::NO_DOWNLOAD_LIMIT { cap } else { cap.saturating_sub(waiting) };
if self.waiting_download_count() >= cmd::exports::MAX_DOWNLOADS || bytes == 0 {
return Err(cmd::gp::queue_full(self.download_cap()));

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.

When there is no byte limit (the phone, where download_cap() is usize::MAX), this refusal still says queue_full(cap), which prints mib(cap). So a count refusal reads "file export queue limit reached (8 files or 17592186044416 MiB)". The count is the limit that tripped, so the byte figure is wrong. It needs eight files that are never acknowledged, so the impact is small. Suggest leaving the MiB figure out of queue_full when the cap is NO_DOWNLOAD_LIMIT, and having this call pass that flag or a sentinel-aware message.

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.

Agreed, and the count is the limit that trips there. Left for the release quality pass: it needs eight files that were never acknowledged, which a button never leaves.

}
Expand Down
1 change: 0 additions & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use crate::render::rustgis_tiles::address::Reach;
mod capabilities;
#[path = "project_label_losses.rs"]
pub(crate) mod label_losses;
pub use capabilities::layout_file_bytes;
#[cfg(test)]
pub(crate) use capabilities::{layer_file_bytes, map_file_bytes};
pub(crate) use capabilities::{layer_file_within, layout_file_within, map_file_within, model_capabilities, task_capabilities};
Expand Down
5 changes: 0 additions & 5 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1366,11 +1366,6 @@ pub(crate) fn map_file_within(map: &Map, out: Output<'_>) -> Result<Vec<u8>, Str
/// A layout file has its own header, as a map file has: what its elements use, as the project
/// holding it requires for them (#2277). Indented, as layout files have always been written. No
/// `crs-wkt`: a layout holds no coordinate system, only a measured grid's as text.
pub fn layout_file_bytes(layout: &rustgis_map::layout::Layout) -> Result<Vec<u8>, String> {
layout_file_within(layout, Output::UNLIMITED)
}

/// [`layout_file_bytes`] for the file `out` describes.
pub(crate) fn layout_file_within(layout: &rustgis_map::layout::Layout, out: Output<'_>) -> Result<Vec<u8>, String> {
let requires = layout_capabilities(std::slice::from_ref(layout));
out.json_pretty(&Item { format: FORMAT, requires, value: layout })
Expand Down
Loading
Loading