diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 3ce202f8e1..99e8da7b4c 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -30,7 +30,7 @@ fn need_layer_or_group(s: &Session) -> Option<&'static str> { } /// The most steps a task takes (`task.new`). -const MAX_TASK_STEPS: usize = 200; +pub(crate) const MAX_TASK_STEPS: usize = 200; /// What an item past [`max_file`] is told. fn too_large() -> String { diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 21cc6ceef4..3c45de1593 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -85,17 +85,21 @@ impl Project { 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))) + let ordered = &command_uses_table_export_order; + if self + .tasks + .iter() + .any(|task| task.steps.iter().any(|s| read_as_task_step(&s.command) && command_uses(ordered, &s.command, &s.params))) || self.gp_history.iter().any(|record| { - command_uses_table_export_order(&record.id, &record.params) - || record.command.as_ref().is_some_and(|(id, params)| command_uses_table_export_order(id, params)) + command_uses(ordered, &record.id, &record.params) + || record.command.as_ref().is_some_and(|(id, params)| command_uses(ordered, id, params)) }) || self.notebooks.iter().any(|notebook| { notebook.language().is_none() && notebook .cells .iter() - .any(|cell| cell.kind == crate::cmd::notebook::CellKind::Code && script_uses_table_export_order(&cell.source)) + .any(|cell| cell.kind == crate::cmd::notebook::CellKind::Code && script_uses(&cell.source, ordered)) }) { required.push("table-export-order"); @@ -123,7 +127,7 @@ impl Project { /// Apply the same capability predicate to every replayable project container. 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| read_as_task_step(&s.command) && 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)) @@ -138,11 +142,12 @@ impl Project { /// What a task saved on its own needs: what a project saves for its tasks' steps (a `model.run` /// given its graph inline, and a script line, included), in the order its list has them. pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> { + let steps: Vec<&super::TaskStep> = steps.iter().filter(|s| read_as_task_step(&s.command)).collect(); let mut required: Vec<&'static str> = COMMAND_CAPABILITIES .iter() .filter_map(|&(name, uses)| steps.iter().any(|s| command_uses(&uses, &s.command, &s.params)).then_some(name)) .collect(); - if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { + if steps.iter().any(|s| command_uses(&command_uses_table_export_order, &s.command, &s.params)) { required.push("table-export-order"); } let (opened, reads) = (RefCell::new(Vec::new()), OpenedReads::default()); @@ -257,7 +262,10 @@ fn opened_capabilities(kind: Opened, text: &str, depth: usize, reads: &OpenedRea .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)) + .map(|task| { + let steps = task.steps.into_iter().filter(|step| read_as_task_step(&step.command)); + commands_capabilities(steps.map(|step| (step.command, step.params)), depth, reads) + }) .unwrap_or_default(), Opened::Notebook => crate::cmd::notebook::parse(text, "Notebook") .ok() @@ -318,7 +326,7 @@ fn commands_capabilities(commands: impl Iterator, depth: required.push(name); } } - if !required.contains(&"table-export-order") && command_uses_table_export_order(&id, ¶ms) { + if !required.contains(&"table-export-order") && command_uses(&command_uses_table_export_order, &id, ¶ms) { required.push("table-export-order"); } command_uses( @@ -1732,23 +1740,81 @@ fn svg_picture(p: rustgis_map::Picture) -> bool { /// Use the executor's line grammar; comments/invalid lines are not executable commands, and /// script_line refuses nested scripts, so this check cannot recurse through script.run. fn script_uses(script: &str, uses: impl Fn(&str, &Value) -> bool) -> bool { + script_lines_use(script, |id, params| command_uses(&uses, id, params)) +} + +/// Whether `check` holds for any command of `script`'s lines, as many as a script takes. +fn script_lines_use(script: &str, check: impl Fn(&str, &Value) -> bool) -> bool { script .lines() .take(crate::cmd::workflows::MAX_SCRIPT_LINES) - .any(|line| crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| command_uses(&uses, &id, ¶ms)))) + .any(|line| crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| check(&id, ¶ms)))) } /// `uses` on a saved command and, for a command given a model's graph inline (`model.run`, /// `model.new`, `model.save`), on each of the graph's tool nodes as on a saved model's steps /// (#2758), and for `model.new` given its `steps` inline, on each step: that graph or those steps /// are in no saved model, so nothing else reads them, and an older reader would replay them with -/// the option dropped. +/// the option dropped. For the same reason, on the steps that `task.new` and `task.addStep` create +/// ([`created_task_steps_use`], #3657). fn command_uses(uses: &impl Fn(&str, &Value) -> bool, id: &str, params: &Value) -> bool { + own_command_uses(uses, id, params) || created_task_steps_use(id, params, uses) +} + +/// [`command_uses`] without the task steps the command creates. +fn own_command_uses(uses: &impl Fn(&str, &Value) -> bool, id: &str, params: &Value) -> bool { uses(id, params) || (matches!(id, "model.run" | "model.new" | "model.save") && inline_graph_uses(params, uses)) || (id == "model.new" && inline_steps_uses(params, uses)) } +/// Whether a saved task's step is read for what it requires: not `task.new` or `task.addStep`, as a +/// task doesn't run a task command, so the steps it would create never exist. A saved `task.import` +/// step doesn't run either, but still requires what its file does (#3476). +fn read_as_task_step(command: &str) -> bool { + !matches!(command, "task.new" | "task.addStep") +} + +/// The task steps command `id` creates, as it takes them: `task.new`'s `steps`, an array of at most +/// `MAX_TASK_STEPS` (more is refused there), and `task.addStep`'s own `params`. +fn created_steps<'a>(id: &str, params: &'a Value) -> &'a [Value] { + match id { + "task.new" => params + .get("steps") + .and_then(Value::as_array) + .filter(|steps| steps.len() <= crate::cmd::items::MAX_TASK_STEPS) + .map_or(&[][..], Vec::as_slice), + "task.addStep" => std::slice::from_ref(params), + _ => &[], + } +} + +/// What the steps a command creates use ([`created_steps`]), each its `command` and `params`. They +/// are read leniently: a step the command would refuse for another reason, such as a missing `title`, may +/// require more than needed. A `model.run` with its graph and a `script.run` with its lines are read +/// into. One naming a `task.*` command needs nothing, as a task doesn't run it. +/// +/// One level only: the steps that a created step's script creates in turn aren't read. A script +/// whose lines create a task whose step is a script can be nested as deep as a file cares to write +/// (`\u` escapes keep it from doubling at each level), and every check would walk the whole nest. +/// Instead such a line holds for every check, so the project requires what any command can, as a +/// step opening a document past its limits requires everything. +fn created_task_steps_use(id: &str, params: &Value, uses: &impl Fn(&str, &Value) -> bool) -> bool { + created_steps(id, params).iter().any(|step| { + let command = step.get("command").and_then(Value::as_str).unwrap_or(""); + let params = step.get("params").unwrap_or(&Value::Null); + if command == "script.run" { + // Its lines are read here, not by the check's own `script.run` arm, which would follow + // what they create. + params.get("script").and_then(Value::as_str).is_some_and(|script| { + script_lines_use(script, |id, params| !created_steps(id, params).is_empty() || own_command_uses(uses, id, params)) + }) + } else { + !command.starts_with("task.") && own_command_uses(uses, command, params) + } + }) +} + /// A `model.new`'s inline `steps` read as it reads them: an array of `{tool, params}`, at most /// `MAX_NODES` (more is refused there, so needs nothing), each checked by the leaf check only, and /// one naming `script.run` skipped, as for a graph's node ([`inline_graph_uses`]). @@ -2263,19 +2329,13 @@ fn group_file_requires(layers: &[Layer]) -> Vec<&'static str> { fn command_uses_table_export_order(id: &str, params: &serde_json::Value) -> bool { match id { "share.exportTable" => ["sort", "limit"].iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())), - "script.run" => params.get("script").and_then(serde_json::Value::as_str).is_some_and(script_uses_table_export_order), + "script.run" => { + params.get("script").and_then(serde_json::Value::as_str).is_some_and(|s| script_uses(s, command_uses_table_export_order)) + } _ => false, } } -/// Use the executor's bounded line grammar; nested script.run is refused by script_line, -/// so inspecting script commands cannot recurse through scripts. -fn script_uses_table_export_order(script: &str) -> bool { - script.lines().take(crate::cmd::workflows::MAX_SCRIPT_LINES).any(|line| { - crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| command_uses_table_export_order(&id, ¶ms))) - }) -} - #[cfg(test)] mod tests { use super::*; @@ -3011,6 +3071,104 @@ mod tests { } } + /// The steps a saved `task.new` or `task.addStep` creates require what the same steps require + /// when a task holds them, wherever the command is saved (#3657). As a task's own step the command never runs, + /// so there it requires nothing. + #[test] + fn task_steps_a_saved_command_creates_require_what_they_use() { + let fixture = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap().0; + let weigh = |weight: u64| json!({"title": "W", "command": "labels.placement", "params": {"weight": weight}}); + let line = format!("labels.placement {}", json!({"weight": 9})); + for (step, expected) in [ + (weigh(9), Some("label-weight")), + (weigh(u64::from(rustgis_map::symbology::DEFAULT_LABEL_WEIGHT)), None), + (json!({"title": "O", "command": "project.openText", "params": {"text": fixture}}), Some("layout-extent-indicators")), + ( + json!({"title": "G", "command": "model.run", "params": graph_of_one_tool("a5Grid", json!({"system": "H3"}))}), + Some("dggs-system"), + ), + (json!({"title": "S", "command": "script.run", "params": {"script": line}}), Some("label-weight")), + ( + json!({"title": "E", "command": "share.exportTable", "params": {"path": "a.csv", "sort": "name"}}), + Some("table-export-order"), + ), + // A task doesn't run a task command, so what one would create or import isn't read. + (json!({"title": "N", "command": "task.new", "params": {"steps": [weigh(9)]}}), None), + ( + json!({"title": "I", "command": "task.import", "params": {"text": json!({"name": "T", "steps": [weigh(9)]}).to_string()}}), + None, + ), + ] { + for (command, params) in [("task.new", json!({"steps": [step]})), ("task.addStep", step.clone())] { + let expected = expected.map(|name| json!([name])); + let saved = saved_requires_of_inline(command, ¶ms); + assert_eq!(saved, [None, expected.clone(), expected.clone(), expected], "{command} {params}"); + } + } + } + + /// `task.new`'s `steps` are read as far as the command takes them; what it can't take as steps, + /// and `task.editStep`, which changes only a step's words, require nothing. + #[test] + fn task_steps_are_read_as_task_new_takes_them() { + let weigh = json!({"title": "W", "command": "labels.placement", "params": {"weight": 9}}); + let plain = json!({"title": "P", "command": "map.zoomIn"}); + let steps_with = |count: usize, at: usize| { + let mut steps = vec![plain.clone(); count]; + steps[at] = weigh.clone(); + json!({"steps": steps}) + }; + let most = crate::cmd::items::MAX_TASK_STEPS; + let needs = Some(json!(["label-weight"])); + for (command, params, expected) in [ + ("task.new", steps_with(most, 0), needs.clone()), + ("task.new", steps_with(most, most - 1), needs.clone()), + ("task.new", steps_with(most + 1, 0), None), + ("task.new", json!({"steps": []}), None), + ("task.new", json!({"steps": "labels.placement"}), None), + ("task.new", json!({"steps": [null, 7, {"params": {"weight": 9}}]}), None), + ("task.addStep", json!({"title": "W", "params": {"weight": 9}}), None), + ("task.editStep", json!({"step": 0, "command": "labels.placement", "params": {"weight": 9}}), None), + ] { + // The task's own step (container 0) never runs the command. + let saved = saved_requires_of_inline(command, ¶ms); + assert_eq!(saved[1..], [expected.clone(), expected.clone(), expected], "{command} {params}"); + } + } + + /// A task saved on its own asks the same of its script's lines. The script a created step runs + /// is read too, but the steps its own lines create aren't: following them would walk a nest as + /// deep as a file cares to write (`\u` escapes keep it from doubling at each level), once for + /// each capability. A line that creates them requires every command capability instead. + #[test] + fn task_steps_in_a_saved_task_follow_one_level_of_scripts() { + let escaped = |s: &str| format!("\"{}\"", s.replace('\\', "\\u005c").replace('"', "\\u0022")); + let nest = |levels: usize| { + let mut script = r#"labels.placement {"weight":9}"#.to_string(); + for _ in 0..levels { + let script_text = escaped(&script); + script = format!(r#"task.new {{"steps":[{{"title":"S","command":"script.run","params":{{"script":{script_text}}}}}]}}"#); + } + serde_json::from_value::(json!({"title": "R", "command": "script.run", "params": {"script": script}})) + .unwrap() + }; + assert_eq!(task_capabilities(&[nest(1)]), ["label-weight"]); + let every: Vec<&str> = COMMAND_CAPABILITIES.iter().map(|&(name, _)| name).chain(["table-export-order"]).collect(); + assert_eq!(task_capabilities(&[nest(2)]), every); + assert_eq!(task_capabilities(&[nest(200)]), every); + // A task command at that depth that creates no step leaves nothing unread. + let none = format!("task.new {}", json!({"steps": [{"title": "S", "command": "script.run", "params": {"script": "task.new {}"}}]})); + let step = json!({"title": "R", "command": "script.run", "params": {"script": none}}); + assert!(task_capabilities(&[serde_json::from_value(step).unwrap()]).is_empty()); + // The task's own step that creates one never runs, in a saved task or an imported one. + let weigh = json!({"title": "W", "command": "labels.placement", "params": {"weight": 9}}); + let create = json!({"title": "N", "command": "task.new", "params": {"steps": [weigh]}}); + assert!(task_capabilities(&[serde_json::from_value(create.clone()).unwrap()]).is_empty()); + let file = json!({"name": "T", "steps": [create]}).to_string(); + assert!(!requires("label-weight", "task.import", json!({"text": file}))); + } + /// A node of an inline graph is checked as a step of a saved model is, by every capability: one /// sample for each entry of `COMMAND_CAPABILITIES`, each requiring exactly its own name, so an /// entry added later without a sample fails here. The walk takes a node's id and parameters as