diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index e9ef743a27..3ce202f8e1 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -486,7 +486,13 @@ pub(crate) fn read_text(p: &Value) -> Result { /// The project JSON inside a package. pub fn package_text(bytes: &[u8]) -> Result { - let entries = rustgis_data::zip::read_matching(bytes, |n| crate::project::is_project_file(n) || n.ends_with(".rgismap"))?; + package_text_within(bytes, rustgis_data::zip::MAX_TOTAL) +} + +/// [`package_text`] inflating at most `budget` bytes (and never more than [`rustgis_data::zip::MAX_TOTAL`]). +pub fn package_text_within(bytes: &[u8], budget: usize) -> Result { + let entries = + rustgis_data::zip::read_matching_within(bytes, |n| crate::project::is_project_file(n) || n.ends_with(".rgismap"), budget)?; let (_, data) = entries .into_iter() .find(|(n, _)| crate::project::is_project_file(n) || n.ends_with(".rgismap")) @@ -2151,19 +2157,27 @@ pub(crate) fn durable_bytes_with( /// Decodes the same data-before-text choice without opening a path. `text` is lent, not copied: /// every save asks each capability check about it. pub(crate) fn inline_text(p: &Value) -> Result>, String> { + inline_text_within(p, max_file(), rustgis_data::zip::MAX_TOTAL) +} + +/// [`inline_text`] with the sizes given: `limit` for the text, or for the base64 of `data`, and +/// `inflated` for what a package inflates to (at most [`rustgis_data::zip::MAX_TOTAL`]). +/// [`inline_text`] passes this computer's file limit and the zip limit; the project walk passes its +/// own budget for both. +pub(crate) fn inline_text_within(p: &Value, limit: u64, inflated: usize) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; - if d.len() as u64 > max_file() / 3 * 4 { + if d.len() as u64 > (limit / 3).saturating_mul(4) { return Err(too_large()); } let bytes = base64::engine::general_purpose::STANDARD.decode(d.trim()).map_err(|_| "data must be base64".to_string())?; if bytes.starts_with(b"PK") { - return package_text(&bytes).map(|t| Some(t.into())); + return package_text_within(&bytes, inflated.min(rustgis_data::zip::MAX_TOTAL)).map(|t| Some(t.into())); } return String::from_utf8(bytes).map(|t| Some(t.into())).map_err(|_| "not a RustGIS file".to_string()); } match ps(p, "text") { - Some(t) if t.len() as u64 <= max_file() => Ok(Some(t.into())), + Some(t) if t.len() as u64 <= limit => Ok(Some(t.into())), Some(_) => Err(too_large()), None => Ok(None), } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index e817be5fff..9bf09c981e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -5,6 +5,8 @@ use rustgis_map::{Layer, Map, raster::RasterRenderer}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::borrow::Cow; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; use super::{FORMAT, ModelGraph, ModelNodeKind, ModelStep, Project}; use crate::cmd::exports::Output; @@ -31,6 +33,12 @@ impl<'de> Deserialize<'de> for Project { impl Project { /// Required features of all saved maps, snapshots and replayable commands/scripts. pub(crate) fn required_capabilities(&self) -> Vec<&'static str> { + self.required_capabilities_at(0, &OpenedReads::default()) + } + + /// [`Project::required_capabilities`] of a project opened `depth` levels down by saved steps + /// ([`collect_opened_project`]). + fn required_capabilities_at(&self, depth: usize, reads: &OpenedReads) -> Vec<&'static str> { let mut required = map_capabilities(self.maps.iter().chain(self.offline_areas.iter().map(|a| &a.data))); if !self.origin_id.is_empty() || self.field_origin.is_some() || self.offline_areas.iter().any(|area| !area.id.is_empty()) { required.push("field-origin"); @@ -94,8 +102,15 @@ impl Project { required.push("label-duplicates"); } let commands: Vec<&'static str> = - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| self.uses_commands(uses).then_some(name)).collect(); + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| self.uses_commands(&uses).then_some(name)).collect(); required.extend(commands.into_iter().filter(|name| !required.contains(name)).collect::>()); + // And what a project that a saved step opens from its text requires (#3462, #3476). + let opened = RefCell::new(Vec::new()); + self.uses_commands(&|id: &str, params: &Value| { + collect_opened_project(&opened, reads, depth, id, params); + false + }); + merge_opened(&mut required, opened); if self.tasks.iter().any(|task| task.steps.iter().any(|step| command_uses_table_export_order(&step.command, &step.params))) || self.gp_history.iter().any(|record| { command_uses_table_export_order(&record.id, &record.params) @@ -132,12 +147,12 @@ impl Project { } /// Apply the same capability predicate to every replayable project container. - fn uses_commands(&self, uses: CommandCheck) -> bool { + fn uses_commands(&self, uses: &impl Fn(&str, &Value) -> bool) -> bool { self.models.iter().any(|m| model_uses(&m.steps, m.graph.as_ref(), uses)) - || self.tasks.iter().any(|t| t.steps.iter().any(|s| command_uses(&uses, &s.command, &s.params))) + || self.tasks.iter().any(|t| t.steps.iter().any(|s| command_uses(uses, &s.command, &s.params))) || self.gp_history.iter().any(|h| { - command_uses(&uses, if h.id.is_empty() { &h.tool } else { &h.id }, &h.params) - || h.command.as_ref().is_some_and(|(id, params)| command_uses(&uses, id, params)) + command_uses(uses, if h.id.is_empty() { &h.tool } else { &h.id }, &h.params) + || h.command.as_ref().is_some_and(|(id, params)| command_uses(uses, id, params)) }) || self.notebooks.iter().any(|n| { n.language().is_none() @@ -156,9 +171,148 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { required.push("table-export-order"); } + let (opened, reads) = (RefCell::new(Vec::new()), OpenedReads::default()); + for step in steps { + command_uses( + &|id: &str, params: &Value| { + collect_opened_project(&opened, &reads, 0, id, params); + false + }, + &step.command, + &step.params, + ); + } + merge_opened(&mut required, opened); required } +/// What a walk has read of the projects that saved steps open: what each text required, by depth +/// and then a digest of where it came from (its `text` or its base64 `data`, as the step gives it), +/// so one opened by several steps at the same depth is read once, and what is kept is 64 bytes, +/// never the decoded text, which can be a gigabyte. The digest is looked up before anything is +/// decoded. It also counts the bytes read, up to a budget. +struct OpenedReads { + read: RefCell>>>, + bytes: Cell, + /// The most bytes of texts a walk reads: [`OPENED_BYTES`], or less in a test. + budget: u64, +} + +impl Default for OpenedReads { + fn default() -> Self { + OpenedReads::with_budget(OPENED_BYTES) + } +} + +impl OpenedReads { + fn with_budget(budget: u64) -> Self { + OpenedReads { read: RefCell::default(), bytes: Cell::new(0), budget } + } +} + +/// The most bytes of texts a walk reads before a step that opens one requires everything. The same +/// on every computer, since what a project requires is saved in it, and small enough to bound the +/// time a save spends on it (about 4 ms per MB with real structure, so a quarter of a second at the +/// limit). A project opening a larger text is rare, and then an older release refuses it instead of +/// opening it and dropping what it can't see. +const OPENED_BYTES: u64 = 64 << 20; + +/// How many projects deep a saved step's opened project is read for what it requires. +const MAX_OPENED_DEPTH: usize = 32; + +/// Adds to `found` what the project that a step opens from its text requires (#3462): the text of +/// `project.openText`, or the `data` else the `text` of `project.fromTemplate`, as those commands +/// read it, without repair ([`Project::from_peer_raw`]) so that what loading it would cut still +/// counts, and so on down the projects its own steps open, `script.run` lines included. Text that +/// isn't a project requires nothing. +/// +/// Two limits keep the walk small: [`MAX_OPENED_DEPTH`] levels, and a budget of bytes +/// ([`OpenedReads::budget`]) in all the texts read. A `text` that holds a project escapes it, so +/// only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a +/// step that opens a text requires every capability a release knows, so an older one refuses it +/// instead of dropping what it can't see, and the text isn't decoded; so does a `data` template +/// that can't be decoded, as what a computer's limits say of it can't change what a project +/// requires. This bounds this walk only: the checks that read a style, layer or map given inline +/// still start again from the top when that text is a project. +/// +/// Returns nothing: it is called from a walk over saved commands ([`command_uses`], a script's +/// lines, a model's graph) as `|id, params| { collect_opened_project(..); false }`, so that the +/// walk visits every command. It has no Cancel check: a walk parses at most [`OPENED_BYTES`] of +/// opened texts (about a quarter of a second at the limit), on each save that calls it. +fn collect_opened_project(found: &RefCell>, reads: &OpenedReads, depth: usize, id: &str, params: &Value) { + // What the step opens, as the command reads it: `project.openText` its `text` only, whatever + // else the step holds; `project.fromTemplate` its `data` before its `text`. + let (tag, source) = match id { + "project.openText" => ("text", crate::cmd::ps(params, "text")), + "project.fromTemplate" => match crate::cmd::ps(params, "data") { + Some(data) => ("data", Some(data)), + None => ("text", crate::cmd::ps(params, "text")), + }, + "script.run" => { + if let Some(script) = params.get("script").and_then(Value::as_str) { + script_uses(script, |id, params| { + collect_opened_project(found, reads, depth, id, params); + false + }); + } + return; + } + _ => return, + }; + let Some(source) = source else { return }; + // A source longer than the whole budget (as base64, a third more for a `data`) is known to + // require everything, and isn't hashed. + let longest = if tag == "data" { (reads.budget / 3).saturating_mul(4) } else { reads.budget }; + let names: Vec<&'static str> = if depth >= MAX_OPENED_DEPTH || source.len() as u64 > longest { + super::CAPABILITIES.to_vec() + } else { + let digest = format!("{tag}:{}", rustgis_plugins::package::sha256_hex(source.as_bytes())); + // Asked before `found` is borrowed: the project's own walk never touches this cell. + let cached = reads.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); + cached.unwrap_or_else(|| { + let budget = reads.budget; + let spent = reads.bytes.get() >= budget; + // A template that can't be decoded (too large for the budget, not base64, a zip this + // build refuses) is not told apart by what the computer would say: it requires + // everything, as past the budget. What a project requires can't depend on the computer. + let text = if spent { + None + } else if tag == "data" { + crate::cmd::items::inline_text_within(params, budget, usize::try_from(budget).unwrap_or(usize::MAX)).ok().flatten() + } else { + Some(Cow::Borrowed(source)) + }; + let undecoded = !spent && tag == "data" && text.is_none(); + let bytes = reads.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); + reads.bytes.set(bytes); + let names = if spent || undecoded || bytes > budget { + super::CAPABILITIES.to_vec() + } else { + text.and_then(|text| Project::from_peer_raw(&text).ok()) + .map(|project| project.required_capabilities_at(depth + 1, reads)) + .unwrap_or_default() + }; + reads.read.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); + names + }) + }; + let mut found = found.borrow_mut(); + for name in names { + if !found.contains(&name) { + found.push(name); + } + } +} + +/// `opened`, a walk's findings ([`collect_opened_project`]), added to `required` after what it has. +fn merge_opened(required: &mut Vec<&'static str>, opened: RefCell>) { + for name in opened.into_inner() { + if !required.contains(&name) { + required.push(name); + } + } +} + type CommandCheck = fn(&str, &Value) -> bool; const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("slope-percent", command_uses_percent_slope), @@ -329,13 +483,11 @@ fn command_sets_generalize(id: &str, params: &Value) -> bool { && crate::cmd::f(params, "generalize") .is_some_and(|v| crate::cmd::raster::relief_generalize(Some(v)).is_ok_and(|g| g > 0.0)) } - // A style, layer, map or project given inline (`text` or `data`) that holds one (#3425 - // review); one read from a `"path"` is a file, whose header requires what it uses. - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + // A style, layer or map given inline (`text` or `data`) that holds one (#3425 review); one + // read from a `"path"` is a file, whose header requires what it uses. + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_generalizes(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_generalizes), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_generalize)), _ => false, } @@ -381,18 +533,16 @@ fn command_masks_by_raster(id: &str, params: &Value) -> bool { } } -/// A saved `style.add`, `style.import`, `layer.addLayerFile`, `map.import` or `project.openText` -/// whose inline style, layer, map or project (`text` or `data`) keeps Unique Values classes in +/// A saved `style.add`, `style.import`, `layer.addLayerFile` or `map.import` whose inline style, +/// layer or map (`text` or `data`) keeps Unique Values classes in /// their order (#3319): an older reader would take the renderer with the classes sorted. One read /// from a `"path"` is a file, whose header requires what it uses. Read only when the text names /// `keep_order` (or escapes, which could hide it). fn command_adds_kept_class_order(id: &str, params: &Value) -> bool { match id { - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_keeps_class_order(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_keeps_class_order), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_adds_kept_class_order)), _ => false, } @@ -569,13 +719,11 @@ fn command_sets_obstacles(id: &str, params: &Value) -> bool { "labels.placement" => { params.get("obstacleWeight").and_then(crate::cmd::labels::number).is_some_and(|w| rustgis_map::symbology::label_weight(w) > 0) } - // A style, layer, map, project or template given inline (`text` or `data`) that holds one; one - // read from a `"path"` is a file, whose header requires what it uses. - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + // A style, layer or map given inline (`text` or `data`) that holds one; one read from a + // `"path"` is a file, whose header requires what it uses. + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_sets_obstacles(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_sets_obstacles), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_obstacles)), _ => false, } @@ -759,22 +907,11 @@ fn command_uses_legend_one_row(id: &str, params: &Value) -> bool { match id { "layout.addElement" | "layout.update" => matches!(crate::cmd::layout::legend_one_row_param(params), Ok(Some(true))), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"one_row\""], legend_in_one_row), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_lays_a_legend_in_one_row), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_lays_a_legend_in_one_row(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_one_row)), _ => false, } } -/// Whether a project's saved text requires `layout-legend-one-row`: for its layouts, its steps -/// or its notebooks. Parsed only when the text names the key, either way it -/// is written, may hide it ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_lays_a_legend_in_one_row(text: &str) -> bool { - (["one_row", "oneRow"].iter().any(|key| text.contains(key)) || may_hide_a_key(text) || names_data(text)) - && inline_project_requires(text, "layout-legend-one-row") == Some(true) -} - /// Whether a project given as text requires `capability` for what it holds as written; `None` /// for text that isn't a project. Read without repair, so asking reads nothing the text names (#3530), /// and what loading it would cut still counts. @@ -831,24 +968,11 @@ fn command_uses_legend_patch_size(id: &str, params: &Value) -> bool { "layout.import" | "report.existingTemplate" => { imported_layout_uses(id, params, &["\"patch_width\"", "\"patch_height\""], legend_patch_features) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_gives_legend_patch_size), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_legend_patch_size(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_patch_size)), _ => false, } } -/// Whether a project's saved text requires `layout-legend-patch-size`: for its layouts, its steps -/// or its notebooks. Parsed only when the text names a key, either way it is written, may hide it -/// ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_gives_legend_patch_size(text: &str) -> bool { - (["patch_width", "patchWidth", "patch_height", "patchHeight"].iter().any(|key| text.contains(key)) - || may_hide_a_key(text) - || names_data(text)) - && inline_project_requires(text, "layout-legend-patch-size") == Some(true) -} - /// Whether a layout element is a legend whose patches aren't at the default size. fn legend_patch_features(e: &rustgis_map::layout::Element) -> bool { e.kind.legend_patch_features() @@ -882,22 +1006,11 @@ fn command_numbers_extents(id: &str, params: &Value) -> bool { match id { "layout.update" => params.get("extentNumbers") == Some(&Value::Bool(true)), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"extent_numbers\""], extent_numbers_features), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_numbers_extents), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_numbers_extents(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_numbers_extents)), _ => false, } } -/// Whether a project's saved text requires `layout-extent-numbers`: for its frames, its steps -/// or its notebooks. Parsed only when the text names the key, either way it -/// is written, may hide it ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_numbers_extents(text: &str) -> bool { - (["extent_numbers", "extentNumbers"].iter().any(|key| text.contains(key)) || may_hide_a_key(text) || names_data(text)) - && inline_project_requires(text, "layout-extent-numbers") == Some(true) -} - /// Whether a layout element is a map frame that numbers its extent indicators. fn extent_numbers_features(e: &rustgis_map::layout::Element) -> bool { e.kind.numbers_extents() @@ -1403,23 +1516,11 @@ fn command_uses_north_arrow_font(id: &str, params: &Value) -> bool { match id { "layout.addElement" => adds_with_font(params, "northArrow"), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"font"], north_arrows_with_font), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-north-arrow-font")), - "project.fromTemplate" => { - crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_font(&t, "layout-north-arrow-font")) - } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_north_arrow_font)), _ => false, } } -/// Whether a project's saved text requires the font `capability`: for its elements, its steps -/// or its notebooks. Parsed only when the text may name a font, may -/// hide the key ([`may_hide_a_key`]) or holds a step's base64 `data` ([`names_data`]). -fn text_gives_font(text: &str, capability: &str) -> bool { - (text.contains("font") || may_hide_a_key(text) || names_data(text)) && inline_project_requires(text, capability) == Some(true) -} - fn scale_bars_with_font(e: &rustgis_map::layout::Element) -> bool { e.kind.scale_bar_uses_font() } @@ -1430,10 +1531,6 @@ fn command_uses_scale_bar_font(id: &str, params: &Value) -> bool { match id { "layout.addElement" => adds_with_font(params, "scaleBar"), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"font"], scale_bars_with_font), - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-scale-bar-font")), - "project.fromTemplate" => { - crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_font(&t, "layout-scale-bar-font")) - } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_scale_bar_font)), _ => false, } @@ -1483,11 +1580,19 @@ fn imported_layout_text<'a>(id: &str, params: &'a Value) -> Option> /// Require only executable payloads being saved: graph files omit steps, web tools omit graphs. pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> { - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, uses).then_some(name)).collect() + let mut required: Vec<&'static str> = + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, &uses).then_some(name)).collect(); + let (opened, reads) = (RefCell::new(Vec::new()), OpenedReads::default()); + model_uses(steps, graph, &|id: &str, params: &Value| { + collect_opened_project(&opened, &reads, 0, id, params); + false + }); + merge_opened(&mut required, opened); + required } /// Traverse executable model nodes with the same predicate used for project commands. -fn model_uses(steps: &[ModelStep], graph: Option<&ModelGraph>, uses: CommandCheck) -> bool { +fn model_uses(steps: &[ModelStep], graph: Option<&ModelGraph>, uses: &impl Fn(&str, &Value) -> bool) -> bool { steps.iter().any(|s| uses(&s.tool, &s.params)) || graph.is_some_and(|g| g.nodes.iter().any(|n| n.kind == ModelNodeKind::Tool && uses(n.tool.as_deref().unwrap_or(""), &n.params))) } @@ -2147,6 +2252,263 @@ mod tests { use super::*; use serde_json::{Value, json}; + /// Whether a saved step `id` with `params` requires `capability`, as a saved model's step does. + fn requires(capability: &str, id: &str, params: Value) -> bool { + model_capabilities(&[ModelStep { tool: id.into(), params }], None).contains(&capability) + } + + /// The same text opened by several steps at one depth is read once, however many steps open it: + /// a zip of the same template repeated costs next to nothing to store, so a few steps opening + /// it at each level would otherwise be read once per way down. + #[test] + fn a_text_opened_by_several_steps_is_read_once() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let step = |id: &str| json!({"title": "Open", "command": id, "params": {"text": text}}); + let mut inner = serde_json::to_value(Project::default()).unwrap(); + inner["tasks"] = json!([{"name": "Twice", "steps": [step("project.openText"), step("project.fromTemplate")]}]); + let mut outer = serde_json::to_value(Project::default()).unwrap(); + let open = |text: &Value| json!({"title": "Open", "command": "project.openText", "params": {"text": text.to_string()}}); + outer["tasks"] = json!([{"name": "Again", "steps": [open(&inner), open(&inner), open(&inner)]}]); + let outer = Project::from_peer_raw(&outer.to_string()).unwrap(); + let reads = OpenedReads::default(); + assert_eq!(outer.required_capabilities_at(0, &reads), ["layout-extent-indicators"]); + // One entry for each text read: the inner project once, and the template once inside it. + let read: usize = reads.read.borrow().values().map(|texts| texts.len()).sum(); + assert_eq!(read, 2); + } + + /// The walk of these two commands reads a project down to [`MAX_OPENED_DEPTH`] levels; at that + /// depth a step that opens a text requires everything a release knows, so an older one refuses + /// it rather than drop what it can't see, and a step that opens nothing requires nothing. + /// Called at a chosen depth: a chain of `text` projects can't be built that deep (each level + /// escapes the one inside it), and one of base64 zips is the case the limit is for. + #[test] + fn the_walk_of_opened_projects_requires_everything_at_its_depth() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let at = |depth: usize, id: &str, params: &Value| { + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, &OpenedReads::default(), depth, id, params); + found.into_inner() + }; + let opens = json!({"text": text}); + assert_eq!(at(0, "project.openText", &opens), ["layout-extent-indicators"]); + assert_eq!(at(MAX_OPENED_DEPTH - 1, "project.openText", &opens), ["layout-extent-indicators"]); + for (id, params) in + [("project.openText", &opens), ("project.fromTemplate", &opens), ("project.openText", &json!({"text": "not a project"}))] + { + let mut all = at(MAX_OPENED_DEPTH, id, params); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "{id}"); + } + assert!(at(MAX_OPENED_DEPTH, "project.openText", &json!({})).is_empty(), "no text, nothing opened"); + assert!(at(MAX_OPENED_DEPTH, "layer.remove", &opens).is_empty(), "another command"); + } + + /// What a saved project requires is a function of the project alone: the same on a computer + /// with a small memory as on one with a large one, so the bytes a walk may read can't follow + /// [`crate::project::max_bytes`]. + #[test] + fn what_a_walk_requires_does_not_follow_the_memory_of_the_computer() { + let project = |name: &str| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = name.into(); + project.saved_text(None).unwrap().0 + }; + let (first, second) = (project("first"), project("second")); + let step = |text: &String| crate::project::TaskStep { + title: "Open".into(), + instructions: String::new(), + command: "project.openText".into(), + params: json!({"text": text}), + }; + let tasks = + vec![crate::project::Task { name: "Open".into(), description: String::new(), steps: vec![step(&first), step(&second)] }]; + let outer = Project { tasks, ..Project::default() }; + // A computer whose projects may hold hardly more than the first text: both are read all the same. + let small = crate::project::with_max_bytes(first.len() as u64 + 10, || outer.required_capabilities()); + assert_eq!(small, outer.required_capabilities()); + assert_eq!(small, ["layout-extent-indicators"]); + } + + /// A template that this computer's limit for a file ([`crate::project::max_bytes`]) refuses is + /// still read: what a project requires can't depend on the computer that saves it, so the limit + /// of a walk is its own budget. + #[test] + fn a_template_over_the_limit_of_this_computer_is_read_all_the_same() { + use base64::Engine; + // A text whose length isn't a multiple of 3, so that its base64 is longer than three + // quarters of a limit the size of the text. + let (text, _) = (0..4) + .map(|pad| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = "p".repeat(pad + 1); + project.saved_text(None).unwrap() + }) + .find(|(text, _)| text.len() % 3 != 0) + .unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(&text); + let at = |max: Option| { + let read = || { + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, &OpenedReads::default(), 0, "project.fromTemplate", &json!({"data": data})); + found.into_inner() + }; + max.map_or_else(read, |max| crate::project::with_max_bytes(max, read)) + }; + assert_eq!(at(None), ["layout-extent-indicators"]); + assert_eq!(at(Some(text.len() as u64)), ["layout-extent-indicators"]); + } + + /// A chain of projects each opening the next from base64 `data`, one more than the walk reads, + /// is read down to the depth limit on a thread with the stack of Windows' main one (1 MiB): a + /// stack overflow aborts the process, and nothing catches it. The walk has a budget no chain + /// reaches, so that it is the depth that stops it (a chain this long is more bytes than the + /// fixed budget). + #[test] + fn the_deepest_chain_of_opened_projects_fits_a_small_stack() { + use base64::Engine; + let (mut text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + for _ in 0..=MAX_OPENED_DEPTH { + let data = base64::engine::general_purpose::STANDARD.encode(&text); + let step = json!({"title": "Open", "command": "project.fromTemplate", "params": {"data": data}}); + text = with_tasks(json!([{"name": "Open", "steps": [step]}])); + } + let outer = Project::from_peer_raw(&text).unwrap(); + let (required, depths) = std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let reads = OpenedReads::with_budget(u64::MAX); + let required = outer.required_capabilities_at(0, &reads); + (required, reads.read.borrow().len()) + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(depths, MAX_OPENED_DEPTH, "a text read at each depth, down to the limit"); + let mut required = required; + required.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(required, known, "past the depth limit a step requires everything"); + } + + /// What the walk asks of a zip doesn't change what the other readers of `inline_text` take: a + /// package inflates up to `zip::MAX_TOTAL` whatever the limit of this computer for a file. + #[test] + fn inline_text_still_inflates_a_package_up_to_the_zip_limit() { + use base64::Engine; + let project = Project { name: "x".repeat(200_000), ..Project::default() }; + let (text, _) = project.clone().saved_text(None).unwrap(); + let zip = rustgis_data::zip::write(&[("p.rgis".to_string(), text.clone().into_bytes())]).unwrap(); + let params = json!({"data": base64::engine::general_purpose::STANDARD.encode(zip)}); + let read = crate::project::with_max_bytes(100_000, || crate::cmd::items::inline_text(¶ms).map(|t| t.map(|t| t.len()))); + assert_eq!(read, Ok(Some(text.len()))); + } + + /// A zip is inflated only within the budget, not up to the 1 GiB a package may hold: a template + /// that inflates past it is refused as it is read, which the walk takes as one it can't decode. + #[test] + fn a_zipped_template_is_inflated_only_within_the_budget() { + use base64::Engine; + let mut project = Project { name: "x".repeat(200_000), ..Project::default() }; + let (text, _) = project.saved_text(None).unwrap(); + let zip = rustgis_data::zip::write(&[("p.rgis".to_string(), text.clone().into_bytes())]).unwrap(); + let params = json!({"data": base64::engine::general_purpose::STANDARD.encode(zip)}); + assert!(params["data"].as_str().unwrap().len() < 10_000, "it is small zipped"); + let within = |limit: u64| { + crate::cmd::items::inline_text_within(¶ms, limit, usize::try_from(limit).unwrap_or(usize::MAX)).map(|t| t.map(|t| t.len())) + }; + assert_eq!(within(1 << 30), Ok(Some(text.len()))); + assert!(within(100_000).is_err(), "it inflates past the budget"); + } + + /// A walk reads as many bytes of opened texts as its budget and no more: past that a step that + /// opens a text requires everything, as at the depth limit, so a chain of templates that each + /// inflate to a gigabyte can't make a save read them all. + #[test] + fn a_walk_reads_only_so_many_bytes() { + let project = |name: &str| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = name.into(); + project.saved_text(None).unwrap().0 + }; + let (first, second) = (project("first"), project("second")); + let (seen, found) = (OpenedReads::with_budget(first.len() as u64 + 10), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "past it"); + } + + /// A text longer than the whole budget requires everything without being hashed, or read, or + /// kept: its answer is known, and a hash of a gigabyte would cost more than the walk is meant to. + #[test] + fn a_text_longer_than_the_budget_is_not_even_hashed() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let (reads, found) = (OpenedReads::with_budget(text.len() as u64 - 1), RefCell::new(Vec::new())); + collect_opened_project(&found, &reads, 0, "project.openText", &json!({"text": text})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "it requires everything"); + assert!(reads.read.borrow().is_empty(), "and nothing was hashed or kept"); + assert_eq!(reads.bytes.get(), 0, "nor counted"); + } + + /// Once the budget of bytes is spent, a `data` template isn't decoded at all: the count of bytes + /// read stays where it was, and the step requires everything. + #[test] + fn a_walk_that_has_spent_its_bytes_decodes_no_more() { + use base64::Engine; + let (first, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let (seen, found) = (OpenedReads::with_budget(first.len() as u64), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + let spent = seen.bytes.get(); + let data = base64::engine::general_purpose::STANDARD.encode(&first); + collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": data})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "the step requires everything"); + assert_eq!(seen.bytes.get(), spent, "and nothing was decoded"); + } + + /// What a walk keeps of the texts it has read is a digest of where each came from, never the + /// decoded text: a template that inflates to a gigabyte would be held until the walk ends. + #[test] + fn a_walk_keeps_no_text_it_has_read() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let seen = OpenedReads::default(); + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": text})); + let kept: Vec<(usize, String)> = + seen.read.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.clone()))).collect(); + let digest = rustgis_plugins::package::sha256_hex(text.as_bytes()); + assert_eq!(kept, [(0, format!("text:{digest}"))], "one entry: where the text came from and its SHA-256, not the text"); + } + + /// The text of an empty project holding `tasks`. + fn with_tasks(tasks: Value) -> String { + let mut project = serde_json::to_value(Project::default()).unwrap(); + project["tasks"] = tasks; + project.to_string() + } + /// The one-row check of a step that opens an inline project asks only what that project /// needs: a raster it names, read in place from a server, is never asked for. #[test] @@ -2163,8 +2525,8 @@ mod tests { crate::render::rustgis_tiles::cache::allow_named(&scene); s.wait_in_place_reads(); while listener.accept().is_ok() {} - assert!(command_uses_legend_one_row("project.openText", &json!({"text": text}))); - assert!(command_uses_legend_one_row("project.fromTemplate", &json!({"text": text}))); + assert!(requires("layout-legend-one-row", "project.openText", json!({"text": text}))); + assert!(requires("layout-legend-one-row", "project.fromTemplate", json!({"text": text}))); for _ in 0..20 { let nothing = listener.accept().err().map(|e| e.kind()); assert_eq!(nothing, Some(std::io::ErrorKind::WouldBlock), "the raster was read"); @@ -2179,7 +2541,7 @@ mod tests { let opens = |params: Value| { let mut project = serde_json::to_value(Project::default()).unwrap(); project["tasks"] = json!([{"name": "Size", "steps": [{"title": "Size", "command": "layout.update", "params": params}]}]); - command_uses_legend_patch_size("project.openText", &json!({"text": project.to_string()})) + requires("layout-legend-patch-size", "project.openText", json!({"text": project.to_string()})) }; assert!(opens(json!({"element": 1, "patchWidth": 20}))); assert!(opens(json!({"element": 1, "patchHeight": 12}))); @@ -2226,20 +2588,20 @@ mod tests { s.project } - /// Asking what a step that opens an inline project needs reads nothing that project names, - /// as saved, without its header, from a script and from a step of a step (#3530). + /// What a step that opens an inline project requires is asked without reading anything that + /// project names, as saved, without its header, from a script and from a step of a step (#3530). #[test] - fn the_checks_of_an_inline_project_read_nothing_it_names() { - let checks: [(&str, CommandCheck); 6] = [ - ("label-obstacles", command_sets_obstacles), - ("shaded-relief-generalize", command_sets_generalize), - ("layout-legend-patch-size", command_uses_legend_patch_size), - ("layout-extent-numbers", command_numbers_extents), - ("layout-north-arrow-font", command_uses_north_arrow_font), - ("layout-scale-bar-font", command_uses_scale_bar_font), + fn asking_what_an_inline_project_needs_reads_nothing_it_names() { + let checks = [ + "label-obstacles", + "shaded-relief-generalize", + "layout-legend-patch-size", + "layout-extent-numbers", + "layout-north-arrow-font", + "layout-scale-bar-font", ]; let mut listeners = Vec::new(); - for (capability, check) in checks { + for capability in checks { for wanted in [true, false] { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); @@ -2255,12 +2617,12 @@ mod tests { crate::Session::new(project).wait_in_place_reads(); while listener.accept().is_ok() {} for text in [saved.clone(), headerless.to_string(), outer.to_string()] { - assert_eq!(check("project.openText", &json!({"text": text})), wanted, "{capability}"); - assert_eq!(check("project.fromTemplate", &json!({"text": text})), wanted, "{capability} in a template"); + assert_eq!(requires(capability, "project.openText", json!({"text": text})), wanted, "{capability}"); + assert_eq!(requires(capability, "project.fromTemplate", json!({"text": text})), wanted, "{capability} in a template"); let script = format!("project.openText {}", json!({"text": text})); - assert_eq!(check("script.run", &json!({"script": script})), wanted, "{capability} in a script"); + assert_eq!(requires(capability, "script.run", json!({"script": script})), wanted, "{capability} in a script"); } - assert!(!check("project.openText", &json!({"text": "{\"maps\": \"font generalize extent_numbers\""}))); + assert!(!requires(capability, "project.openText", json!({"text": "{\"maps\": \"font generalize extent_numbers\""}))); listeners.push((capability, wanted, listener)); } } @@ -2286,7 +2648,7 @@ mod tests { layouts.push(with_font); text["layouts"] = Value::Array(layouts); assert_eq!(Project::from_json(&text.to_string()).unwrap().layouts.len(), crate::project::MAX_LAYOUTS, "loading cuts it"); - assert!(command_uses_north_arrow_font("project.openText", &json!({"text": text.to_string()}))); + assert!(requires("layout-north-arrow-font", "project.openText", json!({"text": text.to_string()}))); } /// A coordinate system saved with its WKT requires `crs-wkt` only when its PROJ definition, @@ -2629,8 +2991,6 @@ mod tests { (&["dggs-system"], "a5Aggregate", json!({"system": "S2"})), (&["label-weight"], "labels.placement", json!({"weight": 9})), (&["label-obstacles"], "labels.placement", json!({"obstacleWeight": 9})), - // A template opened from text holds a project too. - (&["label-obstacles"], "project.fromTemplate", json!({"text": include_str!("../../../schema/fixtures/label_obstacles.rgis")})), (&["unique-keep-order"], "style.add", json!({"text": kept_order_style()})), (&["label-clearance"], "labels.placement", json!({"clearance": 9})), (&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})), @@ -2704,7 +3064,7 @@ mod tests { for (capability, id, params) in samples { let step = [ModelStep { tool: id.into(), params: params.clone() }]; let names: Vec<&str> = - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(&step, None, uses).then_some(name)).collect(); + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(&step, None, &uses).then_some(name)).collect(); assert_eq!(names, capability, "the sample {id} {params} requires exactly its own capability"); covered.extend(capability.iter().copied()); for (index, saved) in saved_requires_of_inline_graph(&graph_of_one_tool(id, params.clone())).into_iter().enumerate() { @@ -2799,20 +3159,18 @@ mod tests { use base64::Engine; let data = base64::engine::general_purpose::STANDARD.encode(kept_order_style()); let step = json!({"title": "C:\\styles", "command": "style.add", "params": {"data": data}}); - let text = json!({"tasks": [{"name": "Add", "steps": [step]}]}).to_string(); + let text = with_tasks(json!([{"name": "Add", "steps": [step]}])); assert!(!text.contains("keep_order") && !may_hide_a_key(&text), "{text}"); let needs = |text: &str| model_capabilities(&[ModelStep { tool: "project.openText".into(), params: json!({"text": text}) }], None); assert_eq!(needs(&text), ["unique-keep-order"]); // Nested as a string inside another project's step, its `data` key is escaped. let outer = - json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) - .to_string(); + with_tasks(json!([{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}])); assert!(!outer.contains("keep_order"), "{outer}"); assert_eq!(needs(&outer), ["unique-keep-order"]); // Two levels deeper still, its `data` key is escaped seven backslashes deep. let open = |text: &str| { - json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) - .to_string() + with_tasks(json!([{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}])) }; let deepest = open(&open(&outer)); assert!(!deepest.contains("keep_order") && !deepest.contains("data\\\\\\\"") && names_data(&deepest), "{deepest}"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 40e499f3f5..9c4d0d434f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -220,6 +220,10 @@ mod layout_colorbar; #[path = "tests/layout_open.rs"] mod layout_open; +/// A saved step that opens a project from its text (#3462, #3476). +#[path = "tests/capabilities_inline_project.rs"] +mod capabilities_inline_project; + /// A north arrow's font (#3467). #[path = "tests/layout_north_font.rs"] mod layout_north_font; diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs new file mode 100644 index 0000000000..d2ceb35409 --- /dev/null +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -0,0 +1,95 @@ +//! A saved step that opens a project from its text requires what that project requires (#3462, +//! #3476). + +use super::*; +use crate::project::{ModelStep, TaskStep, model_capabilities, task_capabilities}; +use base64::Engine; + +/// Every project fixture with a `requires` header: its text without the header, and the +/// capabilities the header names. +fn fixtures() -> Vec<(String, String, Vec)> { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schema/fixtures"); + let mut found = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + if !name.ends_with(".rgis") { + continue; + } + let mut project: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + let requires: Vec = project + .as_object_mut() + .and_then(|o| o.remove("requires")) + .map(|r| serde_json::from_value(r).unwrap_or_else(|e| panic!("{name}: {e}"))) + .unwrap_or_default(); + if !requires.is_empty() { + found.push((name, project.to_string(), requires)); + } + } + // Most fixtures carry a header; none found means the folder wasn't read. + assert!(!found.is_empty(), "the fixtures were not found"); + found +} + +/// The four places a saved step is read: a recorded model step, a task's step, a line of a script +/// and a project holding the task. Each answers what the step requires. +fn needs(id: &str, params: Value) -> [Vec; 4] { + let own = |v: Vec<&'static str>| v.into_iter().map(String::from).collect::>(); + let line = format!("{id} {params}"); + let step = + |command: &str, params: Value| TaskStep { title: "Open".into(), instructions: String::new(), command: command.into(), params }; + let mut in_a_task = Project::default(); + in_a_task.tasks = vec![crate::project::Task { name: "Open".into(), description: String::new(), steps: vec![step(id, params.clone())] }]; + [ + own(model_capabilities(&[ModelStep { tool: id.into(), params: params.clone() }], None)), + own(task_capabilities(&[step(id, params)])), + own(model_capabilities(&[ModelStep { tool: "script.run".into(), params: json!({"script": line}) }], None)), + own(in_a_task.required_capabilities()), + ] +} + +/// Opening a project from its text asks for exactly the capabilities the project asks for: the layout +/// ones, and the rest, whichever fixture it is. +#[test] +fn opening_a_project_from_its_text_requires_what_it_requires() { + for (name, text, requires) in fixtures() { + // A template is given by its `text` or by its base64 `data`; opening reads `text` only. + let data = base64::engine::general_purpose::STANDARD.encode(&text); + for (id, params) in [ + ("project.openText", json!({"text": text})), + ("project.fromTemplate", json!({"text": text})), + ("project.fromTemplate", json!({"data": data})), + ] { + for (place, mut found) in ["a model step", "a task", "a script", "a project's task"].iter().zip(needs(id, params.clone())) { + found.sort(); + found.dedup(); + let mut wanted = requires.clone(); + wanted.sort(); + assert_eq!(found, wanted, "{id} {params:.60} of {name} in {place}"); + } + } + } +} + +/// #3462: several extent indicators in a frame, without a header on the opened project. +#[test] +fn an_opened_project_with_several_extent_indicators_requires_them() { + let (_, text, _) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); + assert!(text.contains("more_extents")); + for found in needs("project.openText", json!({"text": text})) { + assert!(found.contains(&"layout-extent-indicators".to_string()), "{found:?}"); + } +} + +/// A project with nothing new in it, and text that is no project, ask for nothing. +#[test] +fn a_project_with_nothing_new_requires_nothing() { + let plain = Project::default().saved_text(None).unwrap().0; + for text in [plain.as_str(), "not a project", "{\"maps\": 1}", ""] { + for id in ["project.openText", "project.fromTemplate"] { + for found in needs(id, json!({"text": text})) { + assert!(found.is_empty(), "{id} of {text:?}: {found:?}"); + } + } + } +}