diff --git a/crates/engine/src/cmd/notebook.rs b/crates/engine/src/cmd/notebook.rs index 4719d46197..bec4d54469 100644 --- a/crates/engine/src/cmd/notebook.rs +++ b/crates/engine/src/cmd/notebook.rs @@ -483,7 +483,7 @@ fn jupyter_outputs(outputs: &[Value]) -> (String, bool) { } /// A RustGIS or Jupyter notebook. -fn parse(text: &str, fallback_name: &str) -> Result { +pub(crate) fn parse(text: &str, fallback_name: &str) -> Result { let v: Value = serde_json::from_str(text).map_err(|e| format!("not a notebook: {e}"))?; // Jupyter notebooks must be nbformat 4: older ones keep cells in worksheets and newer ones // may hold structure RustGIS would lose on save. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9bf09c981e..3c7384ac9b 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -104,7 +104,8 @@ impl Project { let commands: Vec<&'static str> = 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). + // And what a project, model, task or notebook 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); @@ -186,11 +187,11 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> 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. +/// What a walk has read of the documents that saved steps open: what each text required, by depth +/// and then the kind of document and 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 a short key, 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, @@ -217,14 +218,88 @@ impl OpenedReads { /// 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. +/// How many documents deep what a saved step opens 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. +/// What a step opens from its text. +#[derive(Clone, Copy, Debug)] +enum Opened { + Project, + Model, + Task, + Notebook, +} + +/// What the document in `text`, opened `depth` levels down, requires: +/// - a project, read without repair ([`Project::from_peer_raw`]) so that what loading it would +/// cut still counts; +/// - a model or web tool that `model.import` takes ([`crate::model::check_file`]): what the +/// `model.new` it runs requires for that graph or those steps; +/// - a task that `task.import` reads ([`crate::project::check_format`]): what its steps require; +/// - a notebook whose code cells are commands: what their lines require. +fn opened_capabilities(kind: Opened, text: &str, depth: usize, reads: &OpenedReads) -> Vec<&'static str> { + match kind { + Opened::Project => Project::from_peer_raw(text).map(|project| project.required_capabilities_at(depth, reads)).unwrap_or_default(), + // The whole file stands for `model.new`'s params: `check_file` refuses one holding both a + // `graph` and `steps`, so it is read for the one the command would pass. + Opened::Model => serde_json::from_str::(text) + .ok() + .filter(|file| crate::model::check_file(file).is_ok()) + .map(|file| commands_capabilities(std::iter::once(("model.new".to_string(), file)), depth, reads)) + .unwrap_or_default(), + Opened::Task => crate::project::check_format(text, "task") + .and_then(|()| serde_json::from_str::(text).map_err(|e| e.to_string())) + .map(|task| commands_capabilities(task.steps.into_iter().map(|step| (step.command, step.params)), depth, reads)) + .unwrap_or_default(), + Opened::Notebook => crate::cmd::notebook::parse(text, "Notebook") + .ok() + .filter(|notebook| notebook.language().is_none()) + .map(|notebook| { + let lines = notebook + .cells + .iter() + .filter(|cell| cell.kind == crate::cmd::notebook::CellKind::Code) + .flat_map(|cell| cell.source.lines().take(crate::cmd::workflows::MAX_SCRIPT_LINES)) + .filter_map(|line| crate::script_line(line)?.ok()); + commands_capabilities(lines, depth, reads) + }) + .unwrap_or_default(), + } +} + +/// What `commands` require, with what the documents they open require, `depth` levels down. One +/// command is held at a time and parsed once, not once for each check, and a capability already +/// found isn't asked for again. +fn commands_capabilities(commands: impl Iterator, depth: usize, reads: &OpenedReads) -> Vec<&'static str> { + let mut required: Vec<&'static str> = Vec::new(); + let opened = RefCell::new(Vec::new()); + for (id, params) in commands { + for &(name, uses) in COMMAND_CAPABILITIES { + if !required.contains(&name) && command_uses(&uses, &id, ¶ms) { + required.push(name); + } + } + if !required.contains(&"table-export-order") && command_uses_table_export_order(&id, ¶ms) { + required.push("table-export-order"); + } + command_uses( + &|id: &str, params: &Value| { + collect_opened_project(&opened, reads, depth, id, params); + false + }, + &id, + ¶ms, + ); + } + merge_opened(&mut required, opened); + required +} + +/// Adds to `found` what the document that a step opens from its text requires (#3462, #3476): the +/// text of `project.openText`, or the `data` else the `text` of `project.fromTemplate`, +/// `model.import`, `task.import` and `notebook.open`, as those commands read it +/// ([`opened_capabilities`]), and so on down the documents its own steps open, `script.run` lines +/// included. Text that isn't what the command reads 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 @@ -238,16 +313,22 @@ const MAX_OPENED_DEPTH: usize = 32; /// 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. +/// opened texts (about a quarter of a second at the limit for a project's structure), on each save +/// that calls it. A notebook full of command lines costs more, as every check is asked of every +/// line: 19 MB of them took 1.5 s in an unoptimized build (a project holding the same cells, 10 s). 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")), - }, + // else the step holds; the others their `data` before their `text`. + let data_else_text = || match crate::cmd::ps(params, "data") { + Some(data) => ("data", Some(data)), + None => ("text", crate::cmd::ps(params, "text")), + }; + let (kind, (tag, source)) = match id { + "project.openText" => (Opened::Project, ("text", crate::cmd::ps(params, "text"))), + "project.fromTemplate" => (Opened::Project, data_else_text()), + "model.import" => (Opened::Model, data_else_text()), + "task.import" => (Opened::Task, data_else_text()), + "notebook.open" => (Opened::Notebook, data_else_text()), "script.run" => { if let Some(script) = params.get("script").and_then(Value::as_str) { script_uses(script, |id, params| { @@ -266,7 +347,8 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead 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())); + // The same text is another document to another command, so the kind is part of the key. + let digest = format!("{kind:?}:{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(|| { @@ -288,9 +370,7 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead 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() + text.map(|text| opened_capabilities(kind, &text, depth + 1, reads)).unwrap_or_default() }; reads.read.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); names @@ -2308,6 +2388,39 @@ mod tests { assert!(at(MAX_OPENED_DEPTH, "layer.remove", &opens).is_empty(), "another command"); } + /// A model, a task or a notebook counts a level as a project does: at the depth limit, or past the + /// budget, a step that gives one requires everything, without reading it. + #[test] + fn the_walk_of_opened_models_and_notebooks_shares_the_limits() { + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + let everything = |depth: usize, reads: &OpenedReads, id: &str| { + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, reads, depth, id, &json!({"text": "{}"})); + let mut found = found.into_inner(); + found.sort_unstable(); + assert_eq!(found, known, "{id}"); + }; + for id in ["model.import", "task.import", "notebook.open"] { + everything(MAX_OPENED_DEPTH, &OpenedReads::default(), id); + let reads = OpenedReads::with_budget(1); + everything(0, &reads, id); + assert_eq!(reads.bytes.get(), 0, "{id}: not even counted"); + } + } + + /// The same text read as a notebook and as a project requires what each reading requires. + #[test] + fn a_text_read_as_two_kinds_of_document_is_read_as_each() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let (reads, found) = (OpenedReads::default(), RefCell::new(Vec::new())); + collect_opened_project(&found, &reads, 0, "notebook.open", &json!({"text": text})); + assert!(found.take().is_empty(), "as a notebook it holds no command"); + collect_opened_project(&found, &reads, 0, "project.openText", &json!({"text": text})); + assert_eq!(found.take(), ["layout-extent-indicators"]); + } + /// 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`]. @@ -2499,7 +2612,7 @@ mod tests { 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"); + assert_eq!(kept, [(0, format!("Project:text:{digest}"))], "one entry: where the text came from and its SHA-256, not the text"); } /// The text of an empty project holding `tasks`. diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs index d2ceb35409..cd4c192287 100644 --- a/crates/engine/src/tests/capabilities_inline_project.rs +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -1,5 +1,5 @@ -//! A saved step that opens a project from its text requires what that project requires (#3462, -//! #3476). +//! A saved step that opens a project, a model, a task or a notebook from its text requires +//! what that document requires (#3462, #3476). use super::*; use crate::project::{ModelStep, TaskStep, model_capabilities, task_capabilities}; @@ -31,6 +31,8 @@ fn fixtures() -> Vec<(String, String, Vec)> { found } +const PLACES: [&str; 4] = ["a model step", "a task", "a script", "a project's task"]; + /// 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] { @@ -60,7 +62,7 @@ fn opening_a_project_from_its_text_requires_what_it_requires() { ("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())) { + for (place, mut found) in PLACES.iter().zip(needs(id, params.clone())) { found.sort(); found.dedup(); let mut wanted = requires.clone(); @@ -93,3 +95,164 @@ fn a_project_with_nothing_new_requires_nothing() { } } } + +/// Percent slope, which `slope-percent` is required for. +fn percent_slope() -> Value { + json!({"function": "slope", "units": "percent"}) +} + +/// A model file holding a graph with one tool node. +fn model_file(params: Value) -> String { + json!({"$schema": crate::model::SCHEMA, "version": "1.0.0", "name": "Slope", + "graph": {"nodes": [{"id": "n1", "kind": "tool", "tool": "raster.function", "params": params}], "edges": []}}) + .to_string() +} + +/// A web tool holding its steps. +fn web_tool_file(params: Value) -> String { + json!({"format": "RustGIS web tool", "version": 1, "name": "Slope", "steps": [{"tool": "raster.function", "params": params}]}) + .to_string() +} + +/// A command line that adds a colorbar with a text size, which `layout-colorbar-labels` is +/// required for. +fn colorbar_line() -> String { + format!("layout.addElement {}", json!({"kind": "colorbar", "textSize": 12})) +} + +fn notebook_file(kind: &str, source: &str) -> String { + json!({"name": "N", "cells": [{"kind": kind, "source": source}]}).to_string() +} + +fn jupyter_file(language: &str, source: &str) -> String { + json!({"nbformat": 4, "nbformat_minor": 5, "metadata": {"kernelspec": {"name": language, "language": language}}, + "cells": [{"cell_type": "code", "source": source}]}) + .to_string() +} + +fn encoded(text: &str) -> String { + base64::engine::general_purpose::STANDARD.encode(text) +} + +fn assert_all_need(id: &str, params: Value, capability: &str) { + for (place, found) in PLACES.iter().zip(needs(id, params.clone())) { + assert!(found.iter().any(|f| f == capability), "{id} {params:.80} in {place}: {found:?}"); + } +} + +fn assert_none_needs(id: &str, params: Value) { + for (place, found) in PLACES.iter().zip(needs(id, params.clone())) { + assert!(found.is_empty(), "{id} {params:.80} in {place}: {found:?}"); + } +} + +/// #3476: importing a model or a web tool from its text requires what its steps require. +#[test] +fn a_saved_model_import_requires_what_its_model_requires() { + for text in [model_file(percent_slope()), web_tool_file(percent_slope())] { + assert_all_need("model.import", json!({"text": text}), "slope-percent"); + assert_all_need("model.import", json!({"data": encoded(&text)}), "slope-percent"); + // `data` is read before `text`, as the command reads them. + assert_all_need("model.import", json!({"data": encoded(&text), "text": "other"}), "slope-percent"); + } + assert_none_needs("model.import", json!({"text": model_file(json!({"function": "slope"}))})); +} + +/// A text `model.import` refuses, and a `path`, whose file has its own header, require nothing. +#[test] +fn a_model_import_that_imports_nothing_requires_nothing() { + let mut newer: Value = serde_json::from_str(&model_file(percent_slope())).unwrap(); + newer["version"] = json!("9.0.0"); + let mut extra: Value = serde_json::from_str(&web_tool_file(percent_slope())).unwrap(); + extra["surprise"] = json!(true); + for params in [ + json!({"text": "not a model"}), + json!({"text": newer.to_string()}), + json!({"text": extra.to_string()}), + json!({"path": "slope.model.json"}), + ] { + assert_none_needs("model.import", params); + } +} + +/// #3476: opening a notebook from its text requires what its command cells require. +#[test] +fn a_saved_notebook_open_requires_what_its_cells_require() { + let line = colorbar_line(); + for text in [notebook_file("code", &line), jupyter_file("rustgis", &line)] { + assert_all_need("notebook.open", json!({"text": text}), "layout-colorbar-labels"); + assert_all_need("notebook.open", json!({"data": encoded(&text)}), "layout-colorbar-labels"); + } + // A project opened by a cell is read as one opened by a step. + let (_, project, requires) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); + let open = notebook_file("code", &format!("project.openText {}", json!({"text": project}))); + for capability in &requires { + assert_all_need("notebook.open", json!({"text": open}), capability); + } +} + +/// Text cells, another language's cells, a text that is no notebook and a `path` require nothing. +#[test] +fn a_notebook_open_that_runs_no_command_requires_nothing() { + let line = colorbar_line(); + for params in [ + json!({"text": notebook_file("markdown", &line)}), + json!({"text": jupyter_file("python", &line)}), + json!({"text": "not a notebook"}), + json!({"path": "n.rgisnb"}), + ] { + assert_none_needs("notebook.open", params); + } +} + +/// A task file with one step. +fn task_file(command: &str, params: Value) -> String { + json!({"name": "T", "description": "", "steps": [{"title": "S", "instructions": "", "command": command, "params": params}]}).to_string() +} + +/// #3476: importing a task from its text requires what its steps require, and what the documents +/// they open require. +#[test] +fn a_saved_task_import_requires_what_its_steps_require() { + let text = task_file("raster.function", percent_slope()); + assert_all_need("task.import", json!({"text": text}), "slope-percent"); + assert_all_need("task.import", json!({"data": encoded(&text)}), "slope-percent"); + let nested = task_file("script.run", json!({"script": format!("model.import {}", json!({"text": model_file(percent_slope())}))})); + assert_all_need("task.import", json!({"text": nested}), "slope-percent"); +} + +/// A text `task.import` refuses, and a `path`, require nothing. +#[test] +fn a_task_import_that_imports_nothing_requires_nothing() { + let mut newer: Value = serde_json::from_str(&task_file("raster.function", percent_slope())).unwrap(); + newer["format"] = json!(999_999); + for params in [json!({"text": "not a task"}), json!({"text": newer.to_string()}), json!({"path": "t.rgistask"})] { + assert_none_needs("task.import", params); + } +} + +/// A `data` that can't be decoded requires everything, as a template's does. +#[test] +fn a_document_that_cannot_be_decoded_requires_everything() { + for id in ["model.import", "notebook.open", "task.import"] { + for found in needs(id, json!({"data": "not base64!"})) { + assert!(crate::project::CAPABILITIES.iter().all(|c| found.iter().any(|f| f == c)), "{id}: {found:?}"); + } + } +} + +/// The same reading in the other containers a project saves commands in: its history and its +/// notebooks. +#[test] +fn an_import_in_the_history_or_a_notebook_requires_what_its_document_requires() { + let params = json!({"text": model_file(percent_slope())}); + let mut in_history = serde_json::to_value(Project::default()).unwrap(); + in_history["gp_history"] = + json!([{"id": "model.import", "tool": "Import Model", "params": params, "messages": [], "millis": 0, "ok": true}]); + let in_history = Project::from_peer_raw(&in_history.to_string()).unwrap(); + assert!(in_history.required_capabilities().contains(&"slope-percent")); + let mut in_notebook = serde_json::to_value(Project::default()).unwrap(); + in_notebook["notebooks"] = json!([serde_json::from_str::(¬ebook_file("code", &format!("model.import {params}"))).unwrap()]); + let in_notebook = Project::from_peer_raw(&in_notebook.to_string()).unwrap(); + assert!(in_notebook.required_capabilities().contains(&"slope-percent")); +}