diff --git a/Cargo.lock b/Cargo.lock index 90e3723f19..445a4b9d00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3705,6 +3705,13 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "migration-nodes" +version = "0.0.0" +dependencies = [ + "migration-core", +] + [[package]] name = "migration-runner" version = "0.0.0" @@ -3720,6 +3727,7 @@ dependencies = [ name = "migration-snapshot" version = "0.0.0" dependencies = [ + "convert_case 0.12.0", "proc-macro2", "quote", "syn 2.0.106", diff --git a/Cargo.toml b/Cargo.toml index 454d1610f5..a37fc21b28 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ members = [ "document/migrations/runner", "document/migrations/formats", "document/migrations/snapshot", + "document/migrations/nodes", "editor", "frontend/wrapper", "libraries/dyn-any", @@ -112,6 +113,7 @@ migration-core = { path = "document/migrations/core", default-features = false } migration-macros = { path = "document/migrations/macros" } migration-runner = { path = "document/migrations/runner" } migration-formats = { path = "document/migrations/formats" } +migration-nodes = { path = "document/migrations/nodes" } raster-nodes = { path = "node-graph/nodes/raster" } graphene-std = { path = "node-graph/nodes/gstd" } interpreted-executor = { path = "node-graph/interpreted-executor" } diff --git a/document/migrations/nodes/Cargo.toml b/document/migrations/nodes/Cargo.toml new file mode 100644 index 0000000000..62c3823325 --- /dev/null +++ b/document/migrations/nodes/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "migration-nodes" +description = "Node migrations of Graphite documents, scaffolded by `cargo run migration new`" +edition.workspace = true +version.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +migration-core = { workspace = true, features = ["typed"] } diff --git a/document/migrations/nodes/src/lib.rs b/document/migrations/nodes/src/lib.rs new file mode 100644 index 0000000000..afb8785d8f --- /dev/null +++ b/document/migrations/nodes/src/lib.rs @@ -0,0 +1,2 @@ +//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with +//! `cargo run migration new ` after bumping a node's `version(N)`. diff --git a/document/migrations/snapshot/Cargo.toml b/document/migrations/snapshot/Cargo.toml index b6978a5d60..5820ccad9e 100644 --- a/document/migrations/snapshot/Cargo.toml +++ b/document/migrations/snapshot/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "migration-snapshot" -description = "Freezes Graphite's stored document types into migration-formats and checks them against the latest frozen version" +description = "The `cargo run migration` CLI: freezes Graphite's stored document types per format version and scaffolds node migrations" edition.workspace = true version.workspace = true license.workspace = true @@ -11,3 +11,4 @@ publish = false syn = { workspace = true } proc-macro2 = { workspace = true } quote = { workspace = true } +convert_case = { workspace = true } diff --git a/document/migrations/snapshot/src/main.rs b/document/migrations/snapshot/src/main.rs index 81e4c10e9b..895f10bcdf 100644 --- a/document/migrations/snapshot/src/main.rs +++ b/document/migrations/snapshot/src/main.rs @@ -1,10 +1,13 @@ -//! Freezes the stored document types (`graph-storage`'s `schema` module) into `migration-formats` as one format version, -//! and checks that the live types still match the latest frozen version. +//! `cargo run migration`: freezes the stored document types (`graph-storage`'s `schema` module) into `migration-formats` +//! as one format version with the step from the previous one, checks that the live types still match the latest frozen +//! version, and scaffolds node migrations into `migration-nodes`. //! //! A new version declares again only the types that changed, plus every type reaching one, and re-exports the rest from //! the previous version. So format steps convert only what changed, and old versions never depend on the live crate. +mod nodes; mod plan; +mod scaffold; mod step; mod types; @@ -26,7 +29,15 @@ fn usage() { println!(); println!(":"); println!(" check Fail if the stored types changed since the latest frozen format version"); - println!(" snapshot Freeze the stored types as the next format version"); + println!(" snapshot Freeze the stored types as the next format version, with the step from the previous one"); + println!(" new "); + println!(" Scaffold the migration of a node from the version before its current `version(N)`"); + println!(" new @ "); + println!(" Scaffold the migration replacing a removed node by another"); + println!(" rename @ "); + println!(" Register that a node only moved to a new identifier"); + println!(); + println!("A node is named by its full identifier, or by a function name or identifier suffix only one node has."); println!(); } @@ -34,9 +45,11 @@ fn main() -> ExitCode { let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); let workspace = workspace.canonicalize().unwrap_or(workspace); - let result = match std::env::args().nth(1).as_deref() { + let arguments: Vec = std::env::args().skip(1).collect(); + let result = match arguments.first().map(String::as_str) { Some("check") => check(&workspace), Some("snapshot") => snapshot(&workspace), + Some(command @ ("new" | "rename")) => scaffold::scaffold(&workspace, command, &arguments[1..]), Some("help" | "--help") => { usage(); return ExitCode::SUCCESS; diff --git a/document/migrations/snapshot/src/nodes.rs b/document/migrations/snapshot/src/nodes.rs new file mode 100644 index 0000000000..cce0f60396 --- /dev/null +++ b/document/migrations/snapshot/src/nodes.rs @@ -0,0 +1,138 @@ +//! Finds every `#[node_macro::node]` function in the node graph crates, with the identifier and version the macro gives it. + +use convert_case::{Case, Casing}; +use std::path::{Path, PathBuf}; +use syn::punctuated::Punctuated; + +/// One node as its source declares it. +pub struct NodeSource { + /// What `ProtoNodeIdentifier` the macro generates: the `path(...)` override or the module path, then the Pascal-case + /// function name with a `Node` suffix. + pub identifier: String, + pub version: u32, + pub function: String, + pub file: PathBuf, +} + +/// Every node in a crate under `root` with a `src/lib.rs`. Files that don't parse are skipped, since they don't build either. +pub fn find_nodes(root: &Path) -> Result, String> { + let mut manifests = Vec::new(); + collect_manifests(root, &mut manifests)?; + + let mut nodes = Vec::new(); + for manifest in manifests { + let Some(directory) = manifest.parent() else { continue }; + let library = directory.join("src/lib.rs"); + if !library.exists() { + continue; + } + + let crate_name = library_name(&manifest)?; + walk_file(&library, &directory.join("src"), &[crate_name], &mut nodes); + } + + nodes.sort_by(|a, b| a.identifier.cmp(&b.identifier)); + Ok(nodes) +} + +fn collect_manifests(directory: &Path, manifests: &mut Vec) -> Result<(), String> { + let entries = std::fs::read_dir(directory).map_err(|error| format!("{}: {error}", directory.display()))?; + for entry in entries.filter_map(Result::ok) { + let path = entry.path(); + if path.is_dir() && path.file_name().is_some_and(|name| name != "target" && name != "node_modules") { + collect_manifests(&path, manifests)?; + } else if path.file_name().is_some_and(|name| name == "Cargo.toml") { + manifests.push(path); + } + } + Ok(()) +} + +/// The crate's name in paths: `[lib] name`, or the package name with dashes as underscores. +fn library_name(manifest: &Path) -> Result { + let source = std::fs::read_to_string(manifest).map_err(|error| format!("{}: {error}", manifest.display()))?; + + let mut section = ""; + let (mut package, mut library) = (None, None); + for line in source.lines().map(str::trim) { + if line.starts_with('[') { + section = line; + continue; + } + let Some(value) = line.strip_prefix("name").map(str::trim_start).and_then(|rest| rest.strip_prefix('=')) else { + continue; + }; + let value = value.trim().trim_matches('"').to_string(); + match section { + "[package]" => package = Some(value), + "[lib]" => library = Some(value), + _ => {} + } + } + + library.or(package).map(|name| name.replace('-', "_")).ok_or_else(|| format!("{}: no package name", manifest.display())) +} + +/// `file` is the module at `module_path`, whose `mod child;` declarations live in `children`. +fn walk_file(file: &Path, children: &Path, module_path: &[String], nodes: &mut Vec) { + let Ok(source) = std::fs::read_to_string(file) else { return }; + let Ok(parsed) = syn::parse_file(&source) else { return }; + walk_items(&parsed.items, file, children, module_path, nodes); +} + +fn walk_items(items: &[syn::Item], file: &Path, children: &Path, module_path: &[String], nodes: &mut Vec) { + for item in items { + match item { + syn::Item::Fn(function) => { + if let Some(node) = node_source(function, file, module_path) { + nodes.push(node); + } + } + syn::Item::Mod(module) => { + let name = module.ident.to_string(); + let path: Vec = module_path.iter().cloned().chain(std::iter::once(name.clone())).collect(); + let directory = children.join(&name); + + match &module.content { + Some((_, items)) => walk_items(items, file, &directory, &path, nodes), + None => { + let flat = children.join(format!("{name}.rs")); + let nested = directory.join("mod.rs"); + let module_file = if flat.exists() { flat } else { nested }; + walk_file(&module_file, &directory, &path, nodes); + } + } + } + _ => {} + } + } +} + +fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> Option { + let attribute = function.attrs.iter().find(|attribute| { + let segments: Vec = attribute.path().segments.iter().map(|segment| segment.ident.to_string()).collect(); + matches!(segments.iter().map(String::as_str).collect::>().as_slice(), ["node_macro", "node"] | ["node"]) + })?; + let arguments = attribute.parse_args_with(Punctuated::::parse_terminated).ok()?; + + let mut path = module_path.join("::"); + let mut version = 1; + for argument in arguments { + let syn::Meta::List(list) = argument else { continue }; + if list.path.is_ident("path") { + path = list.tokens.to_string().replace(' ', ""); + } else if list.path.is_ident("version") + && let Ok(literal) = syn::parse2::(list.tokens.clone()) + { + version = literal.base10_parse().ok()?; + } + } + + let function_name = function.sig.ident.to_string(); + Some(NodeSource { + identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)), + version, + function: function_name, + file: file.to_path_buf(), + }) +} diff --git a/document/migrations/snapshot/src/scaffold.rs b/document/migrations/snapshot/src/scaffold.rs new file mode 100644 index 0000000000..2e972db510 --- /dev/null +++ b/document/migrations/snapshot/src/scaffold.rs @@ -0,0 +1,284 @@ +//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate. + +use crate::nodes::{NodeSource, find_nodes}; +use std::path::{Path, PathBuf}; + +const NODE_CRATES: &str = "node-graph"; +const MIGRATIONS: &str = "document/migrations/nodes/src"; + +/// `new ` steps a node from its previous version, `new @ ` replaces a node by another, +/// and `rename @ ` registers a finished rename. +pub fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> { + let nodes = find_nodes(&workspace.join(NODE_CRATES))?; + let migrations = workspace.join(MIGRATIONS); + + match (command, arguments) { + ("new", [identifier]) => { + let node = find(&nodes, identifier)?; + if node.version == 1 { + return Err(format!( + "`{}` is at version 1, so there is nothing to migrate from. Bump it with `version(2)` on its `#[node_macro::node]` in {}", + node.identifier, + node.file.display() + )); + } + + let from = node.version - 1; + let source = format!("\"{}\"@{from} => @{}", node.identifier, node.version); + write_step(&migrations, node, &format!("{}_v{from}", node.function), &source, from) + } + ("new", [old, identifier]) => { + let (old_identifier, from) = parse_declaration(old)?; + let node = find_target(&nodes, identifier, from)?; + let source = format!("\"{old_identifier}\"@{from} => \"{}\"@{}", node.identifier, node.version); + write_step(&migrations, node, &format!("{}_from_{}", node.function, last_segment(&old_identifier)), &source, from) + } + ("rename", [old, identifier]) => { + let (old_identifier, from) = parse_declaration(old)?; + let node = find_target(&nodes, identifier, from)?; + let line = format!("rename!(\"{old_identifier}\"@{from} => \"{}\"@{});", node.identifier, node.version); + write_rename(&migrations, node, &line) + } + _ => Err("expected `new `, `new @ `, or `rename @ `".to_string()), + } +} + +/// The node `query` names: its full identifier, or an unambiguous function name or identifier suffix. +fn find<'a>(nodes: &'a [NodeSource], query: &str) -> Result<&'a NodeSource, String> { + if let Some(node) = nodes.iter().find(|node| node.identifier == query) { + return Ok(node); + } + + let candidates: Vec<&NodeSource> = nodes.iter().filter(|node| node.function == query || node.identifier.ends_with(&format!("::{query}"))).collect(); + match candidates.as_slice() { + [node] => Ok(node), + [] => Err(format!("no `#[node_macro::node]` is identified by `{query}`")), + _ => { + let identifiers: Vec<&str> = candidates.iter().map(|node| node.identifier.as_str()).collect(); + Err(format!("`{query}` could be any of: {}", identifiers.join(", "))) + } + } +} + +/// The node a replacement or rename from version `from` leads to, which must be at the next version. +fn find_target<'a>(nodes: &'a [NodeSource], query: &str, from: u32) -> Result<&'a NodeSource, String> { + let node = find(nodes, query)?; + if Some(node.version) != from.checked_add(1) { + return Err(format!( + "`{}` is at version {}, but a migration from version {from} leads to version {}. Set `version({})` on its `#[node_macro::node]` in {}", + node.identifier, + node.version, + from + 1, + from + 1, + node.file.display() + )); + } + Ok(node) +} + +fn parse_declaration(declaration: &str) -> Result<(String, u32), String> { + let parsed = declaration.rsplit_once('@').and_then(|(identifier, version)| Some((identifier.to_string(), version.parse().ok()?))); + parsed.ok_or_else(|| format!("expected `@`, found `{declaration}`")) +} + +fn last_segment(identifier: &str) -> String { + let segment = identifier.rsplit("::").next().unwrap_or(identifier); + let mut name = String::new(); + for (index, character) in segment.chars().enumerate() { + if character.is_uppercase() && index > 0 { + name.push('_'); + } + name.extend(character.to_lowercase()); + } + name +} + +/// The module holding migrations of nodes from `node`'s crate, declared in the crate root. +fn crate_module(migrations: &Path, node: &NodeSource) -> Result { + let module = node.identifier.split("::").next().unwrap_or_default().to_string(); + declare_module(&migrations.join("lib.rs"), &module)?; + + let directory = migrations.join(&module); + std::fs::create_dir_all(&directory).map_err(|error| format!("{}: {error}", directory.display()))?; + + let module_file = directory.join("mod.rs"); + if !module_file.exists() { + let header = format!("//! Migrations of the nodes in `{module}`.\n"); + std::fs::write(&module_file, header).map_err(|error| format!("{}: {error}", module_file.display()))?; + } + Ok(directory) +} + +fn write_step(migrations: &Path, node: &NodeSource, name: &str, step: &str, from: u32) -> Result<(), String> { + if already_migrated(migrations, step) { + return Err(format!("a migration `{step}` already exists in {}", migrations.display())); + } + + let directory = crate_module(migrations, node)?; + let file = directory.join(format!("{name}.rs")); + if file.exists() { + return Err(format!("{} already exists", file.display())); + } + + let source = format!( + "use migration_core::{{Inputs, migration}};\n\n\ + /// Describe what changed from version {from}.\n\ + #[migration({step})]\n\ + pub fn {name}(inputs: &mut Inputs) {{\n\ + \tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, or `&mut Downstream`\");\n\ + }}\n" + ); + std::fs::write(&file, source).map_err(|error| format!("{}: {error}", file.display()))?; + declare_module(&directory.join("mod.rs"), name)?; + + println!("Scaffolded `{step}` in {}", file.display()); + println!("Write the migration where its `compile_error!` points, and describe the change in its doc comment"); + Ok(()) +} + +fn write_rename(migrations: &Path, node: &NodeSource, line: &str) -> Result<(), String> { + let directory = crate_module(migrations, node)?; + let file = directory.join("renames.rs"); + + let existing = std::fs::read_to_string(&file).unwrap_or_else(|_| "//! Nodes that only moved to a new identifier.\n\nuse migration_core::rename;\n\n".to_string()); + if existing.lines().any(|existing_line| existing_line == line) { + return Err(format!("{} already has `{line}`", file.display())); + } + + std::fs::write(&file, format!("{existing}{line}\n")).map_err(|error| format!("{}: {error}", file.display()))?; + declare_module(&directory.join("mod.rs"), "renames")?; + + println!("Registered `{line}` in {}", file.display()); + Ok(()) +} + +/// Whether some migration file already registers `step`. +fn already_migrated(directory: &Path, step: &str) -> bool { + let Ok(entries) = std::fs::read_dir(directory) else { return false }; + entries.filter_map(Result::ok).any(|entry| { + let path = entry.path(); + if path.is_dir() { + return already_migrated(&path, step); + } + std::fs::read_to_string(&path).is_ok_and(|source| source.contains(&format!("#[migration({step})]"))) + }) +} + +/// Adds `mod ;` to `file` unless it's there, keeping the declarations sorted after the header. +fn declare_module(file: &Path, module: &str) -> Result<(), String> { + let source = std::fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?; + let declaration = format!("mod {module};"); + if source.lines().any(|line| line == declaration) { + return Ok(()); + } + + let mut lines: Vec = source.lines().map(str::to_string).collect(); + let mut declarations: Vec = lines.iter().filter(|line| line.starts_with("mod ")).cloned().chain(std::iter::once(declaration)).collect(); + declarations.sort(); + lines.retain(|line| !line.starts_with("mod ")); + while lines.last().is_some_and(|line| line.is_empty()) { + lines.pop(); + } + + let updated = format!("{}\n\n{}\n", lines.join("\n"), declarations.join("\n")); + std::fs::write(file, updated).map_err(|error| format!("{}: {error}", file.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A workspace with one node crate and an empty `migration-nodes`, removed on drop. + struct Workspace(PathBuf); + + impl Workspace { + fn new(name: &str) -> Self { + let root = std::env::temp_dir().join(format!("migration-scaffold-{name}-{}", std::process::id())); + let nodes = root.join("node-graph/nodes/blending"); + std::fs::create_dir_all(nodes.join("src")).unwrap(); + std::fs::write(nodes.join("Cargo.toml"), "[package]\nname = \"blending-nodes\"\n").unwrap(); + std::fs::write( + nodes.join("src/lib.rs"), + "mod adjust;\n#[node_macro::node(category(\"Blending\"), version(2))]\nfn opacity(value: f64) -> f64 { value }\n#[node_macro::node(category(\"Blending\"))]\nfn blend(value: f64) -> f64 { value }\n", + ) + .unwrap(); + std::fs::write( + nodes.join("src/adjust.rs"), + "mod inner {\n#[node_macro::node(category(\"Blending\"), path(legacy::adjust), version(3))]\nfn brighten(value: f64) -> f64 { value }\n}\n", + ) + .unwrap(); + + std::fs::create_dir_all(root.join(MIGRATIONS)).unwrap(); + std::fs::write(root.join(MIGRATIONS).join("lib.rs"), "//! Node migrations.\n").unwrap(); + Self(root) + } + + fn read(&self, path: &str) -> String { + std::fs::read_to_string(self.0.join(MIGRATIONS).join(path)).unwrap() + } + } + + impl Drop for Workspace { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn arguments(values: &[&str]) -> Vec { + values.iter().map(|value| value.to_string()).collect() + } + + #[test] + fn finds_identifiers_and_versions_like_the_macro() { + let workspace = Workspace::new("find"); + let nodes = find_nodes(&workspace.0.join(NODE_CRATES)).unwrap(); + let found: Vec<(&str, u32)> = nodes.iter().map(|node| (node.identifier.as_str(), node.version)).collect(); + + assert_eq!(found, [("blending_nodes::BlendNode", 1), ("blending_nodes::OpacityNode", 2), ("legacy::adjust::BrightenNode", 3)]); + } + + #[test] + fn new_scaffolds_the_step_from_the_previous_version() { + let workspace = Workspace::new("new"); + scaffold(&workspace.0, "new", &arguments(&["opacity"])).unwrap(); + + assert!(workspace.read("lib.rs").ends_with("\n\nmod blending_nodes;\n")); + assert!(workspace.read("blending_nodes/mod.rs").contains("mod opacity_v1;")); + let step = workspace.read("blending_nodes/opacity_v1.rs"); + assert!(step.contains("#[migration(\"blending_nodes::OpacityNode\"@1 => @2)]\npub fn opacity_v1(inputs: &mut Inputs) {")); + assert!(step.contains("compile_error!")); + + let again = scaffold(&workspace.0, "new", &arguments(&["blending_nodes::OpacityNode"])).unwrap_err(); + assert!(again.contains("already exists"), "{again}"); + } + + #[test] + fn new_refuses_a_node_at_version_one() { + let workspace = Workspace::new("first"); + let error = scaffold(&workspace.0, "new", &arguments(&["blend"])).unwrap_err(); + assert!(error.contains("Bump it with `version(2)`"), "{error}"); + } + + #[test] + fn replacements_and_renames_lead_to_the_next_version() { + let workspace = Workspace::new("rename"); + + scaffold(&workspace.0, "new", &arguments(&["legacy::Brighten@2", "BrightenNode"])).unwrap(); + assert!( + workspace + .read("legacy/brighten_from_brighten.rs") + .contains("#[migration(\"legacy::Brighten\"@2 => \"legacy::adjust::BrightenNode\"@3)]") + ); + + scaffold(&workspace.0, "rename", &arguments(&["graphene_core::Opacity@1", "opacity"])).unwrap(); + assert!( + workspace + .read("blending_nodes/renames.rs") + .contains("rename!(\"graphene_core::Opacity\"@1 => \"blending_nodes::OpacityNode\"@2);") + ); + assert!(workspace.read("blending_nodes/mod.rs").contains("mod renames;")); + + let skipped = scaffold(&workspace.0, "rename", &arguments(&["graphene_core::Blend@3", "blend"])).unwrap_err(); + assert!(skipped.contains("Set `version(4)`"), "{skipped}"); + } +} diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index fbcb6f2475..0858d6c0d4 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -16,6 +16,8 @@ pub struct NodeMetadata { pub inspector: Option<&'static str>, pub context_features: Vec, pub flags: NodeFlags, + /// The declaration version from `#[node(version(N))]`, starting at 1. + pub version: u32, pub output_fields: Option, } diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 28e920009a..df52e62db6 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -870,6 +870,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn .. } = attributes.flags; let asynchronous = parsed.is_async; + let version = attributes.version.unwrap_or(1); // A node returning a `Destructure` struct records its fields as output connectors let output_fields = match may_return_destructure_struct(parsed) { true => { @@ -1101,6 +1102,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn inject_scope: #inject_scope, asynchronous: #asynchronous, }, + version: #version, output_fields: #output_fields, fields: vec![ #( diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index a83f89c419..a56103ec9f 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -73,6 +73,8 @@ pub(crate) struct NodeFnAttributes { pub(crate) flags: NodeFlags, /// Fn producing an placeholder value used while node evaluation is pending pub(crate) placeholder: Option, + /// The declaration version, starting at 1 when absent. Bumping it requires a migration from the previous version. + pub(crate) version: Option, } #[derive(Clone, Debug, Default)] @@ -466,6 +468,7 @@ impl Parse for NodeFnAttributes { let mut serialize = None; let mut flags = NodeFlags::default(); let mut placeholder = None; + let mut version = None; let content = input; // let content; @@ -611,6 +614,23 @@ impl Parse for NodeFnAttributes { // // Example usage: // #[node_macro::node(..., inject_scope, ...)] + // The version of the node's declaration. Bump it whenever its inputs or behavior change in a way older documents + // would load wrongly, and add a migration from the previous version (`cargo run migration new `). + // + // Example usage: + // #[node_macro::node(..., version(2), ...)] + "version" => { + let meta = meta.require_list()?; + if version.is_some() { + return Err(Error::new_spanned(meta, "Multiple 'version' attributes are not allowed")); + } + let literal: LitInt = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected an integer for 'version', e.g., version(2)"))?; + let parsed: u32 = literal.base10_parse()?; + if parsed == 0 { + return Err(Error::new_spanned(literal, "Versions start at 1")); + } + version = Some(parsed); + } "inject_scope" => set_flag(&mut flags.inject_scope, meta, "inject_scope")?, // The placeholder value used while a node's evaluation is pending. // @@ -636,7 +656,7 @@ impl Parse for NodeFnAttributes { indoc!( r#" Unsupported attribute in `node`. - Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', and 'no_partial'. + Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'. Example usage: #[node_macro::node(..., name("Test Node"), ...)] "# @@ -670,6 +690,7 @@ impl Parse for NodeFnAttributes { serialize, flags, placeholder, + version, }) } } @@ -1782,6 +1803,24 @@ mod tests { assert!(error_message.contains("expected a range like `0..100`, `..100`, or `0..`")); } + #[test] + fn test_version() { + let input = quote!( + fn add(a: f64, b: f64) -> f64 { + a + b + } + ); + + let unversioned = parse_node_fn(quote!(category("Math: Arithmetic")), input.clone()).unwrap(); + assert_eq!(unversioned.attributes.version, None); + + let versioned = parse_node_fn(quote!(category("Math: Arithmetic"), version(3)), input.clone()).unwrap(); + assert_eq!(versioned.attributes.version, Some(3)); + + let error_message = parse_node_fn(quote!(category("Math: Arithmetic"), version(0)), input).unwrap_err().to_string(); + assert!(error_message.contains("Versions start at 1")); + } + #[test] fn test_async_node() { let attr = quote!(category("IO")); diff --git a/node-graph/rfcs/document-format-migrations.md b/node-graph/rfcs/document-format-migrations.md index 6f6a8c1b72..be1f672a33 100644 --- a/node-graph/rfcs/document-format-migrations.md +++ b/node-graph/rfcs/document-format-migrations.md @@ -39,7 +39,7 @@ fn opacity(/* ... */) -> Item { } ``` -A declaration is identified by `identifier@version`. Declaration resources are content-addressed from that pair, so the same declaration has the same `ResourceId` on every peer, and a document states the exact version of every node it contains. +The macro records the version in `NODE_METADATA` as `NodeMetadata::version`. A declaration is identified by `identifier@version`. Declaration resources are content-addressed from that pair, so the same declaration has the same `ResourceId` on every peer, and a document states the exact version of every node it contains. A node's **lineage** is the chain of declarations connected by migrations. Every migration bumps the version by one, including renames, so `identifier@version` never repeats within a lineage even if a node is renamed back and forth (`a@1 → b@2 → a@3`). The version declared on a node is its position in its lineage. It is declared rather than derived because a binary shipping only a subset of migration crates can't count the lineage. @@ -430,7 +430,13 @@ A CLI subcommand dumps `NODE_METADATA` (identifier, version, input names and typ | Version bumped | A migration from the previous version is registered. | | Migration registered | `target.version == source.version + 1`, and the dependency order has no cycle. | -The scaffold command printed by a failing check (`cargo run new-migration `) generates the migration file with its attribute and registration. Migrations don't need input shapes: positions come from the anchor's instance, the source version guarantees the layout, and inserted nodes list every input explicitly. +The scaffold commands, which a failing check prints, find the node in the `node-graph` sources with its identifier (the `path(...)` override or the module path, then the Pascal-case function name and `Node`) and its `version(N)`, and write into `migration-nodes`, a module per node crate and a file per step: + +- `cargo run migration new ` scaffolds `#[migration(""@N-1 => @N)]`, refusing a node still at version 1. +- `cargo run migration new @ ` scaffolds the replacement of a removed node, checking that the new node is at `version + 1`. +- `cargo run migration rename @ ` appends a finished `rename!` to the crate module's `renames.rs`. + +A node is named by its full identifier, or by a function name or identifier suffix only one node has. The scaffolded body is a `compile_error!` naming the parameters a migration can take, so it can't ship unwritten. Migrations don't need input shapes: positions come from the anchor's instance, the source version guarantees the layout, and inserted nodes list every input explicitly. ## Testing @@ -446,7 +452,8 @@ document/migrations/ ├── core/ migration-core: views, connectors, `decl!`, registry, Payload, errors, re-exporting `#[migration]` and `rename!` ├── macros/ migration-macros: `#[migration]` and `rename!` ├── formats/ migration-formats: the frozen stored types of every format version -├── snapshot/ migration-snapshot: `cargo run migration snapshot` and `check` +├── snapshot/ migration-snapshot: the `cargo run migration` CLI (`snapshot`, `check`, `new`, `rename`) +├── nodes/ migration-nodes: node migrations, scaffolded by `cargo run migration new` ├── runner/ migration-runner: format chaining, ordering, history rewrite, fast path, settling, Rev mapping, translation of older peers' deltas └── migration crates, one per era or area, selected per binary by cargo features ``` diff --git a/tools/cargo-run/src/main.rs b/tools/cargo-run/src/main.rs index 2e71fff077..30c9364cb3 100644 --- a/tools/cargo-run/src/main.rs +++ b/tools/cargo-run/src/main.rs @@ -18,7 +18,7 @@ fn usage() { println!(" build Build the selected target"); println!(" explore Open an assortment of tools for exploring the codebase"); println!(" drive Drive the web editor in an isolated browser (see `cargo run drive help`)"); - println!(" migration Freeze or check the stored document format (see `cargo run migration help`)"); + println!(" migration Freeze the stored format or scaffold node migrations (see `cargo run migration help`)"); println!(" help Show this message"); println!(":"); println!(" [web] Web app (default)");