Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/notebook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ fn jupyter_outputs(outputs: &[Value]) -> (String, bool) {
}

/// A RustGIS or Jupyter notebook.
fn parse(text: &str, fallback_name: &str) -> Result<Notebook, String> {
pub(crate) fn parse(text: &str, fallback_name: &str) -> Result<Notebook, String> {
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.
Expand Down
163 changes: 138 additions & 25 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>());
// 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);
Expand Down Expand Up @@ -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<HashMap<usize, HashMap<String, Vec<&'static str>>>>,
bytes: Cell<u64>,
Expand All @@ -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::<Value>(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::<super::Task>(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")
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
.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<Item = (String, Value)>, depth: usize, reads: &OpenedReads) -> Vec<&'static str> {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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, &params) {
required.push(name);
}
}
if !required.contains(&"table-export-order") && command_uses_table_export_order(&id, &params) {
required.push("table-export-order");
}
command_uses(
&|id: &str, params: &Value| {
collect_opened_project(&opened, reads, depth, id, params);
false
},
&id,
&params,
);
}
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
Expand All @@ -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<Vec<&'static str>>, 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| {
Expand All @@ -266,7 +347,8 @@ fn collect_opened_project(found: &RefCell<Vec<&'static str>>, 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(|| {
Expand All @@ -288,9 +370,7 @@ fn collect_opened_project(found: &RefCell<Vec<&'static str>>, 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
Expand Down Expand Up @@ -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`].
Expand Down Expand Up @@ -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`.
Expand Down
Loading
Loading