Files
Dennis Kobert 5c7265cfb6 Add the migration CLI and CI checks (#4864)
Add the migration CLI: frozen format versions, node migration scaffolding, and CI checks
2026-10-31 12:55:56 +01:00

449 lines
17 KiB
Rust

//! The format step from the previous version to a new one: an `Upgrade` impl per type the new version declares again,
//! and the `format_migration!` registering the conversion of each changed root.
//!
//! Types declared again only because they reach a changed type convert field by field on their own. A changed type
//! converts what still matches by name, and marks the rest with `compile_error!`, so the compiler lists what is left.
use crate::plan::{Plan, Snapshots};
use crate::types::Types;
use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, format_ident, quote};
use std::collections::{BTreeMap, BTreeSet};
use syn::visit_mut::VisitMut;
/// The stored roots `format_migration!` converts, by the name it lists each under.
const ROOTS: &[(&str, &str)] = &[("registry", "Registry"), ("delta", "Delta"), ("hot_op", "HotOp"), ("session", "SessionState")];
/// Types whose encoding lives outside the payloads a format step converts.
const UNCONVERTED: &[&str] = &["ProtoNode"];
pub(crate) struct Step<'a> {
plan: &'a Plan,
previous: u32,
live: &'a Types,
snapshots: &'a Snapshots,
previous_module: Ident,
next_module: Ident,
}
impl<'a> Step<'a> {
pub fn new(plan: &'a Plan, previous: u32, live: &'a Types, snapshots: &'a Snapshots) -> Self {
Self {
plan,
previous,
live,
snapshots,
previous_module: format_ident!("v{previous}"),
next_module: format_ident!("v{}", plan.version),
}
}
/// Changed types the step can't convert, for the caller to warn about.
pub fn unconverted(&self) -> Vec<&'static str> {
UNCONVERTED.iter().copied().filter(|name| self.plan.changed.contains(*name)).collect()
}
/// The step file, before rustfmt.
pub fn render(&self) -> String {
let (previous, next) = (&self.previous_module, &self.next_module);
let upgrades: Vec<String> = self
.live
.order
.iter()
.filter(|name| self.plan.redeclared.contains(*name))
.filter_map(|name| self.upgrade(name))
.map(|tokens| tokens.to_string())
.collect();
let changed: Vec<&str> = self.plan.changed.iter().map(String::as_str).collect();
format!(
"//! Format step {} to {}, generated by `cargo run migration snapshot`. Types that only reach a changed one convert on their own. \
Finish the changed ones ({}) where a `compile_error!` or a type mismatch points.\n\n{}\n\n{}\n\n{}\n",
self.previous,
self.plan.version,
changed.join(", "),
quote!(use crate::{#previous, #next}; use migration_core::{MigrationError, Upgrade, format_migration};),
self.registration(),
upgrades.join("\n\n")
)
}
/// Registers the step with every root the new version declares again, converted from its previous version.
/// Written as text, since rustfmt leaves macro calls as they are.
fn registration(&self) -> String {
let previous = self.previous;
let roots: Vec<String> = ROOTS
.iter()
.filter(|(_, name)| self.plan.redeclared.contains(*name))
.map(|(root, name)| format!("\t{root}: v{previous}::{name},\n"))
.collect();
format!("format_migration! {{\n\t{previous} => {},\n{}}}", self.plan.version, roots.concat())
}
/// `impl Upgrade` for one type, or nothing for an alias, a generic type (converted inline where used), or a new type.
fn upgrade(&self, name: &str) -> Option<TokenStream> {
let new = self.live.entries.get(name)?;
let old = self.snapshots.entry(self.previous, name)?;
if generics(&new.definition).is_some_and(|generics| !generics.params.is_empty()) {
return None;
}
let (previous, next) = (&self.previous_module, &self.next_module);
let ident = format_ident!("{name}");
let body = match (&old.definition, &new.definition) {
(syn::Item::Struct(old), syn::Item::Struct(new)) => {
let (pattern, construction) = self.convert_fields(&old.fields, &new.fields, quote!(#previous::#ident), quote!(#next::#ident), &BTreeMap::new());
quote!(let #pattern = self; Ok(#construction))
}
(syn::Item::Enum(old), syn::Item::Enum(new)) => {
let conversion = self.convert_enum(old, new, &ident);
quote!(Ok(#conversion))
}
(syn::Item::Type(_), syn::Item::Type(_)) => return None,
_ => {
let message = format!("`{name}` changed between a struct, an enum, and an alias; convert it here");
quote!(compile_error!(#message))
}
};
Some(quote! {
impl Upgrade for #previous::#ident {
type Next = #next::#ident;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
#body
}
}
})
}
/// Destructures `value` as `old_path` and builds `new_path`, matching fields by name or position.
fn convert_struct(&self, value: TokenStream, old: &syn::Fields, new: &syn::Fields, old_path: TokenStream, new_path: TokenStream, substitutions: &BTreeMap<String, syn::Type>) -> TokenStream {
let (pattern, construction) = self.convert_fields(old, new, old_path, new_path, substitutions);
quote!({
let #pattern = #value;
#construction
})
}
/// The pattern destructuring `old` and the expression building `new` from its bindings.
fn convert_fields(&self, old: &syn::Fields, new: &syn::Fields, old_path: TokenStream, new_path: TokenStream, substitutions: &BTreeMap<String, syn::Type>) -> (TokenStream, TokenStream) {
let old_fields = field_list(old);
let new_fields = field_list(new);
let bindings: Vec<Ident> = old_fields.iter().map(|(binding, _, _)| binding.clone()).collect();
let values = new_fields.iter().map(|(binding, label, new_type)| {
let new_type = substitute(new_type, substitutions);
match old_fields.iter().find(|(old_binding, _, _)| old_binding == binding) {
Some((_, _, old_type)) if substitute(old_type, substitutions).to_token_stream().to_string() == new_type.to_token_stream().to_string() => {
self.convert(binding.to_token_stream(), &new_type)
}
Some(_) => {
let message = format!("`{label}` changed type to `{}`; convert it here", new_type.to_token_stream());
quote!(compile_error!(#message))
}
None => {
let message = format!("`{label}` is new; give it a value here");
quote!(compile_error!(#message))
}
}
});
match (old, new) {
(syn::Fields::Named(_), syn::Fields::Named(_)) => {
let fields = new_fields
.iter()
.zip(values)
.map(|((binding, _, _), value)| if *binding == value.to_string() { quote!(#binding) } else { quote!(#binding: #value) });
(quote!(#old_path { #(#bindings),* }), quote!(#new_path { #(#fields),* }))
}
(syn::Fields::Unnamed(_), syn::Fields::Unnamed(_)) => (quote!(#old_path(#(#bindings),*)), quote!(#new_path(#(#values),*))),
(syn::Fields::Unit, syn::Fields::Unit) => (quote!(#old_path), quote!(#new_path)),
_ => (
quote!(#old_path { .. }),
quote!(compile_error!("the fields changed between named, positional, and none; convert them here")),
),
}
}
fn convert_enum(&self, old: &syn::ItemEnum, new: &syn::ItemEnum, ident: &Ident) -> TokenStream {
let (previous, next) = (&self.previous_module, &self.next_module);
let arms = old.variants.iter().map(|old_variant| {
let variant = &old_variant.ident;
let old_path = quote!(#previous::#ident::#variant);
match new.variants.iter().find(|new_variant| new_variant.ident == *variant) {
Some(new_variant) => {
let (pattern, construction) = self.convert_fields(&old_variant.fields, &new_variant.fields, old_path, quote!(#next::#ident::#variant), &BTreeMap::new());
quote!(#pattern => #construction,)
}
None => {
let message = format!("`{ident}::{variant}` is gone; map it here");
quote!(#old_path { .. } => compile_error!(#message),)
}
}
});
quote!(match self { #(#arms)* })
}
/// The expression converting `value` of the stored type `ty`, moving it when nothing in it changed.
fn convert(&self, value: TokenStream, ty: &syn::Type) -> TokenStream {
if !self.mentions_redeclared(ty) {
return value;
}
let collect = quote!(.collect::<Result<_, MigrationError>>()?);
match ty {
syn::Type::Path(path) => {
let Some(segment) = path.path.segments.last() else { return value };
let arguments = type_arguments(segment);
let name = segment.ident.to_string();
match (name.as_str(), arguments.as_slice()) {
("Vec" | "HashSet" | "BTreeSet", [element]) if self.upgrades_directly(element) => quote!(#value.into_iter().map(Upgrade::upgrade) #collect),
("Option", [inner]) if self.upgrades_directly(inner) => quote!(#value.map(Upgrade::upgrade).transpose()?),
("Vec" | "HashSet" | "BTreeSet", [element]) => {
let element = self.convert(quote!(element), element);
quote!(#value.into_iter().map(|element| Ok::<_, MigrationError>(#element)) #collect)
}
("HashMap" | "BTreeMap", [key, entry]) => {
let key = self.convert(quote!(key), key);
let entry = self.convert(quote!(entry), entry);
quote!(#value.into_iter().map(|(key, entry)| Ok::<_, MigrationError>((#key, #entry))) #collect)
}
("Option", [inner]) => {
let inner = self.convert(quote!(inner), inner);
quote!(#value.map(|inner| Ok::<_, MigrationError>(#inner)).transpose()?)
}
("Box", [inner]) => {
let inner = self.convert(quote!(inner), inner);
quote!({ let inner = *#value; Box::new(#inner) })
}
_ => self.convert_named(value, &name, &arguments),
}
}
syn::Type::Tuple(tuple) => {
let bindings: Vec<Ident> = (0..tuple.elems.len()).map(|index| format_ident!("element_{index}")).collect();
let elements = bindings.iter().zip(&tuple.elems).map(|(binding, element)| self.convert(binding.to_token_stream(), element));
quote!({ let (#(#bindings),*) = #value; (#(#elements),*) })
}
_ => {
let message = format!("can't convert `{}` on its own; convert it here", ty.to_token_stream());
quote!(compile_error!(#message))
}
}
}
/// A schema type by name: an alias expands, a generic struct converts inline with its arguments, anything else upgrades.
fn convert_named(&self, value: TokenStream, name: &str, arguments: &[&syn::Type]) -> TokenStream {
let Some(entry) = self.live.entries.get(name) else {
let message = format!("`{name}` isn't a schema type; convert it here");
return quote!(compile_error!(#message));
};
match &entry.definition {
syn::Item::Type(alias) => self.convert(value, &alias.ty),
syn::Item::Struct(definition) if !definition.generics.params.is_empty() => {
let substitutions: BTreeMap<String, syn::Type> = definition
.generics
.type_params()
.map(|parameter| parameter.ident.to_string())
.zip(arguments.iter().map(|argument| (*argument).clone()))
.collect();
let old_fields = self.snapshots.entry(self.previous, name).and_then(|old| match &old.definition {
syn::Item::Struct(old) => Some(old.fields.clone()),
_ => None,
});
let Some(old_fields) = old_fields else {
let message = format!("`{name}` is new; convert it here");
return quote!(compile_error!(#message));
};
let (previous, next) = (&self.previous_module, &self.next_module);
let ident = format_ident!("{name}");
self.convert_struct(value, &old_fields, &definition.fields, quote!(#previous::#ident), quote!(#next::#ident), &substitutions)
}
_ => quote!(Upgrade::upgrade(#value)?),
}
}
/// Whether `ty` converts through its own `Upgrade` impl, with nothing around it.
fn upgrades_directly(&self, ty: &syn::Type) -> bool {
let syn::Type::Path(path) = ty else { return false };
let Some(segment) = path.path.segments.last() else { return false };
let name = segment.ident.to_string();
self.plan.redeclared.contains(&name)
&& self.live.entries.get(&name).is_some_and(|entry| match &entry.definition {
syn::Item::Struct(definition) => definition.generics.params.is_empty(),
syn::Item::Enum(definition) => definition.generics.params.is_empty(),
_ => false,
})
}
/// Whether converting `ty` does anything: it names a redeclared type, or an alias or generic type that leads to one.
fn mentions_redeclared(&self, ty: &syn::Type) -> bool {
let mut names = BTreeSet::new();
collect_type_names(ty, &mut names);
names.iter().any(|name| {
self.plan.redeclared.contains(name)
|| self.live.entries.get(name).is_some_and(|entry| match &entry.definition {
syn::Item::Type(alias) => self.mentions_redeclared(&alias.ty),
_ => false,
})
})
}
}
fn generics(item: &syn::Item) -> Option<&syn::Generics> {
match item {
syn::Item::Struct(definition) => Some(&definition.generics),
syn::Item::Enum(definition) => Some(&definition.generics),
syn::Item::Type(definition) => Some(&definition.generics),
_ => None,
}
}
/// Each field's binding (its name, or `field_<index>`), how to name it in a message, and its type.
fn field_list(fields: &syn::Fields) -> Vec<(Ident, String, syn::Type)> {
fields
.iter()
.enumerate()
.map(|(index, field)| match &field.ident {
Some(ident) => (ident.clone(), ident.to_string(), field.ty.clone()),
None => (format_ident!("field_{index}"), index.to_string(), field.ty.clone()),
})
.collect()
}
fn type_arguments(segment: &syn::PathSegment) -> Vec<&syn::Type> {
let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else { return Vec::new() };
arguments
.args
.iter()
.filter_map(|argument| match argument {
syn::GenericArgument::Type(ty) => Some(ty),
_ => None,
})
.collect()
}
fn collect_type_names(ty: &syn::Type, names: &mut BTreeSet<String>) {
struct Names<'a>(&'a mut BTreeSet<String>);
impl<'ast> syn::visit::Visit<'ast> for Names<'_> {
fn visit_path_segment(&mut self, segment: &'ast syn::PathSegment) {
self.0.insert(segment.ident.to_string());
syn::visit::visit_path_segment(self, segment);
}
}
syn::visit::Visit::visit_type(&mut Names(names), ty);
}
/// `ty` with each generic parameter replaced by its argument.
fn substitute(ty: &syn::Type, substitutions: &BTreeMap<String, syn::Type>) -> syn::Type {
struct Substitute<'a>(&'a BTreeMap<String, syn::Type>);
impl VisitMut for Substitute<'_> {
fn visit_type_mut(&mut self, ty: &mut syn::Type) {
if let syn::Type::Path(path) = ty
&& path.qself.is_none()
&& let Some(ident) = path.path.get_ident()
&& let Some(argument) = self.0.get(&ident.to_string())
{
*ty = argument.clone();
return;
}
syn::visit_mut::visit_type_mut(self, ty);
}
}
let mut ty = ty.clone();
Substitute(substitutions).visit_type_mut(&mut ty);
ty
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
const OLD: &str = "
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
pub struct Slot { pub target: u32 }
#[derive(Serialize, Deserialize)]
pub struct Network { pub slots: Vec<Slot>, pub removed: HashMap<u32, Tombstone<Slot>> }
#[derive(Serialize, Deserialize)]
pub struct Tombstone<T> { pub content: T, pub timestamp: u64 }
#[derive(Serialize, Deserialize)]
pub enum Op { Add(Network), Clear, Rename { name: String } }
pub type Store = HashMap<u32, Network>;
#[derive(Serialize, Deserialize)]
pub struct Registry { pub store: Store, pub id: u32 }
";
fn write_schema(directory: &Path, source: &str) {
std::fs::create_dir_all(directory).unwrap();
std::fs::write(directory.join("model.rs"), source).unwrap();
}
fn compact(text: &str) -> String {
text.chars().filter(|character| !character.is_whitespace()).collect()
}
/// The step from `OLD` to `new`, without whitespace.
fn step_to(new: &str, name: &str) -> String {
let root: PathBuf = std::env::temp_dir().join(format!("migration-snapshot-{name}-{}", std::process::id()));
let (schema, snapshots_directory) = (root.join("schema"), root.join("snapshots"));
std::fs::create_dir_all(&snapshots_directory).unwrap();
write_schema(&schema, OLD);
let old = Types::read_schema(&schema).unwrap();
let first = Plan::new(&old, &Snapshots::read(&snapshots_directory).unwrap());
std::fs::write(snapshots_directory.join("v1.rs"), first.render(&old)).unwrap();
write_schema(&schema, new);
let live = Types::read_schema(&schema).unwrap();
let snapshots = Snapshots::read(&snapshots_directory).unwrap();
let plan = Plan::new(&live, &snapshots);
let rendered = Step::new(&plan, 1, &live, &snapshots).render();
std::fs::remove_dir_all(&root).unwrap();
compact(&rendered)
}
#[test]
fn changed_types_point_at_what_is_left() {
let new = OLD
.replace("pub struct Slot { pub target: u32 }", "pub struct Slot { pub target: u32, pub label: Option<String> }")
.replace("Clear, ", "");
let step = step_to(&new, "changed");
assert!(step.contains(&compact(r#"label: compile_error!("`label` is new; give it a value here")"#)));
assert!(step.contains(&compact(r#"v1::Op::Clear { .. } => compile_error!("`Op::Clear` is gone; map it here")"#)));
}
#[test]
fn types_reaching_a_change_convert_on_their_own() {
let new = OLD.replace("pub struct Slot { pub target: u32 }", "pub struct Slot { pub target: u64 }");
let step = step_to(&new, "carried");
// Containers map through the trait, and fields that didn't change move as they are
assert!(step.contains(&compact("slots: slots.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?")));
assert!(step.contains(&compact("Ok(v2::Registry { store: store.into_iter()")));
assert!(step.contains(&compact(", id })")));
// A generic type converts inline with its argument, and an alias by what it stands for
assert!(step.contains(&compact("let v1::Tombstone { content, timestamp } = entry;")));
assert!(!step.contains("implUpgradeforv1::Tombstone"));
assert!(!step.contains("implUpgradeforv1::Store"));
assert!(step.contains(&compact(r#"target: compile_error!("`target` changed type to `u64`; convert it here")"#)));
assert!(step.contains(&compact("format_migration! { 1 => 2, registry: v1::Registry, }")));
}
}