Compare commits

..
Author SHA1 Message Date
Timon 45757b45f4 Report attribute type conflicts from push/extend and when reading list attributes 2026-10-30 14:17:17 +00:00
Timon 207647e78f Report attribute type mismatches 2026-10-30 14:17:17 +00:00
Timon d90cc62bc1 Make nodes report errors instead of panicking or failing silently (#4837)
* Fix crashes and report errors in math nodes

* Fix crashes and report errors in text nodes and Boolean Operation

* Fix crashes and report errors in raster, brush and I/O nodes

* Fix crashes and report errors in vector and transform nodes

* Report errors from graphic and context nodes
2026-10-30 14:16:24 +00:00
171 changed files with 3794 additions and 10185 deletions

No files matched your search

-90
View File
@@ -158,96 +158,6 @@ jobs:
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: mold -run cargo test --all-features
# The plain `cargo test` above only covers the workspace's default members, which leave these out
- name: 🧪 Run document migration tests
env:
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: >-
mold -run cargo test --all-features
--package migration-core
--package migration-runner
--package migration-formats
--package migration-nodes
--package migration-snapshot
--package document-graph-storage
--package document-format
--package graphene-cli
--package regression
- name: 🖼️ Check that the demo artwork is up to date with its migrations
env:
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: mold -run cargo run --package regression -- upgrade --check
# Render the documents of the regression corpus and compare them with their reference images
regression-corpus:
needs: skip-check
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
runs-on: [self-hosted, target/native]
permissions:
contents: read
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: 📥 Clone regression corpus
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
repository: tagtraumen/graphite-corpus
path: target/regression-corpus
lfs: true
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
with:
toolchain: stable
override: true
cache: false
rustflags: ""
- name: 🖼️ Check the corpus renders against its references
run: mold -run cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
- name: 📤 Upload the renders and diffs of mismatches
if: ${{ failure() }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: regression-mismatches
path: target/regression
if-no-files-found: ignore
# Stored types, node version lineages, and node APIs against the base commit. Only needs the snapshot tool, so it runs on a GitHub runner
migrations:
needs: skip-check
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
runs-on: ubuntu-latest
permissions:
contents: read
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
with:
toolchain: stable
override: true
cache: false
rustflags: ""
- name: 📥 Fetch the base commit
run: git fetch --depth=1 origin "$BASE_SHA"
- name: 🔬 Check migrations against the base commit
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
# Rust format check on GitHub runner
rust-fmt:
needs: skip-check
Generated
+11 -94
View File
@@ -966,6 +966,7 @@ dependencies = [
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -1332,9 +1333,6 @@ dependencies = [
"graph-craft",
"graphene-resource",
"log",
"migration-core",
"migration-formats",
"migration-runner",
"postcard",
"serde",
"serde_json",
@@ -2159,8 +2157,6 @@ dependencies = [
"image",
"interpreted-executor",
"log",
"migration-formats",
"migration-nodes",
"preprocessor",
"serde_json",
"tokio",
@@ -2182,6 +2178,7 @@ dependencies = [
"node-macro",
"raster-types",
"serde",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
]
@@ -2269,6 +2266,7 @@ dependencies = [
"rand",
"raster-types",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -2436,8 +2434,6 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"migration-formats",
"migration-nodes",
"node-macro",
"num_enum",
"once_cell",
@@ -3621,10 +3617,10 @@ dependencies = [
"glam 0.33.10",
"graphene-core",
"graphic-types",
"log",
"math-parser",
"node-macro",
"rand",
"thiserror 2.0.18",
"vector-types",
]
@@ -3673,76 +3669,6 @@ dependencies = [
"libc",
]
[[package]]
name = "migration-core"
version = "0.0.0"
dependencies = [
"blake3",
"ctor",
"document-graph-storage",
"migration-macros",
"postcard",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "migration-formats"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"graphene-resource",
"migration-core",
"postcard",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "migration-macros"
version = "0.0.0"
dependencies = [
"blake3",
"convert_case 0.12.0",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "migration-nodes"
version = "0.0.0"
dependencies = [
"migration-core",
"migration-runner",
"serde",
]
[[package]]
name = "migration-runner"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"migration-core",
"migration-runner",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "migration-snapshot"
version = "0.0.0"
dependencies = [
"convert_case 0.12.0",
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -4366,6 +4292,7 @@ dependencies = [
"node-macro",
"smallvec",
"text-nodes",
"thiserror 2.0.18",
"vector-types",
]
@@ -4914,6 +4841,7 @@ dependencies = [
"raster-types",
"serde",
"spirv-std",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -4951,6 +4879,7 @@ dependencies = [
"node-macro",
"serde",
"serde_json",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
"wgpu",
@@ -5108,21 +5037,6 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
[[package]]
name = "regression"
version = "0.0.0"
dependencies = [
"clap",
"document-format",
"fern",
"graphene-cli",
"image",
"log",
"serde",
"serde_json",
"tokio",
]
[[package]]
name = "renderdoc-sys"
version = "1.1.0"
@@ -6212,13 +6126,13 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"ipsum",
"log",
"node-macro",
"parley",
"rand",
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"titlecase",
"tsify",
"unicode-segmentation",
@@ -6618,6 +6532,7 @@ dependencies = [
"node-macro",
"rand",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -6879,6 +6794,7 @@ dependencies = [
"repeat-nodes",
"rustc-hash 2.1.1",
"serde",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -6908,6 +6824,7 @@ dependencies = [
"rustc-hash 2.1.1",
"serde",
"serde_json",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
-12
View File
@@ -11,12 +11,6 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/migrations/core",
"document/migrations/macros",
"document/migrations/runner",
"document/migrations/formats",
"document/migrations/snapshot",
"document/migrations/nodes",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -43,7 +37,6 @@ members = [
"tools/third-party-licenses",
"tools/editor-message-tree",
"tools/node-docs",
"tools/regression",
"tools/web-editor-driver",
]
default-members = [
@@ -110,11 +103,6 @@ graph-craft = { path = "node-graph/graph-craft" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
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" }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-6
View File
@@ -23,8 +23,6 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
zip = ["document-container/zip"]
xz = ["document-container/xz"]
# Runs the format steps and node migrations the binary links (see migration-core) when a document opens, and persists the result.
migrations = ["conversion", "dep:migration-core", "dep:migration-runner"]
default = ["conversion", "zip", "xz"]
[dependencies]
@@ -32,8 +30,6 @@ document-container = { workspace = true }
document-graph-storage = { workspace = true, default-features = false }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
migration-core = { workspace = true, optional = true, features = ["typed"] }
migration-runner = { workspace = true, optional = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -43,8 +39,6 @@ thiserror = "2.0"
log = { workspace = true }
[dev-dependencies]
migration-core = { workspace = true, features = ["typed"] }
migration-formats = { workspace = true }
futures = { workspace = true }
graphene-resource = { workspace = true }
tempfile = "3"
-58
View File
@@ -121,45 +121,6 @@ impl Codec {
}
}
impl Codec {
/// Each value's bytes in `bytes`, unframed, so format migrations can transform them before they decode into the live types.
pub fn records(self, bytes: &[u8]) -> Result<Vec<&[u8]>, CodecError> {
match self {
Codec::Json | Codec::Postcard => Ok(vec![bytes]),
Codec::JsonLines => Ok(bytes.split(|&byte| byte == b'\n').map(trim_ascii).filter(|line| !line.is_empty()).collect()),
Codec::PostcardFrames => {
let mut records = Vec::new();
let mut remaining = bytes;
while !remaining.is_empty() {
let Some((length_bytes, tail)) = remaining.split_first_chunk::<4>() else {
return Err(CodecError::TruncatedLengthPrefix(remaining.len()));
};
let length = u32::from_be_bytes(*length_bytes) as usize;
if tail.len() < length {
return Err(CodecError::TruncatedFrame {
declared: length,
remaining: tail.len(),
});
}
let (record, after) = tail.split_at(length);
records.push(record);
remaining = after;
}
Ok(records)
}
}
}
/// Decode one record [`records`](Self::records) split out.
pub fn decode_record<T: DeserializeOwned>(self, record: &[u8]) -> Result<T, CodecError> {
match self {
Codec::Json | Codec::JsonLines => Ok(serde_json::from_slice(record)?),
Codec::Postcard | Codec::PostcardFrames => Ok(postcard::from_bytes(record)?),
}
}
}
struct JsonLineIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
@@ -339,25 +300,6 @@ mod tests {
assert!(matches!(result, Err(CodecError::ExpectedSingle)), "got {result:?}");
}
#[test]
fn records_split_every_codec_like_iter() {
let frames = frames();
for codec in [Codec::JsonLines, Codec::PostcardFrames] {
let mut buffer = Vec::new();
for frame in &frames {
codec.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = codec.records(&buffer).unwrap().into_iter().map(|record| codec.decode_record(record).unwrap()).collect();
assert_eq!(decoded, frames, "codec {codec:?}");
}
for codec in [Codec::Json, Codec::Postcard] {
let bytes = codec.write_single(&frames[0]).unwrap();
let records = codec.records(&bytes).unwrap();
assert_eq!(codec.decode_record::<Frame>(records[0]).unwrap(), frames[0], "codec {codec:?}");
}
}
#[test]
fn extensions_are_distinct() {
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
-4
View File
@@ -47,10 +47,6 @@ pub enum Error {
/// The requested export options are incoherent (e.g. neither registry nor history included).
#[error("invalid export options: {0}")]
InvalidExportOptions(&'static str),
/// A migration of the document failed while it opened.
#[cfg(feature = "migrations")]
#[error("migration error: {0}")]
Migration(#[from] migration_runner::RunnerError),
/// An export marked a resource for embedding but its bytes were absent from the byte store.
#[error("embedded resource {0} missing from the byte store")]
MissingResource(ResourceHash),
+1 -1
View File
@@ -8,9 +8,9 @@ use std::path::Path;
use graphene_resource::{LoadResource, Resource, ResourceHash};
use crate::SessionState;
use crate::error::Error;
use crate::layout::Layout;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
+1 -1
View File
@@ -6,7 +6,7 @@
use graphene_resource::ResourceHash;
pub trait Layout: Send + Sync {
pub trait Layout {
fn manifest_basename(&self) -> &str;
fn session_basename(&self) -> &str;
fn registry_basename(&self) -> &str;
+42 -70
View File
@@ -14,11 +14,9 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
#[cfg(feature = "migrations")]
use document_graph_storage::Rev;
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -28,21 +26,19 @@ pub mod error;
pub mod export;
pub mod io;
pub mod layout;
mod load;
pub mod manifest;
#[cfg(feature = "migrations")]
mod migrate;
pub mod persist;
pub mod resource;
pub mod session_state;
pub use codec::{Codec, CodecError};
pub use document_graph_storage::SessionState;
pub use error::Error;
pub use export::{ExportFormat, ExportOptions};
pub use io::ReadError;
pub use layout::{GddV1Layout, Layout};
pub use manifest::{Manifest, PayloadCodecs};
pub use resource::ResourceProxy;
pub use session_state::SessionState;
/// The default [`Layout`], so callers write `GddV1` for the common `Gdd<GddV1Layout>` handle.
pub type GddV1 = Gdd<GddV1Layout>;
@@ -85,8 +81,6 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
/// Whether opening ran a format step or node migration, and so rewrote the working copy.
pub(crate) migrated: bool,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -138,45 +132,28 @@ impl<L: Layout> Gdd<L> {
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only format migrations change the stored records"))]
let mut records = load::StoredRecords::read(&working, &layout, codecs).await?;
#[cfg(feature = "migrations")]
let format_outcome = migrate::migrate_format(&mut records, codecs, manifest.format_version)?;
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only format migrations change the decoded payloads"))]
let mut payloads = records.decode(codecs)?;
#[cfg(feature = "migrations")]
match format_outcome {
Some(migration_runner::HistoryOutcome::Rewritten) => {
// Records changed, so their content-addressed revs did too
let revs = migration_runner::rehash_deltas(payloads.history.as_deref_mut().unwrap_or_default());
let remap = |rev: Rev| revs.get(&rev).copied().unwrap_or(rev);
let state = &mut payloads.session;
state.head_rev = state.head_rev.map(remap);
state.last_broadcast_rev = state.last_broadcast_rev.map(remap);
state.redo_stack.iter_mut().for_each(|rev| *rev = remap(*rev));
}
Some(migration_runner::HistoryOutcome::Truncated) => {
let state = &mut payloads.session;
state.head_rev = None;
state.last_broadcast_rev = None;
state.redo_stack.clear();
}
Some(migration_runner::HistoryOutcome::Untouched) | None => {}
}
let load::DecodedPayloads {
registry,
history,
hot_log,
session: session_state,
} = payloads;
let session_state: SessionState = match io::exists(&working, layout.session_basename(), codecs.session).await {
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
false => SessionState::default(),
};
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let user = session_state.user_id;
let mut session = match (registry, history) {
(Some(registry), Some(history)) => Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter),
// Registry-only export: synthesize a history that reproduces this state.
(Some(registry), None) => Session::bootstrap_from_registry(peer, user, registry)?,
(None, history) => Session::replay_from_history(peer, user, history.unwrap_or_default(), session_state.next_node_counter)?,
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -188,32 +165,16 @@ impl<L: Layout> Gdd<L> {
session.restore_clock_counter(session_state.clock_counter);
// Before the hot log replays, so a retired op in it is dropped rather than staged again.
session.absorb_retired_marks(&session_state.retired_marks);
for hot_op in hot_log {
session.replay_hot_op(hot_op)?;
}
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only migrations change the opened document"))]
let mut gdd = Self {
Ok(Self {
session,
working,
layout,
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
migrated: false,
};
#[cfg(feature = "migrations")]
{
let migrated_nodes = gdd.migrate_nodes().await?;
if format_outcome.is_some() || migrated_nodes {
gdd.manifest.format_version = gdd.manifest.format_version.max(manifest::SUPPORTED_FORMAT_VERSION);
gdd.persist_all()?;
gdd.migrated = true;
}
}
Ok(gdd)
})
}
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
@@ -239,7 +200,6 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
migrated: false,
})
}
}
@@ -260,6 +220,23 @@ fn validate_manifest(manifest: &Manifest) -> Result<(), Error> {
Ok(())
}
async fn load_history<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec) -> Result<Vec<Delta>, Error> {
if !io::exists(working, layout.history_basename(), codec).await {
return Ok(Vec::new());
}
Ok(io::iter::<Delta>(working, layout.history_basename(), codec).await?)
}
async fn replay_hot_log<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec, session: &mut Session) -> Result<(), Error> {
if !io::exists(working, layout.hot_log_basename(), codec).await {
return Ok(());
}
for hot_op in io::iter::<HotOp>(working, layout.hot_log_basename(), codec).await? {
session.replay_hot_op(hot_op)?;
}
Ok(())
}
impl<L: Layout> Gdd<L> {
pub fn session(&self) -> &Session {
&self.session
@@ -283,11 +260,6 @@ impl<L: Layout> Gdd<L> {
&self.manifest
}
/// Whether opening ran a format step or node migration, and so rewrote the working copy.
pub fn migrated(&self) -> bool {
self.migrated
}
pub fn layout(&self) -> &L {
&self.layout
}
-62
View File
@@ -1,62 +0,0 @@
//! Reads a working copy's payloads as records before decoding them, so format migrations can run in between.
use document_container::{AnyContainer, AsyncContainer};
use document_graph_storage::{Delta, HotOp, Registry};
use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::PayloadCodecs;
use crate::{Codec, SessionState, io};
/// Each payload's records in their stored encoding. `None` is a payload the working copy doesn't have.
pub(crate) struct StoredRecords {
pub registry: Option<Vec<u8>>,
pub history: Option<Vec<Vec<u8>>>,
pub hot_log: Vec<Vec<u8>>,
pub session: Option<Vec<u8>>,
}
/// The payloads in the live types.
pub(crate) struct DecodedPayloads {
pub registry: Option<Registry>,
pub history: Option<Vec<Delta>>,
pub hot_log: Vec<HotOp>,
pub session: SessionState,
}
impl StoredRecords {
pub async fn read<L: Layout>(working: &AnyContainer, layout: &L, codecs: PayloadCodecs) -> Result<Self, Error> {
let single = |records: Option<Vec<Vec<u8>>>| records.and_then(|records| records.into_iter().next());
Ok(Self {
registry: single(read_records(working, layout.registry_basename(), codecs.registry).await?),
history: read_records(working, layout.history_basename(), codecs.history).await?,
hot_log: read_records(working, layout.hot_log_basename(), codecs.hot_log).await?.unwrap_or_default(),
session: single(read_records(working, layout.session_basename(), codecs.session).await?),
})
}
pub fn decode(self, codecs: PayloadCodecs) -> Result<DecodedPayloads, Error> {
Ok(DecodedPayloads {
registry: self.registry.map(|record| codecs.registry.decode_record(&record)).transpose()?,
history: self.history.map(|records| decode_all(records, codecs.history)).transpose()?,
hot_log: decode_all(self.hot_log, codecs.hot_log)?,
session: self.session.map(|record| codecs.session.decode_record(&record)).transpose()?.unwrap_or_default(),
})
}
}
fn decode_all<T: serde::de::DeserializeOwned>(records: Vec<Vec<u8>>, codec: Codec) -> Result<Vec<T>, crate::CodecError> {
records.iter().map(|record| codec.decode_record(record)).collect()
}
async fn read_records(working: &AnyContainer, basename: &str, codec: Codec) -> Result<Option<Vec<Vec<u8>>>, Error> {
let path = io::path_for(basename, codec);
if !working.exists(&path).await {
return Ok(None);
}
let bytes = working.read(&path).await?;
let records = codec.records(bytes.as_slice())?.into_iter().map(<[u8]>::to_vec).collect();
Ok(Some(records))
}
+1 -1
View File
@@ -10,7 +10,7 @@ pub const FORMAT_MAGIC: &str = "gdd";
/// Maximum manifest version this build can open. Bumped when manifest layout changes
/// in a way that older builds can't safely read.
pub const SUPPORTED_FORMAT_VERSION: u32 = 2;
pub const SUPPORTED_FORMAT_VERSION: u32 = 1;
/// The on-disk codec for each working-copy payload, recorded so reads/writes never have to probe
/// the filesystem to discover it. The manifest itself is excluded: it is always JSON, since it must
-180
View File
@@ -1,180 +0,0 @@
//! Runs the migrations this binary links on a document as it opens: format steps over the stored records, then node migrations
//! over history. See `node-graph/rfcs/document-format-migrations.md`.
use std::collections::{BTreeSet, HashMap};
use document_container::AsyncContainer;
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, TimeStamp, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, migrate_history, references, run_format_migrations};
use crate::error::Error;
use crate::layout::Layout;
use crate::load::StoredRecords;
use crate::manifest::{PayloadCodecs, SUPPORTED_FORMAT_VERSION};
use crate::{Codec, Gdd};
/// Bring `records` from `format_version` to [`SUPPORTED_FORMAT_VERSION`]. `None` when they already are.
pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs, format_version: u32) -> Result<Option<HistoryOutcome>, Error> {
if format_version >= SUPPORTED_FORMAT_VERSION {
return Ok(None);
}
let payload = |record: &Vec<u8>, codec: Codec| Payload::new(record.clone(), payload_codec(codec));
let mut payloads = DocumentPayloads {
format_version,
registry: records.registry.as_ref().map(|record| payload(record, codecs.registry)),
history: records.history.iter().flatten().map(|record| payload(record, codecs.history)).collect(),
hot_log: records.hot_log.iter().map(|record| payload(record, codecs.hot_log)).collect(),
session: records.session.as_ref().map(|record| payload(record, codecs.session)),
};
let outcome = run_format_migrations(&migration_core::registered_format_migrations(), &mut payloads, SUPPORTED_FORMAT_VERSION)?;
log::info!("Migrated the document format from version {format_version} to {SUPPORTED_FORMAT_VERSION}");
records.registry = payloads.registry.map(|payload| payload.bytes);
records.history = match outcome {
HistoryOutcome::Truncated => None,
_ => records.history.as_ref().map(|_| payloads.history.into_iter().map(|payload| payload.bytes).collect()),
};
records.hot_log = payloads.hot_log.into_iter().map(|payload| payload.bytes).collect();
records.session = payloads.session.map(|payload| payload.bytes);
Ok(Some(outcome))
}
fn payload_codec(codec: Codec) -> PayloadCodec {
match codec {
Codec::Json | Codec::JsonLines => PayloadCodec::Json,
Codec::Postcard | Codec::PostcardFrames => PayloadCodec::Postcard,
}
}
impl<L: Layout> Gdd<L> {
/// Rewrite history through every registered node migration whose source declaration it references. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self) -> Result<bool, Error> {
let migrations = migration_core::registered_migrations();
if migrations.is_empty() {
return Ok(false);
}
let declarations = self.declarations(self).await;
let resolver = DocumentDeclarations::new(&declarations, &migrations, self.session.peer());
let hot_ops = self.session.hot_log().iter().map(|hot_op| &hot_op.op);
let kinds: Vec<_> = self.session.history().map(|delta| &delta.kind).chain(hot_ops).collect();
let pending: Vec<Declaration> = migrations
.iter()
.map(|migration| migration.source())
.filter(|source| kinds.iter().any(|kind| references(kind, *source, &resolver)))
.collect();
if pending.is_empty() {
return Ok(false);
}
// Hot ops join history first, so they migrate with it
self.session.retire_all()?;
let history: Vec<Delta> = self.session.history().cloned().collect();
let rewritten = migrate_history(&migrations, history, &resolver)?;
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
let head = self.session.head_rev().and_then(remap);
let redo_stack = self.session.redo_stack().iter().filter_map(|rev| remap(*rev)).collect();
let registry = registry_at(&rewritten.deltas, head)?;
let previous = &self.session;
let mut session = Session::load(previous.peer(), previous.user(), registry, rewritten.deltas, head, redo_stack, previous.next_node_counter());
if let Some(rev) = previous.last_broadcast_rev().and_then(remap) {
session.publish_up_to(rev);
}
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter());
session.absorb_retired_marks(previous.retired_marks());
self.session = session;
// Declarations the migrations introduced need their bytes next to the other resources
let referenced = self.session.all_declaration_resources();
for declaration in resolver.encoded.values().filter(|declaration| referenced.contains_key(&declaration.id)) {
let path = self.layout.resource_path(&declaration.hash);
if !self.working.exists(&path).await {
self.working.write_non_blocking(&path, &declaration.bytes)?;
}
}
let names: Vec<String> = pending.iter().map(ToString::to_string).collect();
log::info!("Migrated nodes from {}", names.join(", "));
Ok(true)
}
}
/// The registry after replaying `deltas` up to and including `head`.
fn registry_at(deltas: &[Delta], head: Option<Rev>) -> Result<Registry, Error> {
let mut registry = Registry::default();
let Some(head) = head else { return Ok(registry) };
for delta in deltas {
apply_retired_op(&mut registry, delta.kind.clone(), delta.timestamp)?;
if delta.id == head {
break;
}
}
Ok(registry)
}
/// Resolves a document's declaration resources to the declarations migrations name, by identifier and version.
struct DocumentDeclarations {
known: HashMap<ResourceId, Declaration>,
encoded: HashMap<Declaration, EncodedDeclaration>,
peer: PeerId,
}
impl DocumentDeclarations {
fn new(declarations: &Declarations, migrations: &[&'static dyn NodeMigration], peer: PeerId) -> Self {
let named: BTreeSet<Declaration> = migrations
.iter()
.flat_map(|migration| [migration.source(), migration.target()].into_iter().chain(migration.pins().iter().copied()))
.collect();
let identifiers: HashMap<&str, &'static str> = named.iter().map(|declaration| (declaration.identifier, declaration.identifier)).collect();
let mut known = HashMap::new();
for (id, proto) in declarations {
if let Some(identifier) = identifiers.get(proto.identifier.as_str()) {
known.insert(*id, Declaration::new(identifier, proto.version));
}
}
let mut encoded = HashMap::new();
for declaration in named {
match EncodedDeclaration::new(declaration.identifier.to_string(), declaration.version) {
Ok(declaration_resource) => {
known.insert(declaration_resource.id, declaration);
encoded.insert(declaration, declaration_resource);
}
Err(error) => log::error!("Encoding the declaration {declaration} failed: {error}"),
}
}
Self { known, encoded, peer }
}
}
impl DeclarationResolver for DocumentDeclarations {
fn declaration(&self, resource: ResourceId) -> Option<Declaration> {
self.known.get(&resource).copied()
}
fn resource(&self, declaration: Declaration) -> ResourceId {
match self.encoded.get(&declaration) {
Some(encoded) => encoded.id,
None => {
log::error!("No migration names the declaration {declaration}, so it has no resource");
ResourceId::default()
}
}
}
fn resource_entry(&self, declaration: Declaration) -> Option<ResourceEntry> {
let encoded = self.encoded.get(&declaration)?;
Some(ResourceEntry::embedded(encoded.hash, self.peer, TimeStamp::ORIGIN))
}
}
+1 -19
View File
@@ -10,10 +10,10 @@ use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
use crate::SessionState;
use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::Manifest;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
impl<L: Layout> Gdd<L> {
@@ -182,24 +182,6 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Rewrite every payload and the manifest from memory, after opening changed what the files hold.
#[cfg(feature = "migrations")]
pub(crate) fn persist_all(&mut self) -> Result<(), Error> {
self.rewrite_history()?;
self.persist_registry_snapshot()?;
let mut hot_buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
self.working
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
self.persist_session_state()?;
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &self.manifest)?;
Ok(())
}
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
fn rewrite_history(&mut self) -> Result<(), Error> {
@@ -1,10 +1,10 @@
//! Persistent cursor state for the local peer. Separate from the document manifest because the
//! Persistent cursor state for the local peer. Separate from [`crate::Manifest`] because the
//! manifest describes document identity (what this document *is*), while [`SessionState`]
//! describes where the local peer's cursor sits inside it.
//!
//! Lives in `session.json`. Rewritten on retirement.
use super::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
use document_graph_storage::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
-111
View File
@@ -1,111 +0,0 @@
// Opening a document runs the format steps and node migrations the binary links, and persists what they changed.
#![cfg(feature = "migrations")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Error, GddV1, GddV1Layout, manifest};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
use migration_core::rename;
use migration_formats as _;
rename!("test_nodes::FadeNode"@1 => "test_nodes::OpacityNode"@2);
fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
let node = |identifier: &'static str| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: nodes.iter().map(|(id, identifier)| (NodeId(*id), node(identifier))).collect(),
..Default::default()
}
}
fn create() -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
}
fn implementations(gdd: &GddV1) -> Vec<Implementation> {
let mut nodes: Vec<_> = gdd.registry().node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
nodes.into_iter().map(|(_, node)| node.implementation().clone()).collect()
}
#[test]
fn opening_migrates_nodes_and_persists_the_result() {
block_on(async {
let mut gdd = create();
gdd.commit_from_runtime(&network_of(&[(1, "test_nodes::FadeNode")]), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap();
let (working, layout) = gdd.into_storage();
let migrated = GddV1::open_in(working, layout).await.unwrap();
let target = EncodedDeclaration::new("test_nodes::OpacityNode".to_string(), 2).unwrap();
assert_eq!(implementations(&migrated), [Implementation::ProtoNode(target.id)]);
assert!(migrated.registry().resources.contains_key(&target.id), "the target declaration is a registered resource");
assert_eq!(migrated.declarations(&migrated).await[&target.id], target.proto, "its bytes are stored");
assert_eq!(migrated.manifest().format_version, manifest::SUPPORTED_FORMAT_VERSION);
assert!(migrated.migrated());
// The rewritten history persisted, so a reopen has nothing left to migrate
let registry = migrated.registry().clone();
let (working, layout) = migrated.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.registry().value_equal(&registry));
assert!(!reopened.migrated());
});
}
#[test]
fn undo_and_redo_cross_migrated_history() {
block_on(async {
let store = HashMapResourceStorage::new();
let mut gdd = create();
gdd.commit_from_runtime(&network_of(&[(1, "test_nodes::FadeNode")]), &NoMetadata, &ResourceRegistry::new(), &store)
.unwrap();
gdd.commit_from_runtime(&network_of(&[(1, "test_nodes::FadeNode"), (2, "test_nodes::FadeNode")]), &NoMetadata, &ResourceRegistry::new(), &store)
.unwrap();
gdd.undo().unwrap();
let (working, layout) = gdd.into_storage();
let mut migrated = GddV1::open_in(working, layout).await.unwrap();
let target = Implementation::ProtoNode(EncodedDeclaration::new("test_nodes::OpacityNode".to_string(), 2).unwrap().id);
assert_eq!(implementations(&migrated), std::slice::from_ref(&target), "the undone node stays undone");
migrated.redo().unwrap();
assert_eq!(implementations(&migrated), [target.clone(), target], "redo brings it back migrated");
});
}
#[test]
fn opening_steps_the_format_version() {
block_on(async {
let mut gdd = create();
gdd.update_manifest(|manifest| manifest.format_version = 1).unwrap();
let (working, layout) = gdd.into_storage();
let migrated = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(migrated.manifest().format_version, 2);
let (working, layout) = migrated.into_storage();
assert_eq!(GddV1::open_in(working, layout).await.unwrap().manifest().format_version, 2, "the bump persisted");
});
}
#[test]
fn a_missing_format_step_fails_the_open() {
block_on(async {
let mut gdd = create();
gdd.update_manifest(|manifest| manifest.format_version = 0).unwrap();
let (working, layout) = gdd.into_storage();
let error = GddV1::open_in(working, layout).await.err().unwrap();
assert!(matches!(error, Error::Migration(ref runner_error) if runner_error.to_string().contains("version 0")), "{error}");
});
}
+21 -1
View File
@@ -1,4 +1,5 @@
use crate::{AttributeDelta, AttributeValue, Attributes, TimeStamp, Value, ValueError, from_value, to_value};
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, btree_map};
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
@@ -7,6 +8,16 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
@@ -22,6 +33,15 @@ impl AttributeValue {
}
}
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
/// its floor, when the map was last written whole.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
floor: TimeStamp,
}
impl Attributes {
pub fn new() -> Self {
Self::default()
+151 -7
View File
@@ -1,4 +1,32 @@
use crate::{Attributes, Delta, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Value, attr, compute_rev};
use crate::{
Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
/// Primary parent; `None` for the root delta.
pub parent: Option<Rev>,
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default)]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
@@ -54,12 +82,6 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// Take over `original`'s annotations and retirement time, for a delta that replaces it in rewritten history.
pub fn carry_annotations(&mut self, original: &Delta) {
self.attributes = original.attributes.clone();
self.retired_at_ms = original.retired_at_ms;
}
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
@@ -79,6 +101,128 @@ impl Delta {
}
}
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
node: Node,
},
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
RemoveNode {
id: NodeId,
snapshot: Node,
},
ChangeNodeInput {
id: NodeId,
index: u32,
new_input: NodeInput,
},
/// A node's whole input list, for a change to the number or order of its slots that the
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
/// per-slot edits are lost, which is inherent to the indices themselves moving.
///
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
/// with attribute ops on the same node instead of reverting them.
SetNodeInputs {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
},
ChangeNodeInputAttribute {
id: NodeId,
index: u32,
delta: AttributeDelta,
},
/// LWW per slot. `export == None` removes the slot.
SetNetworkExport {
id: NetworkId,
index: u32,
export: Option<NodeInput>,
},
/// Per-network attribute change, LWW per key. Mirrors `ChangeDocumentAttribute`.
ChangeNetworkAttribute {
id: NetworkId,
delta: AttributeDelta,
},
AddNetwork {
id: NetworkId,
network: Network,
},
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
},
/// LWW on a resource's resolved content hash. Creates the resource entry if absent.
/// Concurrent resolves agree by construction (the hash is content-derived), so LWW is safe.
SetResourceHash {
id: ResourceId,
hash: Option<ResourceHash>,
},
/// Remove a whole resource entry. `snapshot` is the state of the resource before it was removed.
RemoveResource {
id: ResourceId,
snapshot: ResourceEntry,
},
/// Add (or LWW-overwrite) one entry in a resource's source fallback chain. The source body is
/// type-erased; `key` carries the fractional priority + peer that order it. Add-wins: concurrent
/// adds at distinct keys all survive. Creates the resource entry if absent.
AddSource {
id: ResourceId,
key: SourceKey,
source: Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
RegisterPeer {
peer: PeerId,
user: UserId,
},
ChangeDocumentAttribute {
delta: AttributeDelta,
},
/// Joins divergent history tips into one shared node. A registry no-op on replay (it only collapses
/// tips so `head` stays a single `Rev`); the joined tips are `Delta::parent` (the lowest `Rev`) plus
/// these `extra_parents` (sorted). Identity is the parent set alone, so two peers merging the same
/// tips mint the identical delta and it dedups.
Merge {
extra_parents: Vec<Rev>,
},
Meta,
// Allow for future delta types without a model change
Other(Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
}
#[cfg(test)]
mod tests {
use super::*;
+39 -57
View File
@@ -1,6 +1,6 @@
use std::collections::HashSet;
use crate::{AttributeDelta, NetworkId, NodeId, Registry, RegistryDelta, ResourceEntry, ResourceId};
use crate::{AttributeDelta, NetworkId, Node, NodeId, Registry, RegistryDelta, ResourceEntry, ResourceId};
/// Collect a `HashSet` walk (difference/intersection) into ascending order. The sets iterate in
/// random order, so sorting keeps `compute_deltas` emitting a deterministic delta sequence.
@@ -51,8 +51,12 @@ pub fn compute_deltas(from: &Registry, to: &Registry) -> Vec<RegistryDelta> {
let from_node = &from.node_instances[&node_id];
let to_node = &to.node_instances[&node_id];
// A moved node has no in-place op, so the only path is remove + re-add
if from_node.network != to_node.network {
// No `ChangeImplementation` op; the only path is remove + re-add. Same for input-count and
// containing-network changes (a moved node has no in-place op either). `inputs_attributes` is
// checked too: the per-slot loops below `zip` only the shared prefix, so a length change there
// must force a remove + re-add rather than silently dropping the extra slots.
let structural_change = !nodes_have_same_implementation(from_node, to_node) || from_node.inputs.len() != to_node.inputs.len() || from_node.network != to_node.network;
if structural_change {
deltas.push(RegistryDelta::RemoveNode {
id: node_id,
snapshot: from_node.clone(),
@@ -61,34 +65,16 @@ pub fn compute_deltas(from: &Registry, to: &Registry) -> Vec<RegistryDelta> {
continue;
}
if from_node.implementation != to_node.implementation {
deltas.push(RegistryDelta::SetNodeImplementation {
id: node_id,
implementation: to_node.implementation.clone(),
});
}
// A changed slot count moves indices, so the whole list is restated instead of diffed per slot
let inputs_resized = from_node.inputs.len() != to_node.inputs.len();
if inputs_resized {
deltas.push(RegistryDelta::SetNodeInputs {
id: node_id,
inputs: to_node.inputs.clone(),
});
}
// Compare by value, ignoring the per-slot timestamp. Timestamps are derived from the diff
// (assigned by the caller via clock.tick), not part of the diff itself: a slot whose value
// is unchanged but whose timestamp differs should not emit a delta.
if !inputs_resized {
for (input_idx, (from_slot, to_slot)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
if from_slot.input != to_slot.input {
deltas.push(RegistryDelta::ChangeNodeInput {
id: node_id,
index: input_idx as u32,
new_input: to_slot.input.clone(),
});
}
for (input_idx, (from_slot, to_slot)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
if from_slot.input != to_slot.input {
deltas.push(RegistryDelta::ChangeNodeInput {
id: node_id,
index: input_idx as u32,
new_input: to_slot.input.clone(),
});
}
}
@@ -96,15 +82,13 @@ pub fn compute_deltas(from: &Registry, to: &Registry) -> Vec<RegistryDelta> {
deltas.push(RegistryDelta::ChangeNodeAttribute { id: node_id, delta });
}
if !inputs_resized {
for (input_idx, (from_input, to_input)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
for delta in compute_attribute_deltas(&from_input.attributes, &to_input.attributes) {
deltas.push(RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: input_idx as u32,
delta,
});
}
for (input_idx, (from_input, to_input)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
for delta in compute_attribute_deltas(&from_input.attributes, &to_input.attributes) {
deltas.push(RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: input_idx as u32,
delta,
});
}
}
}
@@ -200,6 +184,15 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
}
}
fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
use crate::Implementation::*;
match (&a.implementation, &b.implementation) {
(ProtoNode(a_id), ProtoNode(b_id)) => a_id == b_id,
(Network(a_id), Network(b_id)) => a_id == b_id,
_ => false,
}
}
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
@@ -279,12 +272,15 @@ mod tests {
assert!(matches!(deltas[0], RegistryDelta::AddNode { id: NodeId(42), .. }));
}
/// A changed slot count restates the whole input list: the per-slot diff only `zip`s the shared prefix, so it
/// would drop the extra slots, and a remove + re-add would clear the node's attributes.
/// A change in `inputs_attributes` length is structural: the per-slot diff only `zip`s the shared
/// prefix, so it must force a remove + re-add rather than dropping the extra attribute slots.
#[test]
fn compute_deltas_restates_inputs_on_length_change() {
fn compute_deltas_treats_inputs_attributes_length_change_as_structural() {
// Same implementation/inputs/network in both registries; only `inputs_attributes` length differs.
let base = Node::dummy();
let mut from = Registry::default();
from.node_instances.insert(NodeId(42), Node::dummy());
from.node_instances.insert(NodeId(42), base.clone());
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().inputs.push(crate::InputSlot {
@@ -295,25 +291,11 @@ mod tests {
let deltas = compute_deltas(&from, &to);
assert!(
matches!(deltas.as_slice(), [RegistryDelta::SetNodeInputs { id: NodeId(42), inputs }] if inputs.len() == 1),
"a slot count change must emit one SetNodeInputs, got {deltas:?}"
deltas.iter().any(|delta| matches!(delta, RegistryDelta::RemoveNode { id: NodeId(42), .. })) && deltas.iter().any(|delta| matches!(delta, RegistryDelta::AddNode { id: NodeId(42), .. })),
"an inputs_attributes length change must emit RemoveNode + AddNode, got {deltas:?}"
);
}
/// Swapping what a node computes keeps its identity and attributes, so it must not remove and re-add the node.
#[test]
fn compute_deltas_swaps_implementation_in_place() {
let mut from = Registry::default();
from.node_instances.insert(NodeId(42), Node::dummy());
let mut to = from.clone();
let implementation = crate::Implementation::ProtoNode(crate::ResourceId::new());
to.node_instances.get_mut(&NodeId(42)).unwrap().implementation = implementation.clone();
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas, vec![RegistryDelta::SetNodeImplementation { id: NodeId(42), implementation }]);
}
#[test]
fn test_compute_deltas_change_network_attribute() {
use crate::TimeStamp;
+1 -14
View File
@@ -3,7 +3,7 @@ use std::hash::Hash;
use crate::{
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
PeerId, PeerRegistration, Prior, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
};
#[derive(Clone, Debug)]
@@ -365,19 +365,6 @@ impl Document {
}
}
/// Apply `op` at `timestamp` the way replaying a retired delta does, returning what it overwrote for the delta's `reverse`.
/// For building history outside a [`Session`](crate::Session), such as a migration's history rewrite.
pub fn apply_retired_op(registry: &mut Registry, op: RegistryDelta, timestamp: TimeStamp) -> Result<Vec<Prior>, CrdtError> {
let reverse = crate::prior::capture(registry, &op);
let mut scratch = Document::empty(timestamp.peer, UserId::default());
scratch.working_registry = std::mem::take(registry);
let result = scratch.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent);
*registry = scratch.working_registry;
result.map(|()| reverse)
}
/// An entity whose existence and every field are last-writer-wins on a timestamp.
pub(crate) trait Entity: Sized {
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
+8 -31
View File
@@ -1,7 +1,6 @@
use std::collections::HashMap;
use core_types::Context;
use core_types::registry::NODE_METADATA;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
@@ -139,32 +138,6 @@ pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
postcard::to_stdvec(&value).map_err(|error| error.to_string())
}
/// A declaration with no attributes, as runtime conversion stores `identifier@version` and node migrations switch nodes to it.
pub struct EncodedDeclaration {
pub id: ResourceId,
pub hash: ResourceHash,
pub bytes: Vec<u8>,
pub proto: ProtoNode,
}
impl EncodedDeclaration {
pub fn new(identifier: String, version: u32) -> Result<Self, String> {
let proto = ProtoNode {
identifier,
version,
attributes: Default::default(),
};
let bytes = encode_declaration(&proto)?;
let hash = ResourceHash::from(bytes.as_slice());
Ok(Self {
id: ResourceId::from_hash(&hash),
hash,
bytes,
proto,
})
}
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
@@ -698,10 +671,14 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
return Ok(Implementation::ProtoNode(*id));
}
// Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1);
let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
let proto = ProtoNode {
identifier: identifier_str.clone(),
attributes: Default::default(),
};
// Content-address the declaration: serialize, hash, derive a deterministic id.
let bytes = encode_declaration(&proto).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
let hash = ResourceHash::from(bytes.as_slice());
let id = ResourceId::from_hash(&hash);
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
-32
View File
@@ -250,35 +250,3 @@ impl History {
Ok(())
}
}
/// Recompute every delta's content-addressed `Rev` after delta payloads were rewritten, walking in
/// topological order and remapping parent links (including `Merge` extra parents) along the way.
/// Returns the old → new mapping for remapping cursors (`head`, redo stack, broadcast tip).
pub fn rehash_deltas(deltas: &mut [Delta]) -> HashMap<Rev, Rev> {
fn remap_merge_parents(kind: &mut RegistryDelta, mapping: &HashMap<Rev, Rev>) {
if let RegistryDelta::Merge { extra_parents } = kind {
for parent in extra_parents.iter_mut() {
if let Some(new) = mapping.get(parent) {
*parent = *new;
}
}
}
}
let mut mapping: HashMap<Rev, Rev> = HashMap::new();
for delta in deltas.iter_mut() {
if let Some(parent) = delta.parent.as_mut()
&& let Some(new) = mapping.get(parent)
{
*parent = *new;
}
remap_merge_parents(&mut delta.kind, &mapping);
let new_id = delta.recomputed_id();
mapping.insert(delta.id, new_id);
delta.id = new_id;
}
mapping
}
+40 -1
View File
@@ -1,6 +1,18 @@
use crate::{NetworkId, NodeId, PeerId, RegistryDelta, Rev, TimeStamp};
use crate::RegistryDelta;
use serde::{Deserialize, Serialize};
/// Stable, document-scoped identity for a node. Minted as a truncated `blake3(peer, counter)` so it
/// reproduces across `to_runtime` -> `from_runtime` round trips. Used purely as an opaque key.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub u64);
/// Stable identity for a node network. `ROOT_NETWORK` for the renderable graph; nested networks get a
/// path-derived ID via `owned_network_id`. Used purely as an opaque key.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NetworkId(pub u64);
impl std::fmt::Display for NodeId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
@@ -13,6 +25,14 @@ impl std::fmt::Display for NetworkId {
}
}
/// Content-addressed identity for a `Delta`.
/// 128-bit blake3 truncation: comfortable collision headroom for any plausible document lifetime
/// without being adversarial-grade. Same delta content always produces the same `Rev`. Non-zero so
/// `Option<Rev>` (a missing/root parent) is niche-optimized to the same size as a bare `Rev`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Rev(pub std::num::NonZeroU128);
impl Rev {
/// Wrap a raw value, or `None` if it is zero.
pub fn new(value: u128) -> Option<Self> {
@@ -39,6 +59,25 @@ pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PeerId(pub u64);
/// Per-human identity. Stable across devices (one user, many devices). Used for identity display
/// and undo-chain walking. Derived from `PeerId` via `Registry.peer_users`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UserId(pub u64);
/// Lamport timestamp with a peer-ID tiebreak. Higher counter wins; ties broken by peer.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct TimeStamp {
pub counter: u64,
pub peer: PeerId,
}
impl TimeStamp {
/// Pre-edit origin. Used by initial `from_runtime` conversion before any edits have happened.
pub const ORIGIN: Self = TimeStamp { counter: 0, peer: PeerId(0) };
+9 -6
View File
@@ -10,7 +10,6 @@ pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod schema;
pub mod session;
mod touched;
pub mod value;
@@ -23,18 +22,22 @@ pub mod metadata_source;
pub mod to_runtime;
pub use attributes::*;
pub use crdt::*;
pub use document::*;
pub use history::{History, rehash_deltas};
pub use history::History;
pub use ids::*;
pub use schema::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use touched::Touched;
pub use value::{ValueError, from_value, to_value};
pub use value::{Value, ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
EncodedDeclaration, PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes,
encode_node_ui_attributes, node_value_resource_refs, value_resource_ref,
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
node_value_resource_refs, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
+93 -19
View File
@@ -1,5 +1,27 @@
use crate::registry::attributes_value_equal;
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub(crate) network: NetworkId,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) network_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) attributes: Attributes,
}
impl Node {
pub fn implementation(&self) -> &Implementation {
@@ -15,21 +37,6 @@ impl Node {
self.network
}
// Mutable access for edits on a registry clone that is diffed back into deltas;
// live-session edits go through the delta paths instead.
pub fn implementation_mut(&mut self) -> &mut Implementation {
&mut self.implementation
}
pub fn inputs_mut(&mut self) -> &mut Vec<InputSlot> {
&mut self.inputs
}
pub fn attributes_mut(&mut self) -> &mut Attributes {
&mut self.attributes
}
pub fn set_network(&mut self, network: NetworkId) {
self.network = network;
}
/// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps.
pub fn value_equal(&self, other: &Self) -> bool {
if self.implementation != other.implementation || self.network != other.network {
@@ -67,10 +74,19 @@ impl Node {
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(crate::ResourceId::new()), 0)
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
}
}
/// One positional input. The timestamp drives LWW on concurrent `ChangeNodeInput` ops targeting
/// the same `(node_id, input_idx)`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
}
impl InputSlot {
/// A slot holding nothing, stamped `timestamp`.
pub fn unset(timestamp: TimeStamp) -> Self {
@@ -87,6 +103,47 @@ impl InputSlot {
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeInput {
Node {
id: NodeId,
index: u32,
},
Value {
value: Value,
exposed: bool,
},
Scope(Cow<'static, str>),
Import {
index: u32,
},
/// Marker; the `DocumentNodeMetadata` lives in `inputs_attributes`.
Reflection,
Other,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Implementation {
/// References a proto-node declaration resource (see [`ProtoNode`]); the binding to content lives
/// in `Registry.resources` like any other resource.
ProtoNode(ResourceId),
Network(NetworkId),
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// When the export list last changed shape; see [`Node::inputs_timestamp`](crate::Node).
#[serde(default)]
pub(crate) exports_timestamp: TimeStamp,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
}
impl Network {
/// True if both networks agree on every value-bearing field, ignoring slot/attribute timestamps.
pub fn value_equal(&self, other: &Self) -> bool {
@@ -107,10 +164,27 @@ impl Network {
}
}
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
}
/// Content of a proto-node declaration. Stored as a content-addressed resource (serialized bytes
/// keyed by `ResourceHash`, held by the `Gdd` byte store) and referenced from
/// `Implementation::ProtoNode(ResourceId)`. `document-graph-storage` itself only holds the reference.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProtoNode {
pub identifier: String,
pub attributes: Attributes,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ExportSlot, NodeId, TimeStamp};
use crate::TimeStamp;
fn target_slot(node_id: u64) -> ExportSlot {
ExportSlot {
+105 -1
View File
@@ -1,7 +1,111 @@
use crate::{AttributeValue, Implementation, InputSlot, Network, NetworkField, NetworkId, Node, NodeField, NodeId, NodeInput, Prior, Registry, RegistryDelta, ResourceId, Tombstone};
use crate::{
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
Tombstone,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::hash::Hash;
/// What a slot held before a delta wrote it, stamps included. Undo puts it back bypassing LWW, so the registry is again
/// the fold of history up to the delta's parent. Never sent or applied as an op.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
/// The whole entity, live, tombstoned, or absent. Restoring an absent one leaves no tombstone, so undoing an addition erases it.
Node {
id: NodeId,
node: Node,
},
RemovedNode {
id: NodeId,
tombstone: Tombstone<Node>,
},
AbsentNode {
id: NodeId,
},
Network {
id: NetworkId,
network: Network,
},
RemovedNetwork {
id: NetworkId,
tombstone: Tombstone<Network>,
},
AbsentNetwork {
id: NetworkId,
},
Resource {
id: ResourceId,
resource: ResourceEntry,
},
RemovedResource {
id: ResourceId,
tombstone: Tombstone<ResourceEntry>,
},
AbsentResource {
id: ResourceId,
},
/// One field of a live node, and the node's presence, which every write moves.
NodeField {
id: NodeId,
presence: TimeStamp,
field: NodeField,
},
/// One field of a live network, and its presence.
NetworkField {
id: NetworkId,
presence: TimeStamp,
field: NetworkField,
},
DocumentAttribute {
key: String,
previous: Option<AttributeValue>,
},
PeerUser {
peer: PeerId,
previous: Option<PeerRegistration>,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
/// Only the presence moved, by a reference from another entity's op.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Input {
index: u32,
previous: InputSlot,
},
InputAttribute {
index: u32,
key: String,
previous: Option<AttributeValue>,
},
Inputs {
previous: Vec<InputSlot>,
inputs_timestamp: TimeStamp,
},
Implementation {
previous: Implementation,
implementation_timestamp: TimeStamp,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
/// Only the presence moved, by a node added to or implemented by it.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Exports {
previous: Vec<ExportSlot>,
},
}
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
let mut priors = Vec::new();
+44 -3
View File
@@ -1,16 +1,57 @@
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
/// revives the entity.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
pub networks: HashMap<NetworkId, Network>,
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub timestamp: TimeStamp,
}
/// A removed entity's content, for reviving it, and its removal stamp.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub timestamp: TimeStamp,
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&crate::Node> {
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&crate::Network> {
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
+149 -2
View File
@@ -1,5 +1,27 @@
use crate::{PeerId, Priority, ResourceEntry, SourceKey, SourceValue, TimeStamp, Value, from_value, to_value};
use graphene_resource::ResourceHash;
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Ordering key for an entry in a resource's source chain: fractional `priority`, with `peer` as
/// the tiebreak so concurrent insertions at the same priority converge deterministically.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SourceKey {
pub priority: Priority,
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, which readers see as absent.
#[serde(default)]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
@@ -12,6 +34,67 @@ impl SourceValue {
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
/// plus the resolved content hash. The source chain is an add-wins ordered set (concurrent
/// additions all survive); the hash is last-writer-wins (concurrent resolves of the same logical
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition; a key the chain lacks is deleted as of then.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
impl<'de> Deserialize<'de> for ResourceEntry {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
// The `binary_search`-based accessors require `sources` sorted by `SourceKey` with unique keys.
// On-disk data (older writers, hand edits) can't be trusted to preserve either, so re-sort and
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
if later_key != kept_key {
return false;
}
if later_value.timestamp > kept_value.timestamp {
*kept_value = later_value.clone();
}
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
impl ResourceEntry {
/// A resource backed by a single `DataSource::Embedded` fallback resolved to `hash`. Both the
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
@@ -122,6 +205,70 @@ impl ResourceEntry {
}
}
/// All resources referenced by the document, keyed by stable per-document [`ResourceId`]. Replicates
/// through the normal CmRDT path; bytes live in content-addressed storage keyed by [`ResourceHash`].
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
/// Fractional priority for ordering a resource's source chain. New sources are inserted by picking
/// a value strictly between two neighbors, so concurrent insertions elsewhere never collide; an
/// exact tie between two peers inserting at the same gap is broken by `PeerId` in [`SourceKey`].
/// `f64` precision is ample for the short fallback chains resources carry in practice.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "f64")]
pub struct Priority(f64);
impl Priority {
/// Rejects non-finite input. The field is private and deserialization routes through here, so a
/// `Priority` is always finite, keeping its `Ord`/`Hash`/`Eq` agreement sound.
pub fn new(value: f64) -> Result<Self, NonFinitePriority> {
if value.is_finite() { Ok(Self(value)) } else { Err(NonFinitePriority(value)) }
}
pub fn value(self) -> f64 {
self.0
}
}
impl TryFrom<f64> for Priority {
type Error = NonFinitePriority;
fn try_from(value: f64) -> Result<Self, Self::Error> {
Self::new(value)
}
}
/// A [`Priority`] was constructed from a `NaN` or infinite value.
#[derive(Debug, thiserror::Error)]
#[error("priority must be finite, got {0}")]
pub struct NonFinitePriority(pub f64);
// `total_cmp` drives `Ord`, `Hash`, and `Eq` together so `Priority` is a sound `BTree`/`Hash` key:
// a derived `PartialEq` would disagree with this ordering on `-0.0` and `NaN`.
impl PartialEq for Priority {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Priority {}
impl Ord for Priority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for Priority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl std::hash::Hash for Priority {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1,22 +0,0 @@
use super::{TimeStamp, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
/// its floor, when the map was last written whole.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
pub(crate) entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
pub(crate) floor: TimeStamp,
}
-149
View File
@@ -1,149 +0,0 @@
use super::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, Rev, SourceKey, TimeStamp, UserId, Value};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
/// Primary parent; `None` for the root delta.
pub parent: Option<Rev>,
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default)]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
node: Node,
},
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
RemoveNode {
id: NodeId,
snapshot: Node,
},
ChangeNodeInput {
id: NodeId,
index: u32,
new_input: NodeInput,
},
/// A node's whole input list, for a change to the number or order of its slots that the
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
/// per-slot edits are lost, which is inherent to the indices themselves moving.
///
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
/// with attribute ops on the same node instead of reverting them.
SetNodeInputs {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
},
ChangeNodeInputAttribute {
id: NodeId,
index: u32,
delta: AttributeDelta,
},
/// LWW per slot. `export == None` removes the slot.
SetNetworkExport {
id: NetworkId,
index: u32,
export: Option<NodeInput>,
},
/// Per-network attribute change, LWW per key. Mirrors `ChangeDocumentAttribute`.
ChangeNetworkAttribute {
id: NetworkId,
delta: AttributeDelta,
},
AddNetwork {
id: NetworkId,
network: Network,
},
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
},
/// LWW on a resource's resolved content hash. Creates the resource entry if absent.
/// Concurrent resolves agree by construction (the hash is content-derived), so LWW is safe.
SetResourceHash {
id: ResourceId,
hash: Option<ResourceHash>,
},
/// Remove a whole resource entry. `snapshot` is the state of the resource before it was removed.
RemoveResource {
id: ResourceId,
snapshot: ResourceEntry,
},
/// Add (or LWW-overwrite) one entry in a resource's source fallback chain. The source body is
/// type-erased; `key` carries the fractional priority + peer that order it. Add-wins: concurrent
/// adds at distinct keys all survive. Creates the resource entry if absent.
AddSource {
id: ResourceId,
key: SourceKey,
source: Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
RegisterPeer {
peer: PeerId,
user: UserId,
},
ChangeDocumentAttribute {
delta: AttributeDelta,
},
/// Joins divergent history tips into one shared node. A registry no-op on replay (it only collapses
/// tips so `head` stays a single `Rev`); the joined tips are `Delta::parent` (the lowest `Rev`) plus
/// these `extra_parents` (sorted). Identity is the parent set alone, so two peers merging the same
/// tips mint the identical delta and it dedups.
Merge {
extra_parents: Vec<Rev>,
},
Meta,
// Allow for future delta types without a model change
Other(Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
}
-40
View File
@@ -1,40 +0,0 @@
use serde::{Deserialize, Serialize};
/// Stable, document-scoped identity for a node. Minted as a truncated `blake3(peer, counter)` so it
/// reproduces across `to_runtime` -> `from_runtime` round trips. Used purely as an opaque key.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub u64);
/// Stable identity for a node network. `ROOT_NETWORK` for the renderable graph; nested networks get a
/// path-derived ID via `owned_network_id`. Used purely as an opaque key.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NetworkId(pub u64);
/// Content-addressed identity for a `Delta`.
/// 128-bit blake3 truncation: comfortable collision headroom for any plausible document lifetime
/// without being adversarial-grade. Same delta content always produces the same `Rev`. Non-zero so
/// `Option<Rev>` (a missing/root parent) is niche-optimized to the same size as a bare `Rev`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Rev(pub std::num::NonZeroU128);
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PeerId(pub u64);
/// Per-human identity. Stable across devices (one user, many devices). Used for identity display
/// and undo-chain walking. Derived from `PeerId` via `Registry.peer_users`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UserId(pub u64);
/// Lamport timestamp with a peer-ID tiebreak. Higher counter wins; ties broken by peer.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct TimeStamp {
pub counter: u64,
pub peer: PeerId,
}
-27
View File
@@ -1,27 +0,0 @@
//! Every type a document stores, and the trait impls its encoding depends on. Behavior lives with the rest of the crate.
//!
//! `cargo run migration snapshot` freezes this module into `migration-formats` as one format version, and
//! `cargo run migration check` fails when it no longer matches the latest snapshot. Keep it to definitions and the impls
//! serde or the derives need, so a change here is a change to the format.
mod attributes;
mod delta;
mod ids;
mod model;
mod prior;
mod registry;
mod resources;
mod session;
mod session_state;
mod value;
pub use attributes::*;
pub use delta::*;
pub use ids::*;
pub use model::*;
pub use prior::*;
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use session_state::*;
pub use value::*;
-106
View File
@@ -1,106 +0,0 @@
use super::{Attributes, NetworkId, NodeId, TimeStamp, Value};
use graphene_resource::ResourceId;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub(crate) network: NetworkId,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) network_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) attributes: Attributes,
}
/// One positional input. The timestamp drives LWW on concurrent `ChangeNodeInput` ops targeting
/// the same `(node_id, input_idx)`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeInput {
Node {
id: NodeId,
index: u32,
},
Value {
value: Value,
exposed: bool,
},
Scope(Cow<'static, str>),
Import {
index: u32,
},
/// Marker; the `DocumentNodeMetadata` lives in `inputs_attributes`.
Reflection,
Other,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Implementation {
/// References a proto-node declaration resource (see [`ProtoNode`]); the binding to content lives
/// in `Registry.resources` like any other resource.
ProtoNode(ResourceId),
Network(NetworkId),
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// When the export list last changed shape; see [`Node::inputs_timestamp`](crate::Node).
#[serde(default)]
pub(crate) exports_timestamp: TimeStamp,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
}
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
}
/// Content of a proto-node declaration. Stored as a content-addressed resource (serialized bytes
/// keyed by `ResourceHash`, held by the `Gdd` byte store) and referenced from
/// `Implementation::ProtoNode(ResourceId)`. `document-graph-storage` itself only holds the reference.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProtoNode {
pub identifier: String,
/// The declaration's position in its node's lineage. Omitted at version 1, so first versions keep the bytes, and with them the
/// content-addressed `ResourceId`, they had before declarations were versioned.
#[serde(default = "ProtoNode::first_version", skip_serializing_if = "ProtoNode::is_first_version")]
pub version: u32,
pub attributes: Attributes,
}
impl ProtoNode {
fn first_version() -> u32 {
1
}
fn is_first_version(version: &u32) -> bool {
*version == 1
}
}
-103
View File
@@ -1,103 +0,0 @@
use super::{AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, PeerId, PeerRegistration, ResourceEntry, TimeStamp, Tombstone};
use graphene_resource::ResourceId;
use serde::{Deserialize, Serialize};
/// What a slot held before a delta wrote it, stamps included. Undo puts it back bypassing LWW, so the registry is again
/// the fold of history up to the delta's parent. Never sent or applied as an op.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
/// The whole entity, live, tombstoned, or absent. Restoring an absent one leaves no tombstone, so undoing an addition erases it.
Node {
id: NodeId,
node: Node,
},
RemovedNode {
id: NodeId,
tombstone: Tombstone<Node>,
},
AbsentNode {
id: NodeId,
},
Network {
id: NetworkId,
network: Network,
},
RemovedNetwork {
id: NetworkId,
tombstone: Tombstone<Network>,
},
AbsentNetwork {
id: NetworkId,
},
Resource {
id: ResourceId,
resource: ResourceEntry,
},
RemovedResource {
id: ResourceId,
tombstone: Tombstone<ResourceEntry>,
},
AbsentResource {
id: ResourceId,
},
/// One field of a live node, and the node's presence, which every write moves.
NodeField {
id: NodeId,
presence: TimeStamp,
field: NodeField,
},
/// One field of a live network, and its presence.
NetworkField {
id: NetworkId,
presence: TimeStamp,
field: NetworkField,
},
DocumentAttribute {
key: String,
previous: Option<AttributeValue>,
},
PeerUser {
peer: PeerId,
previous: Option<PeerRegistration>,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
/// Only the presence moved, by a reference from another entity's op.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Input {
index: u32,
previous: InputSlot,
},
InputAttribute {
index: u32,
key: String,
previous: Option<AttributeValue>,
},
Inputs {
previous: Vec<InputSlot>,
inputs_timestamp: TimeStamp,
},
Implementation {
previous: Implementation,
implementation_timestamp: TimeStamp,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
/// Only the presence moved, by a node added to or implemented by it.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Exports {
previous: Vec<ExportSlot>,
},
}
@@ -1,44 +0,0 @@
use super::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceStore, TimeStamp, UserId};
use graphene_resource::ResourceId;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
/// revives the entity.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
pub networks: HashMap<NetworkId, Network>,
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub timestamp: TimeStamp,
}
/// A removed entity's content, for reviving it, and its removal stamp.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub timestamp: TimeStamp,
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
#[serde(default)]
pub placeholder: bool,
}
@@ -1,149 +0,0 @@
use super::{PeerId, TimeStamp, Value};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Ordering key for an entry in a resource's source chain: fractional `priority`, with `peer` as
/// the tiebreak so concurrent insertions at the same priority converge deterministically.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SourceKey {
pub priority: Priority,
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, which readers see as absent.
#[serde(default)]
pub deleted: bool,
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
/// plus the resolved content hash. The source chain is an add-wins ordered set (concurrent
/// additions all survive); the hash is last-writer-wins (concurrent resolves of the same logical
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition; a key the chain lacks is deleted as of then.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
impl<'de> Deserialize<'de> for ResourceEntry {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
// The `binary_search`-based accessors require `sources` sorted by `SourceKey` with unique keys.
// On-disk data (older writers, hand edits) can't be trusted to preserve either, so re-sort and
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(key, _)| *key);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
if later_key != kept_key {
return false;
}
if later_value.timestamp > kept_value.timestamp {
*kept_value = later_value.clone();
}
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
/// All resources referenced by the document, keyed by stable per-document [`ResourceId`]. Replicates
/// through the normal CmRDT path; bytes live in content-addressed storage keyed by [`ResourceHash`].
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
/// Fractional priority for ordering a resource's source chain. New sources are inserted by picking
/// a value strictly between two neighbors, so concurrent insertions elsewhere never collide; an
/// exact tie between two peers inserting at the same gap is broken by `PeerId` in [`SourceKey`].
/// `f64` precision is ample for the short fallback chains resources carry in practice.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "f64")]
pub struct Priority(f64);
impl Priority {
/// Rejects non-finite input. The field is private and deserialization routes through here, so a
/// `Priority` is always finite, keeping its `Ord`/`Hash`/`Eq` agreement sound.
pub fn new(value: f64) -> Result<Self, NonFinitePriority> {
if value.is_finite() { Ok(Self(value)) } else { Err(NonFinitePriority(value)) }
}
pub fn value(self) -> f64 {
self.0
}
}
impl TryFrom<f64> for Priority {
type Error = NonFinitePriority;
fn try_from(value: f64) -> Result<Self, Self::Error> {
Self::new(value)
}
}
/// A [`Priority`] was constructed from a `NaN` or infinite value.
#[derive(Debug, thiserror::Error)]
#[error("priority must be finite, got {0}")]
pub struct NonFinitePriority(pub f64);
// `total_cmp` drives `Ord`, `Hash`, and `Eq` together so `Priority` is a sound `BTree`/`Hash` key:
// a derived `PartialEq` would disagree with this ordering on `-0.0` and `NaN`.
impl PartialEq for Priority {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Priority {}
impl Ord for Priority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for Priority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl std::hash::Hash for Priority {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
@@ -1,38 +0,0 @@
use super::{Attributes, PeerId, RegistryDelta, TimeStamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
pub sequence: HotSequence,
/// Shared with every peer, unlike `Delta::attributes`. Dropped at retirement.
#[serde(default)]
pub attributes: Attributes,
}
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
/// One hot op's author and position in its run, as the retired marks name it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: HotSequence,
}
/// Which hot ops are retired: each author's gap-free prefix, plus runs past it while ops are in flight. Persisted, so
/// a late copy of a retired op is dropped.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetiredMarks {
pub retired_up_to: HashMap<PeerId, HotSequence>,
/// retired ops past their author's prefix, as inclusive runs, one per gap in flight.
pub retired_runs: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
-108
View File
@@ -1,108 +0,0 @@
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
+37 -23
View File
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{
ApplyMode, Attributes, Delta, Document, History, HotOp, HotOpId, HotSequence, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry,
RetiredMarks, Rev, TimeStamp, Touched, UserId, Value, to_value,
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId,
Value, to_value,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
@@ -96,27 +96,6 @@ impl Session {
Ok(conversion.network_ids)
}
/// Diff the working registry against `target` and stage the difference as hot ops, so bulk
/// registry mutations commit through the ordinary hot-op path without hand-built deltas.
pub fn stage_registry_replace(&mut self, target: &Registry) -> Result<Vec<HotOp>, CrdtError> {
let ops = crate::delta::compute_deltas(&self.document.working_registry, target);
self.stage_ops(ops)
}
/// Retire every pending hot op as one gesture. Convenience over [`Session::retire`] for callers
/// that don't track hot-op timestamps themselves.
pub fn retire_all(&mut self) -> Result<Vec<Rev>, CrdtError> {
match self.document.hot_log.iter().map(|hot_op| hot_op.timestamp).max() {
Some(up_to) => self.retire(up_to),
None => Ok(Vec::new()),
}
}
/// Mint a fresh peer-scoped `NodeId`. Forwards to [`Document::next_node_id`].
pub fn next_node_id(&mut self) -> NodeId {
self.document.next_node_id()
}
/// Register a content-addressed resource as a single `DataSource::Embedded` source resolved to
/// `hash`, staged as one `AddResource` hot op. The caller owns `id` allocation, persists the
/// returned hot frame, retires, and persists the bytes into its byte store separately.
@@ -939,6 +918,19 @@ impl Default for Session {
}
}
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
pub sequence: HotSequence,
/// Shared with every peer, unlike `Delta::attributes`. Dropped at retirement.
#[serde(default)]
pub attributes: Attributes,
}
impl HotOp {
pub fn ends_interaction(&self) -> bool {
self.attributes.get_or(crate::attr::delta::INTERACTION_END, false)
@@ -964,6 +956,12 @@ pub struct ClosedInteraction {
pub contiguous: bool,
}
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
impl HotSequence {
/// Before this author has written anything, covering no op.
pub const NONE: Self = Self(0);
@@ -974,6 +972,22 @@ impl HotSequence {
}
}
/// One hot op's author and position in its run, as the retired marks name it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: HotSequence,
}
/// Which hot ops are retired: each author's gap-free prefix, plus runs past it while ops are in flight. Persisted, so
/// a late copy of a retired op is dropped.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetiredMarks {
pub retired_up_to: HashMap<PeerId, HotSequence>,
/// retired ops past their author's prefix, as inclusive runs, one per gap in flight.
pub retired_runs: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
/// Sort and coalesce runs, joining any that touch or abut.
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
runs.sort_unstable();
@@ -767,15 +767,3 @@ fn cyclic_network_reference_is_rejected() {
let error = registry.to_runtime_with_metadata(&crate::Declarations::new()).expect_err("cyclic network reference must error");
assert!(matches!(error, ConversionError::CyclicNetwork(_)), "expected CyclicNetwork, got {error:?}");
}
#[test]
fn first_version_declarations_keep_their_unversioned_bytes() {
let first = crate::EncodedDeclaration::new("math_nodes::AddNode".to_string(), 1).unwrap();
let unversioned = crate::to_value(&serde_json::json!({ "identifier": "math_nodes::AddNode", "attributes": crate::Attributes::default() })).unwrap();
assert_eq!(first.bytes, postcard::to_stdvec(&unversioned).unwrap());
let second = crate::EncodedDeclaration::new("math_nodes::AddNode".to_string(), 2).unwrap();
assert_ne!(second.id, first.id);
assert_eq!(crate::decode_declaration(&second.bytes).unwrap().version, 2);
assert_eq!(crate::decode_declaration(&first.bytes).unwrap().version, 1);
}
+108 -4
View File
@@ -1,6 +1,6 @@
use crate::Value;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
@@ -10,6 +10,111 @@ pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
serde_json::from_value(value.clone().into()).map_err(ValueError)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
use serde_json::Value as Json;
@@ -58,7 +163,6 @@ pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[test]
fn round_trips_through_postcard() {
-24
View File
@@ -1,24 +0,0 @@
[package]
name = "migration-core"
description = "Authoring surface for Graphite document migrations"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[features]
default = ["typed"]
# Node-tier migrations over the typed registry. Format-tier-only migration crates
# (historic version steps, wasm builds) disable this to drop the graph-storage dependency.
typed = ["dep:document-graph-storage", "dep:blake3"]
[dependencies]
document-graph-storage = { workspace = true, optional = true }
migration-macros = { workspace = true }
blake3 = { workspace = true, optional = true }
ctor = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
postcard = { workspace = true }
thiserror = { workspace = true }
-32
View File
@@ -1,32 +0,0 @@
use crate::Declaration;
use document_graph_storage::{NetworkId, NodeId, NodeInput};
/// One output of a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OutputConnector {
pub node: NodeId,
pub output: u32,
}
impl From<OutputConnector> for NodeInput {
fn from(connector: OutputConnector) -> Self {
NodeInput::Node {
id: connector.node,
index: connector.output,
}
}
}
/// A slot that reads an output: a node's input, or an export of a network.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum InputConnector {
Node { node: NodeId, input: u32 },
Export { network: NetworkId, index: u32 },
}
/// A node to add, with every input given explicitly.
#[derive(Clone, Debug, PartialEq)]
pub struct NewNode {
pub declaration: Declaration,
pub inputs: Vec<NodeInput>,
}
@@ -1,41 +0,0 @@
use document_graph_storage::{ResourceEntry, ResourceId};
use serde::Serialize;
/// A proto-node declaration at one version, written `identifier@version`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub struct Declaration {
pub identifier: &'static str,
pub version: u32,
}
impl Declaration {
pub const fn new(identifier: &'static str, version: u32) -> Self {
Self { identifier, version }
}
}
impl std::fmt::Display for Declaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.identifier, self.version)
}
}
/// Names a declaration as `decl!("module::node"@2)`.
#[macro_export]
macro_rules! decl {
($identifier:literal @ $version:literal) => {
$crate::Declaration::new($identifier, $version)
};
}
/// Maps the declaration resources nodes reference to the declarations they hold.
pub trait DeclarationResolver {
/// The declaration a proto-node resource holds, if it is one a migration knows.
fn declaration(&self, resource: ResourceId) -> Option<Declaration>;
/// The resource a node of `declaration` references.
fn resource(&self, declaration: Declaration) -> ResourceId;
/// The registry entry of that resource, added when a migration first references it. `None` leaves the registry's resources alone.
fn resource_entry(&self, _declaration: Declaration) -> Option<ResourceEntry> {
None
}
}
-29
View File
@@ -1,29 +0,0 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum MigrationError {
#[error("failed to decode payload: {0}")]
Decode(String),
#[error("failed to encode payload: {0}")]
Encode(String),
/// The source state violates its own declaration's contract.
#[error("migration invariant violated: {0}")]
Invariant(String),
/// The target version can't express a reachable source state.
#[error("source state is unrepresentable in the target version: {0}")]
Unrepresentable(String),
#[error("input slot {index} is out of range for {len} slots")]
SlotOutOfRange { index: u32, len: usize },
#[error("{0} does not read an output of the anchor")]
OutsideRegion(String),
}
impl MigrationError {
pub fn invariant(message: impl Into<String>) -> Self {
Self::Invariant(message.into())
}
pub fn unrepresentable(message: impl Into<String>) -> Self {
Self::Unrepresentable(message.into())
}
}
-54
View File
@@ -1,54 +0,0 @@
use crate::{MigrationError, Payload};
/// How stored history survives a format step.
///
/// Under `Rewrite`, the migration transforms each record's payload via
/// [`FormatMigration::migrate_delta`]; the runner then recomputes `Rev`s in topological order and
/// remaps parent links and session cursors. Because the rewrite is a pure function of content and
/// `Rev`s are content-addressed, peers applying the same migration converge on identical rewritten
/// history without coordination.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum HistoryPolicy {
/// The shape change does not affect stored deltas.
Untouched,
/// Each history record is rewritten via `migrate_delta`.
Rewrite,
/// No faithful rewrite exists; the document becomes a state-only snapshot.
Truncate,
}
/// One whole-document format step, migrating version `migrates_from()` to `migrates_from() + 1`.
///
/// Usually generated by `format_migration!` over the frozen types of `migration-formats`. Migrations only transform
/// payload content, never identity fields (`id`, `parent`), since Merkle bookkeeping belongs to the runner.
pub trait FormatMigration: Send + Sync {
/// The format version this step upgrades from.
fn migrates_from(&self) -> u32;
/// Transform the serialized registry payload.
fn migrate_registry(&self, registry: &Payload) -> Result<Payload, MigrationError> {
Ok(registry.clone())
}
/// How stored history survives this step.
fn history_policy(&self) -> HistoryPolicy {
HistoryPolicy::Untouched
}
/// Transform one history record. Called only under [`HistoryPolicy::Rewrite`].
fn migrate_delta(&self, delta: &Payload) -> Result<Payload, MigrationError> {
Ok(delta.clone())
}
/// Transform one op of the hot log, which outlives a reopen until it retires.
fn migrate_hot_op(&self, hot_op: &Payload) -> Result<Payload, MigrationError> {
Ok(hot_op.clone())
}
/// Transform the per-peer session payload.
fn migrate_session(&self, session: &Payload) -> Result<Payload, MigrationError> {
Ok(session.clone())
}
}
/// Converts a frozen stored type to its counterpart in the next format version. `cargo run migration snapshot`
/// generates these for every type a version declares again, leaving the parts that changed to the author.
pub trait Upgrade {
type Next;
fn upgrade(self) -> Result<Self::Next, MigrationError>;
}
-47
View File
@@ -1,47 +0,0 @@
//! Authoring surface for `.gdd` document migrations.
//!
//! Two tiers: a [`FormatMigration`] steps a document's serialized payloads from one format version
//! to the next, and a [`NodeMigration`] (feature `typed`) steps one proto-node declaration to its
//! successor on the typed `Registry`. The `migration-runner` crate applies both. Design rationale
//! lives in `node-graph/rfcs/document-format-migrations.md`.
#[cfg(feature = "typed")]
pub mod connector;
#[cfg(feature = "typed")]
pub mod declaration;
pub mod error;
pub mod format;
#[cfg(feature = "typed")]
pub mod migration;
pub mod payload;
pub mod registry;
#[cfg(feature = "typed")]
pub mod value;
#[cfg(feature = "typed")]
pub mod view;
#[cfg(feature = "typed")]
pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
pub use declaration::{Declaration, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::NodeInput;
pub use error::MigrationError;
pub use format::{FormatMigration, HistoryPolicy, Upgrade};
#[cfg(feature = "typed")]
pub use migration::{NodeMigration, Rename};
pub use migration_macros::format_migration;
#[cfg(feature = "typed")]
pub use migration_macros::{migration, rename};
pub use payload::{Payload, PayloadCodec};
pub use registry::{register_format_migration, registered_format_migrations};
#[cfg(feature = "typed")]
pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Upstream, View};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
pub use ctor;
-47
View File
@@ -1,47 +0,0 @@
use crate::{AnchorContext, Declaration, Edits, MigrationError, Region};
/// Steps every node of one declaration to its successor. Implemented by `#[migration]` and `rename!`, not by hand.
pub trait NodeMigration: Send + Sync {
/// The declaration whose nodes are anchors.
fn source(&self) -> Declaration;
/// The declaration the runner switches anchors to.
fn target(&self) -> Declaration;
/// Declarations the body names, which order it after the migration producing each and before the one consuming it.
fn pins(&self) -> &'static [Declaration] {
&[]
}
/// The union of the regions the migration's parameters read and edit.
fn footprint(&self) -> Region;
/// Run on one anchor, returning what its views recorded.
fn run(&self, context: &AnchorContext) -> Result<Edits, MigrationError>;
}
/// Switches anchors to another declaration and changes nothing else.
pub struct Rename {
source: Declaration,
target: Declaration,
}
impl Rename {
pub const fn new(source: Declaration, target: Declaration) -> Self {
Self { source, target }
}
}
impl NodeMigration for Rename {
fn source(&self) -> Declaration {
self.source
}
fn target(&self) -> Declaration {
self.target
}
fn footprint(&self) -> Region {
Region::ANCHOR
}
fn run(&self, _context: &AnchorContext) -> Result<Edits, MigrationError> {
Ok(Edits::default())
}
}
-47
View File
@@ -1,47 +0,0 @@
use crate::MigrationError;
use serde::Serialize;
use serde::de::DeserializeOwned;
/// Codec of a serialized payload. Mirrors the `document-format` codec table entries relevant to
/// migrations so migration crates don't depend on `document-format`; the runner maps between the two.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PayloadCodec {
Json,
Postcard,
}
/// One serialized document payload (the registry, a single history record, the session) plus its
/// codec. History framing is the runner's concern; migrations always see one record per payload.
#[derive(Clone, Debug)]
pub struct Payload {
pub bytes: Vec<u8>,
pub codec: PayloadCodec,
}
impl Payload {
pub fn new(bytes: Vec<u8>, codec: PayloadCodec) -> Self {
Self { bytes, codec }
}
/// Decode into a typed shape, usually a frozen mirror struct owned by the migration crate.
pub fn decode<T: DeserializeOwned>(&self) -> Result<T, MigrationError> {
match self.codec {
PayloadCodec::Json => serde_json::from_slice(&self.bytes).map_err(|e| MigrationError::Decode(e.to_string())),
PayloadCodec::Postcard => postcard::from_bytes(&self.bytes).map_err(|e| MigrationError::Decode(e.to_string())),
}
}
/// Encode a typed shape with the given codec.
pub fn encode<T: Serialize>(value: &T, codec: PayloadCodec) -> Result<Self, MigrationError> {
let bytes = match codec {
PayloadCodec::Json => serde_json::to_vec(value).map_err(|e| MigrationError::Encode(e.to_string()))?,
PayloadCodec::Postcard => postcard::to_stdvec(value).map_err(|e| MigrationError::Encode(e.to_string()))?,
};
Ok(Self { bytes, codec })
}
/// Encode a typed shape, keeping this payload's codec.
pub fn encode_as<T: Serialize>(&self, value: &T) -> Result<Self, MigrationError> {
Self::encode(value, self.codec)
}
}
-30
View File
@@ -1,30 +0,0 @@
use crate::FormatMigration;
#[cfg(feature = "typed")]
use crate::NodeMigration;
use std::sync::{Mutex, PoisonError};
#[cfg(feature = "typed")]
static MIGRATIONS: Mutex<Vec<&'static dyn NodeMigration>> = Mutex::new(Vec::new());
static FORMAT_MIGRATIONS: Mutex<Vec<&'static dyn FormatMigration>> = Mutex::new(Vec::new());
/// Add a node migration to the registry. Called at startup by what `#[migration]` and `rename!` generate.
#[cfg(feature = "typed")]
pub fn register_migration(migration: &'static dyn NodeMigration) {
MIGRATIONS.lock().unwrap_or_else(PoisonError::into_inner).push(migration);
}
/// Every registered node migration, in registration order.
#[cfg(feature = "typed")]
pub fn registered_migrations() -> Vec<&'static dyn NodeMigration> {
MIGRATIONS.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Add a format step to the registry. Called at startup by what `format_migration!` generates.
pub fn register_format_migration(migration: &'static dyn FormatMigration) {
FORMAT_MIGRATIONS.lock().unwrap_or_else(PoisonError::into_inner).push(migration);
}
/// Every registered format step, in registration order.
pub fn registered_format_migrations() -> Vec<&'static dyn FormatMigration> {
FORMAT_MIGRATIONS.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
-24
View File
@@ -1,24 +0,0 @@
use document_graph_storage::{NodeInput, Value, from_value, to_value};
use serde::Serialize;
use serde::de::DeserializeOwned;
/// Encode a frozen mirror value as the self-describing `Value` input slots store.
pub fn encode<T: Serialize>(value: &T) -> Value {
to_value(value).expect("frozen mirror values serialize to JSON")
}
/// An unexposed literal input holding `value`.
pub fn literal<T: Serialize>(value: T) -> NodeInput {
NodeInput::Value {
value: encode(&value),
exposed: false,
}
}
/// The literal `input` holds, decoded as `T`. `None` for wires and for literals of other variants.
pub fn literal_of<T: DeserializeOwned>(input: &NodeInput) -> Option<T> {
match input {
NodeInput::Value { value, .. } => from_value(value).ok(),
_ => None,
}
}
-441
View File
@@ -1,441 +0,0 @@
use crate::{Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use std::ops::Deref;
/// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region(u8);
impl Region {
pub const EMPTY: Self = Self(0);
/// The anchor itself, which the runner switches to the target declaration.
pub const ANCHOR: Self = Self(1);
pub const INPUTS: Self = Self(1 << 1);
pub const UPSTREAM: Self = Self(1 << 2);
pub const DOWNSTREAM: Self = Self(1 << 3);
pub const RESOURCES: Self = Self(1 << 4);
/// The anchor's whole network, as read through [`Graph`].
pub const NETWORK: Self = Self(1 << 5);
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub const fn overlaps(self, other: Self) -> bool {
self.0 & other.0 != 0
}
/// Whether no two of `regions` overlap, for checking a migration's mutable views at compile time.
pub const fn disjoint(regions: &[Region]) -> bool {
let mut i = 0;
while i < regions.len() {
let mut j = i + 1;
while j < regions.len() {
if regions[i].overlaps(regions[j]) {
return false;
}
j += 1;
}
i += 1;
}
true
}
}
/// The anchor before migration. Wraps the stored node to add its ID, which the node doesn't hold itself.
#[derive(Clone, Copy)]
pub struct Node<'a> {
id: NodeId,
node: &'a document_graph_storage::Node,
}
impl Node<'_> {
pub fn id(&self) -> NodeId {
self.id
}
}
impl Deref for Node<'_> {
type Target = document_graph_storage::Node;
fn deref(&self) -> &Self::Target {
self.node
}
}
/// What one run of a migration sees: the source state around one anchor.
#[derive(Clone, Copy)]
pub struct AnchorContext<'a> {
registry: &'a Registry,
anchor: Node<'a>,
source: Declaration,
target: Declaration,
resolver: &'a dyn DeclarationResolver,
}
impl<'a> AnchorContext<'a> {
/// `None` when `anchor` isn't a live node of `registry`.
pub fn new(registry: &'a Registry, anchor: NodeId, source: Declaration, target: Declaration, resolver: &'a dyn DeclarationResolver) -> Option<Self> {
let node = registry.node_instances.get(&anchor)?;
Some(Self {
registry,
anchor: Node { id: anchor, node },
source,
target,
resolver,
})
}
pub fn source_node(&self) -> &Node<'a> {
&self.anchor
}
pub fn graph(&self) -> Graph<'a> {
Graph {
registry: self.registry,
network: self.anchor.network(),
resolver: self.resolver,
}
}
/// The ID of a node this run adds. It is the same in every state the migration runs on, so a history rewrite diffs it as one node.
fn derived_node_id(&self, declaration: Declaration, key: &str) -> NodeId {
let mut hasher = blake3::Hasher::new();
postcard::to_io(&(self.source, self.target, self.anchor.id.0, declaration, key), &mut hasher).expect("hashing never fails to write");
let mut truncated = [0_u8; 8];
truncated.copy_from_slice(&hasher.finalize().as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
fn added_node(&self, node: NewNode, key: &str) -> AddedNode {
AddedNode {
id: self.derived_node_id(node.declaration, key),
key: key.to_string(),
node,
}
}
}
/// Read access to the anchor's network before migration.
#[derive(Clone, Copy)]
pub struct Graph<'a> {
registry: &'a Registry,
network: NetworkId,
resolver: &'a dyn DeclarationResolver,
}
impl<'a> Graph<'a> {
pub fn network(&self) -> NetworkId {
self.network
}
/// A node of this network.
pub fn node(&self, id: NodeId) -> Option<&'a document_graph_storage::Node> {
self.registry.node_instances.get(&id).filter(|node| node.network() == self.network)
}
/// The declaration a node of this network implements, if it is one a migration knows.
pub fn declaration(&self, id: NodeId) -> Option<Declaration> {
let document_graph_storage::Implementation::ProtoNode(resource) = self.node(id)?.implementation() else {
return None;
};
self.resolver.declaration(*resource)
}
/// Every slot reading `output`: node inputs ordered by node ID and slot, then the network's exports.
pub fn consumers(&self, output: OutputConnector) -> Vec<InputConnector> {
self.readers(|node, index| node == output.node && index == output.output)
}
/// Every slot reading any output of `node`.
fn consumers_of_node(&self, node: NodeId) -> Vec<InputConnector> {
self.readers(|read_node, _| read_node == node)
}
fn readers(&self, reads: impl Fn(NodeId, u32) -> bool) -> Vec<InputConnector> {
let reads_input = |input: &NodeInput| matches!(input, NodeInput::Node { id, index } if reads(*id, *index));
let mut readers: Vec<InputConnector> = self
.registry
.node_instances
.iter()
.filter(|(_, node)| node.network() == self.network)
.flat_map(|(id, node)| {
node.inputs()
.iter()
.enumerate()
.filter(|(_, slot)| reads_input(&slot.input))
.map(|(input, _)| InputConnector::Node { node: *id, input: input as u32 })
})
.collect();
readers.sort_unstable();
if let Some(network) = self.registry.networks.get(&self.network) {
let exports = network.exports.iter().enumerate().filter(|(_, slot)| slot.target.as_ref().is_some_and(reads_input));
readers.extend(exports.map(|(index, _)| InputConnector::Export {
network: self.network,
index: index as u32,
}));
}
readers
}
}
/// A parameter type of a migration: a window onto one region around the anchor that records edits rather than applying them.
pub trait View<'a>: Sized {
const REGION: Region;
fn extract(context: &AnchorContext<'a>) -> Self;
fn into_edits(self) -> Result<Edits, MigrationError>;
}
/// Everything one run of a migration asks the runner to change.
#[derive(Debug, Default)]
pub struct Edits {
pub inputs: Option<InputsEdit>,
pub added_nodes: Vec<AddedNode>,
pub removed_nodes: Vec<NodeId>,
pub connections: Vec<(OutputConnector, InputConnector)>,
}
impl Edits {
pub fn merge(&mut self, other: Edits) {
if other.inputs.is_some() {
self.inputs = other.inputs;
}
self.added_nodes.extend(other.added_nodes);
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
}
}
#[derive(Debug)]
pub struct AddedNode {
pub id: NodeId,
/// Disambiguates several nodes of one declaration added for one anchor.
pub key: String,
pub node: NewNode,
}
/// The anchor's target input layout.
#[derive(Debug)]
pub struct InputsEdit {
pub slots: Vec<InputSlot>,
/// For each target slot, the source slot it still holds unchanged, or `None` for an inserted or overwritten slot.
pub origins: Vec<Option<u32>>,
}
impl InputsEdit {
/// Where the unchanged source slot `source` ended up, or `None` if it was removed or overwritten.
pub fn target_index(&self, source: u32) -> Option<u32> {
self.origins.iter().position(|origin| *origin == Some(source)).map(|index| index as u32)
}
}
/// The anchor's input slots. Operations apply in order to the target layout being built.
pub struct Inputs {
slots: Vec<InputSlot>,
origins: Vec<Option<u32>>,
edited: bool,
error: Option<MigrationError>,
}
impl Inputs {
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn set(&mut self, index: u32, input: NodeInput) {
if !self.check(index, self.slots.len()) {
return;
}
self.slots[index as usize].input = input;
self.origins[index as usize] = None;
}
pub fn insert(&mut self, index: u32, input: NodeInput) {
if !self.check(index, self.slots.len() + 1) {
return;
}
self.slots.insert(index as usize, new_slot(input));
self.origins.insert(index as usize, None);
}
pub fn push(&mut self, input: NodeInput) {
self.edited = true;
self.slots.push(new_slot(input));
self.origins.push(None);
}
pub fn remove(&mut self, index: u32) {
if !self.check(index, self.slots.len()) {
return;
}
self.slots.remove(index as usize);
self.origins.remove(index as usize);
}
pub fn truncate(&mut self, len: u32) {
self.edited = true;
self.slots.truncate(len as usize);
self.origins.truncate(len as usize);
}
/// Whether `index` is below `bound`, recording the first violation for `into_edits` to report.
fn check(&mut self, index: u32, bound: usize) -> bool {
self.edited = true;
let in_range = (index as usize) < bound;
if !in_range && self.error.is_none() {
self.error = Some(MigrationError::SlotOutOfRange { index, len: self.slots.len() });
}
in_range
}
}
fn new_slot(input: NodeInput) -> InputSlot {
InputSlot {
input,
..InputSlot::unset(TimeStamp::ORIGIN)
}
}
impl<'a> View<'a> for Inputs {
const REGION: Region = Region::INPUTS;
fn extract(context: &AnchorContext<'a>) -> Self {
let slots = context.anchor.inputs().to_vec();
let origins = (0..slots.len() as u32).map(Some).collect();
Self {
slots,
origins,
edited: false,
error: None,
}
}
fn into_edits(self) -> Result<Edits, MigrationError> {
if let Some(error) = self.error {
return Err(error);
}
let inputs = self.edited.then_some(InputsEdit {
slots: self.slots,
origins: self.origins,
});
Ok(Edits { inputs, ..Default::default() })
}
}
/// Nodes upstream of the anchor: new ones that feed its inputs, and existing ones to remove.
pub struct Upstream<'a> {
context: AnchorContext<'a>,
added: Vec<AddedNode>,
removed: Vec<NodeId>,
}
impl Upstream<'_> {
/// Add a node in the anchor's network. Needs no key while it is the only one of its declaration this run adds.
pub fn add_node(&mut self, node: NewNode) -> NodeId {
self.add_node_keyed(node, "")
}
pub fn add_node_keyed(&mut self, node: NewNode, key: &str) -> NodeId {
let added = self.context.added_node(node, key);
let id = added.id;
self.added.push(added);
id
}
/// Only correct when nothing else reads the removed node, which the region can't check.
pub fn remove_node(&mut self, id: NodeId) {
self.removed.push(id);
}
}
impl<'a> View<'a> for Upstream<'a> {
const REGION: Region = Region::UPSTREAM;
fn extract(context: &AnchorContext<'a>) -> Self {
Self {
context: *context,
added: Vec::new(),
removed: Vec::new(),
}
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
added_nodes: self.added,
removed_nodes: self.removed,
..Default::default()
})
}
}
/// The slots reading the anchor's outputs, plus new nodes downstream of it.
pub struct Downstream<'a> {
context: AnchorContext<'a>,
added: Vec<AddedNode>,
connections: Vec<(OutputConnector, InputConnector)>,
}
impl Downstream<'_> {
/// The slots reading the anchor's `output` in the source state. Nodes added by this migration never appear here.
pub fn consumers(&self, output: u32) -> Vec<InputConnector> {
let anchor = OutputConnector { node: self.context.anchor.id, output };
self.context.graph().consumers(anchor)
}
/// Add a node in the anchor's network. Needs no key while it is the only one of its declaration this run adds.
pub fn add_node(&mut self, node: NewNode) -> NodeId {
self.add_node_keyed(node, "")
}
pub fn add_node_keyed(&mut self, node: NewNode, key: &str) -> NodeId {
let added = self.context.added_node(node, key);
let id = added.id;
self.added.push(added);
id
}
/// Make `consumer`, which must read an output of the anchor, read `output` instead.
pub fn connect(&mut self, output: OutputConnector, consumer: InputConnector) {
self.connections.push((output, consumer));
}
}
impl<'a> View<'a> for Downstream<'a> {
const REGION: Region = Region::DOWNSTREAM;
fn extract(context: &AnchorContext<'a>) -> Self {
Self {
context: *context,
added: Vec::new(),
connections: Vec::new(),
}
}
fn into_edits(self) -> Result<Edits, MigrationError> {
let readers = self.context.graph().consumers_of_node(self.context.anchor.id);
if let Some((_, consumer)) = self.connections.iter().find(|(_, consumer)| !readers.contains(consumer)) {
return Err(MigrationError::OutsideRegion(format!("{consumer:?}")));
}
Ok(Edits {
added_nodes: self.added,
connections: self.connections,
..Default::default()
})
}
}
-20
View File
@@ -1,20 +0,0 @@
[package]
name = "migration-formats"
description = "Frozen stored types of every Graphite document format version, for format migrations"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[dependencies]
migration-core = { workspace = true }
graphene-resource = { workspace = true, features = ["serde"] }
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
document-graph-storage = { workspace = true }
postcard = { workspace = true }
serde_json = { workspace = true }
-11
View File
@@ -1,11 +0,0 @@
//! The stored document types of every format version, frozen by `cargo run migration snapshot` and never edited by hand.
//!
//! `v<N>` declares the types that changed in version N, plus every type reaching one, and re-exports the rest from
//! `v<N - 1>`. A type that didn't change is the same Rust type in both versions, so a format step only converts what did.
//! `latest` matches the live types in `graph-storage`, which `cargo run migration check` enforces.
pub mod v1;
pub mod v2;
pub use v2 as latest;
mod steps;
@@ -1,3 +0,0 @@
//! One format step per version, each registering itself.
mod v1_to_v2;
@@ -1,22 +0,0 @@
//! Format step 1 to 2, generated by `cargo run migration snapshot`. Types that only reach a changed one convert on their own. Finish the changed ones (ProtoNode) where a `compile_error!` or a type mismatch points.
use crate::{v1, v2};
use migration_core::{MigrationError, Upgrade, format_migration};
// Payloads keep their encoding. The bump stops builds without declaration versions from reading a later version as the first
format_migration! {
1 => 2,
}
impl Upgrade for v1::ProtoNode {
type Next = v2::ProtoNode;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v1::ProtoNode { identifier, attributes } = self;
Ok(v2::ProtoNode {
identifier,
// Declarations were unversioned before, so every one is the first of its lineage
version: 1,
attributes,
})
}
}
-483
View File
@@ -1,483 +0,0 @@
//! Format version 1, frozen by `cargo run migration snapshot`. Never edit it: old documents decode through these definitions.
use graphene_resource::{ResourceHash, ResourceId};
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
#[serde(default)]
pub deleted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
pub entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
pub floor: TimeStamp,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
pub parent: Option<Rev>,
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: Vec<Prior>,
#[serde(default)]
pub attributes: Attributes,
#[serde(default)]
pub retired_at_ms: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode { id: NodeId, node: Node },
RemoveNode { id: NodeId, snapshot: Node },
ChangeNodeInput { id: NodeId, index: u32, new_input: NodeInput },
SetNodeInputs { id: NodeId, inputs: Vec<InputSlot> },
SetNodeImplementation { id: NodeId, implementation: Implementation },
ChangeNodeAttribute { id: NodeId, delta: AttributeDelta },
ChangeNodeInputAttribute { id: NodeId, index: u32, delta: AttributeDelta },
SetNetworkExport { id: NetworkId, index: u32, export: Option<NodeInput> },
ChangeNetworkAttribute { id: NetworkId, delta: AttributeDelta },
AddNetwork { id: NetworkId, network: Network },
RemoveNetwork { id: NetworkId, snapshot: Network },
AddResource { id: ResourceId, entry: ResourceEntry },
SetResourceHash { id: ResourceId, hash: Option<ResourceHash> },
RemoveResource { id: ResourceId, snapshot: ResourceEntry },
AddSource { id: ResourceId, key: SourceKey, source: Value },
RemoveSource { id: ResourceId, key: SourceKey },
RegisterPeer { peer: PeerId, user: UserId },
ChangeDocumentAttribute { delta: AttributeDelta },
Merge { extra_parents: Vec<Rev> },
Meta,
Other(Value),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub u64);
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NetworkId(pub u64);
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Rev(pub std::num::NonZeroU128);
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PeerId(pub u64);
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UserId(pub u64);
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct TimeStamp {
pub counter: u64,
pub peer: PeerId,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
#[serde(default)]
pub presence: TimeStamp,
pub network: NetworkId,
#[serde(default)]
pub network_timestamp: TimeStamp,
pub implementation: Implementation,
#[serde(default)]
pub implementation_timestamp: TimeStamp,
pub inputs: Vec<InputSlot>,
#[serde(default)]
pub inputs_timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeInput {
Node { id: NodeId, index: u32 },
Value { value: Value, exposed: bool },
Scope(Cow<'static, str>),
Import { index: u32 },
Reflection,
Other,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Implementation {
ProtoNode(ResourceId),
Network(NetworkId),
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
#[serde(default)]
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
#[serde(default)]
pub exports_timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProtoNode {
pub identifier: String,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
Node { id: NodeId, node: Node },
RemovedNode { id: NodeId, tombstone: Tombstone<Node> },
AbsentNode { id: NodeId },
Network { id: NetworkId, network: Network },
RemovedNetwork { id: NetworkId, tombstone: Tombstone<Network> },
AbsentNetwork { id: NetworkId },
Resource { id: ResourceId, resource: ResourceEntry },
RemovedResource { id: ResourceId, tombstone: Tombstone<ResourceEntry> },
AbsentResource { id: ResourceId },
NodeField { id: NodeId, presence: TimeStamp, field: NodeField },
NetworkField { id: NetworkId, presence: TimeStamp, field: NetworkField },
DocumentAttribute { key: String, previous: Option<AttributeValue> },
PeerUser { peer: PeerId, previous: Option<PeerRegistration> },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
Presence,
Attribute { key: String, previous: Option<AttributeValue> },
Input { index: u32, previous: InputSlot },
InputAttribute { index: u32, key: String, previous: Option<AttributeValue> },
Inputs { previous: Vec<InputSlot>, inputs_timestamp: TimeStamp },
Implementation { previous: Implementation, implementation_timestamp: TimeStamp },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
Presence,
Attribute { key: String, previous: Option<AttributeValue> },
Exports { previous: Vec<ExportSlot> },
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
pub networks: HashMap<NetworkId, Network>,
pub resources: ResourceStore,
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub timestamp: TimeStamp,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub timestamp: TimeStamp,
#[serde(default)]
pub placeholder: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SourceKey {
pub priority: Priority,
pub peer: PeerId,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub timestamp: TimeStamp,
#[serde(default)]
pub deleted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
pub presence: TimeStamp,
pub sources: Vec<(SourceKey, SourceValue)>,
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
impl<'de> Deserialize<'de> for ResourceEntry {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(key, _)| *key);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
if later_key != kept_key {
return false;
}
if later_value.timestamp > kept_value.timestamp {
*kept_value = later_value.clone();
}
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "f64")]
pub struct Priority(pub f64);
impl Priority {
pub fn new(value: f64) -> Result<Self, NonFinitePriority> {
if value.is_finite() { Ok(Self(value)) } else { Err(NonFinitePriority(value)) }
}
pub fn value(self) -> f64 {
self.0
}
}
impl TryFrom<f64> for Priority {
type Error = NonFinitePriority;
fn try_from(value: f64) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl PartialEq for Priority {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Priority {}
impl Ord for Priority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for Priority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl std::hash::Hash for Priority {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
#[derive(Debug, thiserror :: Error)]
#[error("priority must be finite, got {0}")]
pub struct NonFinitePriority(pub f64);
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
pub sequence: HotSequence,
#[serde(default)]
pub attributes: Attributes,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: HotSequence,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetiredMarks {
pub retired_up_to: HashMap<PeerId, HotSequence>,
pub retired_runs: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SessionState {
#[serde(default)]
pub peer_id: PeerId,
#[serde(default)]
pub user_id: UserId,
#[serde(default)]
pub head_rev: Option<Rev>,
#[serde(default)]
pub last_broadcast_rev: Option<Rev>,
#[serde(default)]
pub redo_stack: Vec<Rev>,
#[serde(default)]
pub next_node_counter: u64,
#[serde(default)]
pub last_hot_sequence: HotSequence,
#[serde(default)]
pub view_settings: BTreeMap<String, Value>,
#[serde(default)]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
#[serde(default)]
pub retired_marks: RetiredMarks,
#[serde(default)]
pub clock_counter: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
-25
View File
@@ -1,25 +0,0 @@
//! Format version 2, frozen by `cargo run migration snapshot`. Never edit it: old documents decode through these definitions.
pub use super::v1::{
AttributeDelta, AttributeValue, Attributes, Delta, ExportSlot, HotOp, HotOpId, HotSequence, Implementation, InputSlot, Network, NetworkField, NetworkId, Node, NodeField, NodeId, NodeInput,
NonFinitePriority, PeerId, PeerRegistration, Prior, Priority, Registry, RegistryDelta, ResourceEntry, ResourceStore, RetiredMarks, Rev, SessionState, SourceKey, SourceValue, TimeStamp, Tombstone,
UserId, Value,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProtoNode {
pub identifier: String,
#[serde(default = "ProtoNode::first_version", skip_serializing_if = "ProtoNode::is_first_version")]
pub version: u32,
pub attributes: Attributes,
}
impl ProtoNode {
pub fn first_version() -> u32 {
1
}
pub fn is_first_version(version: &u32) -> bool {
*version == 1
}
}
-242
View File
@@ -1,242 +0,0 @@
//! The latest frozen version reads and writes exactly what the live types do. `cargo run migration check` compares the
//! definitions; this compares the encodings, which a changed custom serde impl could break unnoticed.
use document_graph_storage::{
AttributeDelta, Delta, HotOp, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, ProtoNode, ROOT_NETWORK, Registry, RegistryDelta, ResourceEntry, ResourceHash,
ResourceId, Session, SessionState, SourceKey, UserId, Value,
};
use migration_formats::latest;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::BTreeMap;
/// Live value to postcard, through the frozen type, and back.
fn through_frozen_postcard<Live: Serialize + DeserializeOwned, Frozen: Serialize + DeserializeOwned>(live: &Live) -> (Vec<u8>, Live) {
let frozen: Frozen = postcard::from_bytes(&postcard::to_stdvec(live).unwrap()).unwrap();
let bytes = postcard::to_stdvec(&frozen).unwrap();
let decoded = postcard::from_bytes(&bytes).unwrap();
(bytes, decoded)
}
/// Live value to JSON text and back through the frozen type. Text, since a JSON value can't hold the `u128` in a `Rev`.
fn through_frozen_json<Live: Serialize, Frozen: Serialize + DeserializeOwned>(live: &Live) -> String {
let frozen: Frozen = serde_json::from_str(&serde_json::to_string(live).unwrap()).unwrap();
serde_json::to_string(&frozen).unwrap()
}
fn node(network: NetworkId, implementation: Implementation, inputs: Vec<NodeInput>) -> Node {
let mut node = Node::new(network, implementation, inputs.len());
for (slot, input) in node.inputs_mut().iter_mut().zip(inputs) {
slot.input = input;
}
node
}
fn nested_value() -> Value {
Value::Object(vec![
("float".to_string(), Value::Float(1.5)),
("int".to_string(), Value::Int(-7)),
("list".to_string(), Value::Array(vec![Value::Bool(true), Value::None, Value::Str("text".to_string())])),
])
}
/// A session whose history uses every op kind a document stores, with one op still hot.
fn session() -> Session {
let mut session = Session::with_identity(PeerId(1), UserId(7));
let mut commit = |ops: Vec<RegistryDelta>| {
session.stage_computed_ops(ops).unwrap();
session.retire_all().unwrap();
};
let (first, second, nested) = (NodeId(1), NodeId(2), NetworkId(5));
let declaration = ResourceId::from(11);
let image = ResourceId::from(12);
let attribute = |key: &str| AttributeDelta {
key: key.to_string(),
value: Some(nested_value()),
};
let source_key = SourceKey {
priority: Priority::new(0.5).unwrap(),
peer: PeerId(1),
};
commit(vec![
RegistryDelta::RegisterPeer { peer: PeerId(1), user: UserId(7) },
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::AddNetwork {
id: nested,
network: Network::default(),
},
RegistryDelta::AddResource {
id: declaration,
entry: ResourceEntry::default(),
},
RegistryDelta::AddResource {
id: image,
entry: ResourceEntry::default(),
},
]);
commit(vec![
RegistryDelta::AddNode {
id: first,
node: node(
ROOT_NETWORK,
Implementation::ProtoNode(declaration),
vec![
NodeInput::Value { value: nested_value(), exposed: true },
NodeInput::Scope("editor-api".into()),
NodeInput::Import { index: 0 },
NodeInput::Reflection,
],
),
},
RegistryDelta::AddNode {
id: second,
node: node(ROOT_NETWORK, Implementation::Network(nested), vec![NodeInput::Node { id: first, index: 0 }]),
},
]);
commit(vec![
RegistryDelta::ChangeNodeInput {
id: first,
index: 0,
new_input: NodeInput::Value { value: Value::Int(3), exposed: false },
},
RegistryDelta::ChangeNodeAttribute {
id: first,
delta: attribute("ui::name"),
},
RegistryDelta::ChangeNodeInputAttribute {
id: first,
index: 1,
delta: attribute("ui::label"),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(NodeInput::Node { id: second, index: 0 }),
},
RegistryDelta::ChangeNetworkAttribute {
id: ROOT_NETWORK,
delta: attribute("ui::navigation"),
},
RegistryDelta::ChangeDocumentAttribute { delta: attribute("ui::document") },
]);
commit(vec![
RegistryDelta::SetResourceHash {
id: image,
hash: Some(ResourceHash::from(b"image".as_slice())),
},
RegistryDelta::AddSource {
id: image,
key: source_key,
source: Value::Str("embedded".to_string()),
},
]);
commit(vec![
RegistryDelta::SetNodeImplementation {
id: second,
implementation: Implementation::ProtoNode(declaration),
},
RegistryDelta::SetNodeInputs {
id: second,
inputs: node(ROOT_NETWORK, Implementation::ProtoNode(declaration), vec![NodeInput::Other, NodeInput::Import { index: 1 }])
.inputs()
.to_vec(),
},
RegistryDelta::RemoveSource { id: image, key: source_key },
]);
commit(vec![
RegistryDelta::RemoveNode {
id: first,
snapshot: node(ROOT_NETWORK, Implementation::ProtoNode(declaration), vec![]),
},
RegistryDelta::RemoveNetwork {
id: nested,
snapshot: Network::default(),
},
RegistryDelta::RemoveResource {
id: image,
snapshot: ResourceEntry::default(),
},
]);
// Left hot, so the hot log has an op too
session
.stage_computed_ops(vec![RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 1,
export: None,
}])
.unwrap();
session
}
#[test]
fn history_encodes_identically() {
let session = session();
let history: Vec<Delta> = session.history().cloned().collect();
assert!(history.len() > 5);
for delta in &history {
// Deltas hold no hash maps, so their bytes are deterministic
let (bytes, _) = through_frozen_postcard::<Delta, latest::Delta>(delta);
assert_eq!(bytes, postcard::to_stdvec(delta).unwrap(), "delta {:?} changed through the frozen types", delta.id);
}
}
#[test]
fn registry_decodes_identically() {
let session = session();
// Hash map order differs between encodings, so compare decoded values
for registry in [session.registry(), session.retired_registry()] {
let (_, decoded) = through_frozen_postcard::<Registry, latest::Registry>(registry);
assert_eq!(&decoded, registry);
}
}
#[test]
fn hot_log_encodes_identically() {
let session = session();
assert!(!session.hot_log().is_empty());
for hot_op in session.hot_log() {
let (bytes, _) = through_frozen_postcard::<HotOp, latest::HotOp>(hot_op);
assert_eq!(bytes, postcard::to_stdvec(hot_op).unwrap());
}
}
#[test]
fn session_state_encodes_identically() {
let session = session();
let state = SessionState {
peer_id: session.peer(),
user_id: session.user(),
head_rev: session.head_rev(),
last_broadcast_rev: session.head_rev(),
redo_stack: session.history().map(|delta| delta.id).take(2).collect(),
next_node_counter: session.next_node_counter(),
last_hot_sequence: session.last_hot_sequence(),
view_settings: BTreeMap::from([("ui::doc::zoom".to_string(), nested_value())]),
network_view_settings: BTreeMap::from([(ROOT_NETWORK, BTreeMap::from([("ui::nav".to_string(), Value::Float(2.))]))]),
retired_marks: session.retired_marks().clone(),
clock_counter: session.clock_counter(),
};
assert_eq!(through_frozen_json::<SessionState, latest::SessionState>(&state), serde_json::to_string(&state).unwrap());
}
#[test]
fn declarations_encode_identically() {
let mut declaration = ProtoNode {
identifier: "math_nodes::add".to_string(),
version: 2,
attributes: Default::default(),
};
declaration.attributes.set("ui::category", nested_value(), Default::default());
assert_eq!(through_frozen_json::<ProtoNode, latest::ProtoNode>(&declaration), serde_json::to_string(&declaration).unwrap());
}
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "migration-macros"
description = "The #[migration] attribute and rename! macro for Graphite document migrations"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[lints]
workspace = true
[lib]
proc-macro = true
[dependencies]
syn = { workspace = true }
proc-macro2 = { workspace = true }
quote = { workspace = true }
convert_case = { workspace = true }
blake3 = { workspace = true }
proc-macro-crate = "3.1.0"
-89
View File
@@ -1,89 +0,0 @@
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Error, Ident, LitInt, Token, Type};
/// The stored roots a format step can convert, by the `FormatMigration` method converting each.
const ROOTS: &[(&str, &str)] = &[
("registry", "migrate_registry"),
("delta", "migrate_delta"),
("hot_op", "migrate_hot_op"),
("session", "migrate_session"),
];
/// `1 => 2, registry: v1::Registry, delta: v1::Delta`: the version step and the frozen type of each root it converts.
pub struct FormatStep {
pub from: u32,
pub to: u32,
pub roots: Vec<(Ident, Type)>,
}
impl Parse for FormatStep {
fn parse(input: ParseStream) -> syn::Result<Self> {
let from_literal: LitInt = input.parse()?;
input.parse::<Token![=>]>()?;
let to_literal: LitInt = input.parse()?;
let from: u32 = from_literal.base10_parse()?;
let to: u32 = to_literal.base10_parse()?;
if from.checked_add(1) != Some(to) {
return Err(Error::new(
to_literal.span(),
format!("a format step goes from one version to the next, so this must be {}", from.saturating_add(1)),
));
}
let mut roots: Vec<(Ident, Type)> = Vec::new();
while input.parse::<Option<Token![,]>>()?.is_some() && !input.is_empty() {
let root: Ident = input.parse()?;
if !ROOTS.iter().any(|(name, _)| root == name) {
let names: Vec<&str> = ROOTS.iter().map(|(name, _)| *name).collect();
return Err(Error::new(root.span(), format!("the stored roots are {}", names.join(", "))));
}
if roots.iter().any(|(existing, _)| *existing == root) {
return Err(Error::new(root.span(), "this root is already listed"));
}
input.parse::<Token![:]>()?;
roots.push((root, input.parse()?));
}
Ok(Self { from, to, roots })
}
}
/// A `FormatMigration` converting each listed root through its `Upgrade`, leaving the others' payloads as they are.
pub fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
let from = step.from;
let methods = step.roots.iter().map(|(root, frozen)| {
let method = ROOTS.iter().find(|(name, _)| root == name).map(|(_, method)| format_ident!("{method}"));
quote! {
fn #method(&self, payload: &#core::Payload) -> ::core::result::Result<#core::Payload, #core::MigrationError> {
let previous: #frozen = payload.decode()?;
payload.encode_as(&#core::Upgrade::upgrade(previous)?)
}
}
});
let rewrites_history = step.roots.iter().any(|(root, _)| root == "delta");
let history_policy = rewrites_history.then(|| {
quote! {
fn history_policy(&self) -> #core::HistoryPolicy {
#core::HistoryPolicy::Rewrite
}
}
});
quote! {
struct FormatStep;
impl #core::FormatMigration for FormatStep {
fn migrates_from(&self) -> u32 {
#from
}
#history_policy
#(#methods)*
}
}
}
-258
View File
@@ -1,258 +0,0 @@
//! `#[migration]`, `rename!`, and `format_migration!` for `migration-core`. See `node-graph/rfcs/document-format-migrations.md` for what they expand to.
mod format;
mod step;
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote};
use step::{Declaration, Step, scan_pins};
use syn::spanned::Spanned;
use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// Turns a function into a node migration, named by its source and target declarations:
/// `#[migration("module::node"@1 => @2)]` for a version step, `#[migration("module::old"@1 => "module::new"@2)]` for a replacement.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, and each `&mut` parameter is a
/// view (`Inputs`, `Upstream`, `Downstream`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
pub fn migration(attribute: TokenStream, item: TokenStream) -> TokenStream {
let step = parse_macro_input!(attribute as Step);
let function = parse_macro_input!(item as ItemFn);
expand_migration(step, function).unwrap_or_else(Error::into_compile_error).into()
}
/// Registers a migration that only switches nodes to another declaration: `rename!("module::old"@1 => "module::new"@2);`.
#[proc_macro]
pub fn rename(input: TokenStream) -> TokenStream {
let step = parse_macro_input!(input as Step);
expand_rename(step).unwrap_or_else(Error::into_compile_error).into()
}
/// Registers a format step converting the listed stored roots through their `Upgrade` impls:
/// `format_migration!(1 => 2, registry: v1::Registry, delta: v1::Delta);`. Roots left out keep their payloads.
#[proc_macro]
pub fn format_migration(input: TokenStream) -> TokenStream {
let step = parse_macro_input!(input as format::FormatStep);
let expanded = core_path().map(|core| {
let migration = format::expand(&core, &step);
let registration = registration(&core, quote!(register_format_migration), quote!(&FormatStep), &format!("format {}=>{}", step.from, step.to));
quote! {
const _: () = {
#migration
#registration
};
}
});
expanded.unwrap_or_else(Error::into_compile_error).into()
}
/// What one parameter of a migration function receives.
enum Argument {
Node,
Graph,
View(Box<Type>),
}
fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
let core = core_path()?;
let signature = &function.sig;
if let Some(asyncness) = signature.asyncness {
return Err(Error::new(asyncness.span(), "migrations run synchronously"));
}
if !signature.generics.params.is_empty() {
return Err(Error::new(signature.generics.span(), "migrations can't be generic"));
}
let arguments = signature.inputs.iter().map(classify).collect::<syn::Result<Vec<_>>>()?;
let views: Vec<&Type> = arguments
.iter()
.filter_map(|argument| match argument {
Argument::View(view) => Some(view.as_ref()),
_ => None,
})
.collect();
let reads_graph = arguments.iter().any(|argument| matches!(argument, Argument::Graph));
// Call the function with the source state and one extracted view per `&mut` parameter
let view_bindings: Vec<Ident> = (0..views.len()).map(|index| format_ident!("__view_{index}")).collect();
let mut view_index = 0;
let call_arguments = arguments.iter().map(|argument| match argument {
Argument::Node => quote!(context.source_node()),
Argument::Graph => quote!(&__graph),
Argument::View(_) => {
let binding = &view_bindings[view_index];
view_index += 1;
quote!(&mut #binding)
}
});
let function_name = &signature.ident;
let propagate = match &signature.output {
ReturnType::Default => quote!(),
ReturnType::Type(..) => quote!(?),
};
let graph_binding = reads_graph.then(|| quote!(let __graph = context.graph();));
let collect_edits = match view_bindings.as_slice() {
[] => quote!(Ok(#core::Edits::default())),
[binding] => quote!(#core::View::into_edits(#binding)),
bindings => quote! {
let mut edits = #core::Edits::default();
#(edits.merge(#core::View::into_edits(#bindings)?);)*
Ok(edits)
},
};
let run = quote! {
fn run(&self, context: &#core::AnchorContext) -> ::core::result::Result<#core::Edits, #core::MigrationError> {
#graph_binding
#(let mut #view_bindings = <#views as #core::View>::extract(context);)*
#function_name(#(#call_arguments),*) #propagate;
#collect_edits
}
};
let network_region = reads_graph.then(|| quote!(.union(#core::Region::NETWORK)));
let footprint = quote! {
fn footprint(&self) -> #core::Region {
#core::Region::ANCHOR #(.union(<#views as #core::View>::REGION))* #network_region
}
};
// Every `decl!` in the body orders this migration against the ones producing and consuming that declaration
let pins: Vec<Declaration> = scan_pins(quote!(#function))?.into_iter().filter(|pin| *pin != step.source && *pin != step.target).collect();
let pins = (!pins.is_empty()).then(|| {
let pins = pins.iter().map(|pin| declaration(&core, pin));
quote! {
fn pins(&self) -> &'static [#core::Declaration] {
const { &[#(#pins),*] }
}
}
});
let disjoint_views = (views.len() > 1).then(|| {
quote! {
const _: () = ::core::assert!(
#core::Region::disjoint(&[#(<#views as #core::View>::REGION),*]),
"two mutable views of one migration edit overlapping regions",
);
}
});
let struct_name = format_ident!("{}", function_name.to_string().to_case(Case::Pascal), span = function_name.span());
let visibility = &function.vis;
let docs = function.attrs.iter().filter(|attribute| attribute.path().is_ident("doc"));
let source = declaration(&core, &step.source);
let target = declaration(&core, &step.target);
let registration = registration(&core, quote!(register_migration), quote!(&#struct_name), &step_name(&step));
Ok(quote! {
#function
#(#docs)*
#visibility struct #struct_name;
impl #core::NodeMigration for #struct_name {
fn source(&self) -> #core::Declaration {
#source
}
fn target(&self) -> #core::Declaration {
#target
}
#pins
#footprint
#run
}
#disjoint_views
const _: () = {
#registration
};
})
}
fn classify(argument: &FnArg) -> syn::Result<Argument> {
let FnArg::Typed(typed) = argument else {
return Err(Error::new(argument.span(), "migrations are free functions"));
};
let Type::Reference(reference) = &*typed.ty else {
return Err(Error::new(typed.ty.span(), "migration parameters are `&Node`, `&Graph`, or `&mut` views"));
};
if reference.mutability.is_some() {
return Ok(Argument::View(reference.elem.clone()));
}
let Type::Path(path) = &*reference.elem else {
return Err(Error::new(reference.elem.span(), "shared references read the source state: `&Node` or `&Graph`"));
};
match path.path.segments.last().map(|segment| segment.ident.to_string()).as_deref() {
Some("Node") => Ok(Argument::Node),
Some("Graph") => Ok(Argument::Graph),
_ => Err(Error::new(reference.elem.span(), "shared references read the source state: `&Node` or `&Graph`")),
}
}
fn expand_rename(step: Step) -> syn::Result<TokenStream2> {
let core = core_path()?;
let source = declaration(&core, &step.source);
let target = declaration(&core, &step.target);
let registration = registration(&core, quote!(register_migration), quote!(&MIGRATION), &step_name(&step));
Ok(quote! {
const _: () = {
static MIGRATION: #core::Rename = #core::Rename::new(#source, #target);
#registration
};
})
}
fn step_name(step: &Step) -> String {
format!("{}@{}=>{}@{}", step.source.identifier, step.source.version, step.target.identifier, step.target.version)
}
/// Passes `migration` to `register` at startup: through `ctor` on native targets, and through an exported function the host calls
/// on wasm, where `ctor` isn't available. The export's name derives from `step_name`, so registering one step twice fails to link.
fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStream2, step_name: &str) -> TokenStream2 {
let hash = blake3::hash(step_name.as_bytes()).to_hex();
let export = format_ident!("__migration_registry_{}", &hash[..16]);
quote! {
use #core::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register() {
#core::#register(#migration);
}
#[cfg(target_family = "wasm")]
#[unsafe(no_mangle)]
extern "C" fn #export() {
register();
}
}
}
fn declaration(core: &TokenStream2, declaration: &Declaration) -> TokenStream2 {
let Declaration { identifier, version } = declaration;
quote!(#core::Declaration::new(#identifier, #version))
}
/// How the expansion names `migration-core`: `crate` inside it, its (possibly renamed) dependency name elsewhere.
fn core_path() -> syn::Result<TokenStream2> {
match proc_macro_crate::crate_name("migration-core") {
Ok(proc_macro_crate::FoundCrate::Itself) => Ok(quote!(crate)),
Ok(proc_macro_crate::FoundCrate::Name(name)) => {
let name = Ident::new(&name, Span::call_site());
Ok(quote!(::#name))
}
Err(error) => Err(Error::new(Span::call_site(), format!("migrations need `migration-core` as a dependency: {error}"))),
}
}
-90
View File
@@ -1,90 +0,0 @@
use proc_macro2::{TokenStream, TokenTree};
use syn::parse::{Parse, ParseStream};
use syn::{Error, LitInt, LitStr, Token};
/// A declaration as written in macro input: `"identifier"@version`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Declaration {
pub identifier: String,
pub version: u32,
}
impl Parse for Declaration {
fn parse(input: ParseStream) -> syn::Result<Self> {
let identifier: LitStr = input.parse()?;
input.parse::<Token![@]>()?;
let version: LitInt = input.parse()?;
Ok(Self {
identifier: identifier.value(),
version: version.base10_parse()?,
})
}
}
/// `"identifier"@n => "identifier"@m`, or `"identifier"@n => @m` for a version step that keeps the identifier.
pub struct Step {
pub source: Declaration,
pub target: Declaration,
}
impl Parse for Step {
fn parse(input: ParseStream) -> syn::Result<Self> {
let source: Declaration = input.parse()?;
input.parse::<Token![=>]>()?;
let target_identifier = match input.peek(LitStr) {
true => input.parse::<LitStr>()?.value(),
false => source.identifier.clone(),
};
input.parse::<Token![@]>()?;
let target_version_literal: LitInt = input.parse()?;
let target_version = target_version_literal.base10_parse()?;
// Every migration is exactly one step in its lineage, including renames
if Some(target_version) != source.version.checked_add(1) {
return Err(Error::new(
target_version_literal.span(),
format!("a migration steps one version, so the target must be version {}", source.version.saturating_add(1)),
));
}
let target = Declaration {
identifier: target_identifier,
version: target_version,
};
Ok(Self { source, target })
}
}
/// Every declaration named by a `decl!` call anywhere in `tokens`, including inside other macro calls, in first-appearance order.
pub fn scan_pins(tokens: TokenStream) -> syn::Result<Vec<Declaration>> {
let mut pins = Vec::new();
collect_pins(tokens, &mut pins)?;
Ok(pins)
}
fn collect_pins(tokens: TokenStream, pins: &mut Vec<Declaration>) -> syn::Result<()> {
let tokens: Vec<TokenTree> = tokens.into_iter().collect();
for (index, token) in tokens.iter().enumerate() {
match token {
TokenTree::Ident(ident) if ident == "decl" => {
let bang = matches!(tokens.get(index + 1), Some(TokenTree::Punct(punct)) if punct.as_char() == '!');
let Some(TokenTree::Group(group)) = tokens.get(index + 2) else { continue };
if !bang {
continue;
}
let pin: Declaration = syn::parse2(group.stream())?;
if !pins.contains(&pin) {
pins.push(pin);
}
}
TokenTree::Group(group) => collect_pins(group.stream(), pins)?,
_ => {}
}
}
Ok(())
}
-18
View File
@@ -1,18 +0,0 @@
[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"] }
serde = { workspace = true }
[dev-dependencies]
migration-runner = { workspace = true, features = ["testing"] }
[package.metadata.cargo-shear]
# Frozen mirrors of stored values, once a node migration needs one
ignored = ["serde"]
-4
View File
@@ -1,4 +0,0 @@
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod raster_nodes;
@@ -1,39 +0,0 @@
use migration_core::{Inputs, Node, migration};
/// 'Mix Colors' takes the under color first, like a 'Merge' takes its stack, where 'Mix' took the over color first.
#[migration("raster_nodes::blending_nodes::MixNode"@1 => "raster_nodes::blending_nodes::MixColorsNode"@2)]
pub fn mix_colors_from_mix_node(node: &Node, inputs: &mut Inputs) {
let [over, under, ..] = node.inputs() else { return };
inputs.set(0, under.input.clone());
inputs.set(1, over.input.clone());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MixColorsFromMixNode, &contract());
check_undo(&MixColorsFromMixNode, &contract());
}
#[test]
fn swaps_the_colors_and_keeps_the_rest() {
let (over, under, blend_mode, opacity) = (literal(1.), literal(2.), literal(3.), literal(4.));
let mut fixture = Fixture::new(&MixColorsFromMixNode);
let mix = fixture.add(decl!("raster_nodes::blending_nodes::MixNode"@1), vec![over.clone(), under.clone(), blend_mode.clone(), opacity.clone()]);
let migrated = fixture.migrate(&MixColorsFromMixNode).unwrap();
assert_eq!(fixture.declaration_of(&migrated, mix), Some(decl!("raster_nodes::blending_nodes::MixColorsNode"@2)));
assert_eq!(fixture.inputs(&migrated, mix), [under, over, blend_mode, opacity]);
}
}
@@ -1,3 +0,0 @@
//! Migrations of the nodes in `raster_nodes`.
mod mix_colors_from_mix_node;
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "migration-runner"
description = "Applies Graphite document migrations across the format and node tiers"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[features]
# Fixtures and history properties for migrations' tests, as `migration_runner::testing`.
testing = []
[dependencies]
migration-core = { workspace = true, features = ["typed"] }
document-graph-storage = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
migration-runner = { path = ".", features = ["testing"] }
serde = { workspace = true }
serde_json = { workspace = true }
-73
View File
@@ -1,73 +0,0 @@
//! Chains format steps over a document's serialized payloads, before they deserialize into the live types.
use crate::RunnerError;
use migration_core::{FormatMigration, HistoryPolicy, Payload};
/// The serialized payloads of one document, as handed over by the load path before typed
/// deserialization. History records are unframed: one [`Payload`] per retired delta, in stored
/// (topological) order. A working copy that only has history has no registry.
pub struct DocumentPayloads {
pub format_version: u32,
pub registry: Option<Payload>,
pub history: Vec<Payload>,
pub hot_log: Vec<Payload>,
pub session: Option<Payload>,
}
/// What the format tier did to history, so the load path knows whether a `Rev` rehash pass
/// (with session-cursor remap) is required after typed deserialization. Ordered by severity so
/// chained steps combine via `max`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum HistoryOutcome {
Untouched,
/// At least one step rewrote records: rehash `Rev`s with [`rehash_deltas`](crate::rehash_deltas) and remap cursors.
Rewritten,
/// At least one step truncated history: reset cursors, the document is a state-only snapshot.
Truncated,
}
/// Chain `migrations` from `payloads.format_version` up to `target_version`, bumping the version once per applied step.
/// A missing or ambiguous step in the chain is a hard error.
pub fn run_format_migrations(migrations: &[&'static dyn FormatMigration], payloads: &mut DocumentPayloads, target_version: u32) -> Result<HistoryOutcome, RunnerError> {
let mut outcome = HistoryOutcome::Untouched;
while payloads.format_version < target_version {
let version = payloads.format_version;
let step = match migrations.iter().filter(|migration| migration.migrates_from() == version).collect::<Vec<_>>().as_slice() {
[step] => **step,
[] => return Err(RunnerError::MissingFormatStep { at_version: version }),
_ => return Err(RunnerError::DuplicateFormatStep { at_version: version }),
};
let fail = |error| RunnerError::Format { from: version, error };
if let Some(registry) = &payloads.registry {
payloads.registry = Some(step.migrate_registry(registry).map_err(fail)?);
}
match step.history_policy() {
HistoryPolicy::Untouched => {}
HistoryPolicy::Rewrite => {
for record in &mut payloads.history {
*record = step.migrate_delta(record).map_err(fail)?;
}
outcome = outcome.max(HistoryOutcome::Rewritten);
}
HistoryPolicy::Truncate => {
payloads.history.clear();
outcome = HistoryOutcome::Truncated;
}
}
// Hot ops aren't in history yet, so they convert under every policy
for hot_op in &mut payloads.hot_log {
*hot_op = step.migrate_hot_op(hot_op).map_err(fail)?;
}
if let Some(session) = &payloads.session {
payloads.session = Some(step.migrate_session(session).map_err(fail)?);
}
payloads.format_version += 1;
}
Ok(outcome)
}
-48
View File
@@ -1,48 +0,0 @@
//! Applies document migrations: format-version chaining over serialized payloads, then node migrations that rewrite history into the
//! current shape. See `node-graph/rfcs/document-format-migrations.md` for the pipeline design.
mod format;
mod node;
mod order;
#[cfg(feature = "testing")]
pub mod testing;
use document_graph_storage::{CrdtError, NodeId, Rev};
use migration_core::{Declaration, InputConnector, MigrationError};
pub use document_graph_storage::rehash_deltas;
pub use format::{DocumentPayloads, HistoryOutcome, run_format_migrations};
pub use node::{DeclarationTable, RewrittenHistory, apply_migration, rewrite_history};
pub use order::{migrate_history, order_migrations, references};
#[derive(Debug, thiserror::Error)]
pub enum RunnerError {
#[error("no format migration registered from version {at_version}")]
MissingFormatStep { at_version: u32 },
#[error("two format migrations start from version {at_version}")]
DuplicateFormatStep { at_version: u32 },
#[error("format migration from version {from} failed: {error}")]
Format { from: u32, error: MigrationError },
#[error("migration from {migration} failed on node {anchor:?}: {error}")]
Migration { migration: Declaration, anchor: NodeId, error: MigrationError },
#[error("node {anchor:?} adds two nodes of {declaration} under the key {key:?}")]
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
AddedNodeExists(NodeId),
#[error("{0:?} is rewired by one anchor while its own migration replaces or removes it")]
ConflictingSlot(InputConnector),
#[error("{0:?} does not exist in the migrated state")]
MissingConsumer(InputConnector),
#[error("delta {0:?} branches or merges, which the rewrite does not handle yet")]
NonLinearHistory(Rev),
#[error("a rewritten chain both removes and adds node {0:?}, which a shared timestamp can't order")]
ChainWritesTwice(NodeId),
#[error("two migrations start from {0}")]
DuplicateMigration(Declaration),
#[error("migration from {from} to {to} does not step exactly one version")]
InvalidStep { from: Declaration, to: Declaration },
#[error("migrations from {0:?} depend on each other in a cycle")]
OrderCycle(Vec<Declaration>),
#[error("failed to apply a delta: {0}")]
Crdt(#[from] CrdtError),
}
-260
View File
@@ -1,260 +0,0 @@
//! The node tier: `M` as a function on registry states, and the history rewrite derived from it.
use crate::RunnerError;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, Node, NodeId, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, NodeMigration, OutputConnector};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations, whose resource IDs derive from `identifier@version`.
#[derive(Clone, Debug, Default)]
pub struct DeclarationTable {
declarations: HashMap<ResourceId, Declaration>,
}
impl DeclarationTable {
pub fn new(declarations: impl IntoIterator<Item = Declaration>) -> Self {
let mut table = Self::default();
for declaration in declarations {
table.register(declaration);
}
table
}
/// Register every declaration `migration` reads or writes.
pub fn register_migration(&mut self, migration: &dyn NodeMigration) {
self.register(migration.source());
self.register(migration.target());
for pin in migration.pins() {
self.register(*pin);
}
}
pub fn register(&mut self, declaration: Declaration) -> ResourceId {
let resource = Self::resource_id(declaration);
self.declarations.insert(resource, declaration);
resource
}
pub fn resource_id(declaration: Declaration) -> ResourceId {
ResourceId::from_hash(&ResourceHash::from(declaration.to_string().as_bytes()))
}
}
impl DeclarationResolver for DeclarationTable {
fn declaration(&self, resource: ResourceId) -> Option<Declaration> {
self.declarations.get(&resource).copied()
}
fn resource(&self, declaration: Declaration) -> ResourceId {
Self::resource_id(declaration)
}
}
/// `M`: run `migration` on every anchor in `source` and apply the edits. Every run reads `source`, so no run observes another's edits.
pub fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver) -> Result<Registry, RunnerError> {
let mut target = source.clone();
let mut runs = Vec::new();
for anchor in anchors(migration.source(), source, resolver) {
let Some(context) = AnchorContext::new(source, anchor, migration.source(), migration.target(), resolver) else {
continue;
};
let edits = migration.run(&context).map_err(|error| RunnerError::Migration {
migration: migration.source(),
anchor,
error,
})?;
runs.push((anchor, edits));
}
if runs.is_empty() {
return Ok(target);
}
add_nodes(&mut target, &runs, resolver)?;
let input_edits: HashMap<NodeId, &InputsEdit> = runs.iter().filter_map(|(anchor, edits)| Some((*anchor, edits.inputs.as_ref()?))).collect();
for (anchor, inputs) in &input_edits {
let Some(node) = target.node_instances.get_mut(anchor) else { continue };
*node.inputs_mut() = inputs.slots.clone();
}
for (_, edits) in &runs {
for (output, consumer) in &edits.connections {
connect(&mut target, *output, *consumer, &input_edits)?;
}
}
for (_, edits) in &runs {
for removed in &edits.removed_nodes {
target.node_instances.remove(removed);
}
}
let target_implementation = Implementation::ProtoNode(resolver.resource(migration.target()));
for (anchor, _) in &runs {
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = target_implementation.clone();
}
}
let added_declarations = runs.iter().flat_map(|(_, edits)| edits.added_nodes.iter().map(|added| added.node.declaration));
for declaration in std::iter::once(migration.target()).chain(added_declarations) {
if let Some(entry) = resolver.resource_entry(declaration) {
target.resources.entry(resolver.resource(declaration)).or_insert(entry);
}
}
Ok(target)
}
/// The live nodes of `declaration`, in ID order.
fn anchors(declaration: Declaration, registry: &Registry, resolver: &dyn DeclarationResolver) -> Vec<NodeId> {
let mut anchors: Vec<NodeId> = registry
.node_instances
.iter()
.filter(|(_, node)| matches!(node.implementation(), Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration)))
.map(|(id, _)| *id)
.collect();
anchors.sort_unstable();
anchors
}
fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn DeclarationResolver) -> Result<(), RunnerError> {
let mut added_ids = HashSet::new();
for (anchor, edits) in runs {
let Some(network) = target.node_instances.get(anchor).map(Node::network) else { continue };
for added in &edits.added_nodes {
if !added_ids.insert(added.id) {
return Err(RunnerError::DuplicateAddedNode {
anchor: *anchor,
declaration: added.node.declaration,
key: added.key.clone(),
});
}
if target.node_instances.contains_key(&added.id) {
return Err(RunnerError::AddedNodeExists(added.id));
}
let implementation = Implementation::ProtoNode(resolver.resource(added.node.declaration));
let mut node = Node::new(network, implementation, added.node.inputs.len());
for (slot, input) in node.inputs_mut().iter_mut().zip(&added.node.inputs) {
slot.input = input.clone();
}
target.node_instances.insert(added.id, node);
}
}
Ok(())
}
/// Make `consumer`, named in the source layout, read `output` in the target layout. Fails when the consumer's own migration replaced or
/// removed that slot, since two runs then disagree on what it should read.
fn connect(target: &mut Registry, output: OutputConnector, consumer: InputConnector, input_edits: &HashMap<NodeId, &InputsEdit>) -> Result<(), RunnerError> {
match consumer {
InputConnector::Node { node, input } => {
let index = match input_edits.get(&node) {
Some(inputs) => inputs.target_index(input).ok_or(RunnerError::ConflictingSlot(consumer))?,
None => input,
};
let slot = target.node_instances.get_mut(&node).and_then(|node| node.inputs_mut().get_mut(index as usize));
let slot = slot.ok_or(RunnerError::MissingConsumer(consumer))?;
slot.input = output.into();
}
InputConnector::Export { network, index } => {
let slot = target.networks.get_mut(&network).and_then(|network| network.exports.get_mut(index as usize));
let slot = slot.ok_or(RunnerError::MissingConsumer(consumer))?;
slot.target = Some(output.into());
}
}
Ok(())
}
/// A history rewritten into the shape `M` produces, with where each original delta went.
pub struct RewrittenHistory {
pub deltas: Vec<Delta>,
/// Each original `Rev` mapped to the last delta of its rewritten chain, or to its parent's mapping when the chain is empty.
pub revs: HashMap<Rev, Option<Rev>>,
}
/// Rewrite a linear `history` so replaying it yields `M` of the original at every step: `rewritten(d) = diff(R(d), M(O(d) + d))`.
///
/// Each delta costs one full evaluation of `M` and one full diff, so this is O(history × registry). The incremental, footprint-scoped
/// evaluation the RFC describes comes later.
pub fn rewrite_history(migration: &dyn NodeMigration, history: &[Delta], resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
let mut original = Registry::default();
let mut rewritten = Registry::default();
let mut deltas: Vec<Delta> = Vec::with_capacity(history.len());
let mut revs = HashMap::with_capacity(history.len());
let mut previous_original = None;
let mut tip = None;
for delta in history {
if delta.parent != previous_original || matches!(delta.kind, RegistryDelta::Merge { .. }) {
return Err(RunnerError::NonLinearHistory(delta.id));
}
previous_original = Some(delta.id);
apply_retired_op(&mut original, delta.kind.clone(), delta.timestamp)?;
let chain = if passes_through(&delta.kind) {
vec![delta.kind.clone()]
} else {
let migrated = apply_migration(migration, &original, resolver)?;
compute_deltas(&rewritten, &migrated)
};
check_single_writes(&chain)?;
// Every op of the chain shares the original's timestamp, which orders it after everything the original saw
let chain_start = deltas.len();
for op in chain {
let reverse = apply_retired_op(&mut rewritten, op.clone(), delta.timestamp)?;
let rewritten_delta = Delta::new(tip, delta.author, delta.timestamp, op, reverse);
tip = Some(rewritten_delta.id);
deltas.push(rewritten_delta);
}
// A dropped delta's interaction end moves to the rewritten delta before it, so undo keeps its checkpoint
match deltas[chain_start..].last_mut() {
Some(last) => last.carry_annotations(delta),
None if delta.is_interaction_end() => {
if let Some(previous) = deltas.last_mut() {
previous.mark_interaction_end(delta.timestamp);
}
}
None => {}
}
revs.insert(delta.id, tip);
}
Ok(RewrittenHistory { deltas, revs })
}
/// Ops `M` can't affect and `compute_deltas` doesn't diff, which therefore keep their original form.
fn passes_through(kind: &RegistryDelta) -> bool {
matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Other(_))
}
/// Ops of one chain share a timestamp, and last-writer-wins needs a newer stamp to overwrite, so no chain may write one entity twice.
fn check_single_writes(chain: &[RegistryDelta]) -> Result<(), RunnerError> {
let mut removed = HashSet::new();
let mut added = HashSet::new();
for op in chain {
match op {
RegistryDelta::RemoveNode { id, .. } => removed.insert(*id),
RegistryDelta::AddNode { id, .. } => added.insert(*id),
_ => continue,
};
}
match removed.intersection(&added).next() {
Some(id) => Err(RunnerError::ChainWritesTwice(*id)),
None => Ok(()),
}
}
-104
View File
@@ -1,104 +0,0 @@
//! Orders registered node migrations by the declarations they read and write, and runs every pending one over a history.
use crate::{RewrittenHistory, RunnerError, rewrite_history};
use document_graph_storage::{Delta, Implementation, Node, RegistryDelta, Rev};
use migration_core::{Declaration, DeclarationResolver, NodeMigration};
use std::collections::{BTreeSet, HashMap};
/// Order `migrations` so each runs after the one producing its source and before the one consuming its target, and pinned
/// declarations exist in exactly the version the body names. Unrelated migrations order by source declaration, so the result
/// doesn't depend on registration order. Kahn's algorithm, O(n²) in the number of migrations to find edges.
pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec<&'static dyn NodeMigration>, RunnerError> {
let mut migrations = migrations.to_vec();
migrations.sort_by_key(|migration| (migration.source(), migration.target()));
for pair in migrations.windows(2) {
if pair[0].source() == pair[1].source() {
return Err(RunnerError::DuplicateMigration(pair[0].source()));
}
}
if let Some(migration) = migrations.iter().find(|migration| Some(migration.target().version) != migration.source().version.checked_add(1)) {
return Err(RunnerError::InvalidStep {
from: migration.source(),
to: migration.target(),
});
}
let producer = |declaration: Declaration| migrations.iter().position(|migration| migration.target() == declaration);
let consumer = |declaration: Declaration| migrations.iter().position(|migration| migration.source() == declaration);
// `successors[a]` holds every migration that must run after `a`
let mut successors = vec![Vec::new(); migrations.len()];
for (index, migration) in migrations.iter().enumerate() {
if let Some(next) = consumer(migration.target()) {
successors[index].push(next);
}
for pin in migration.pins() {
if let Some(before) = producer(*pin) {
successors[before].push(index);
}
if let Some(after) = consumer(*pin) {
successors[index].push(after);
}
}
}
let mut predecessor_counts = vec![0; migrations.len()];
for next in successors.iter().flatten() {
predecessor_counts[*next] += 1;
}
// Indices follow the sort above, so the smallest ready index is the smallest source
let mut ready: BTreeSet<usize> = (0..migrations.len()).filter(|index| predecessor_counts[*index] == 0).collect();
let mut ordered = Vec::with_capacity(migrations.len());
while let Some(index) = ready.pop_first() {
ordered.push(migrations[index]);
for next in &successors[index] {
predecessor_counts[*next] -= 1;
if predecessor_counts[*next] == 0 {
ready.insert(*next);
}
}
}
if ordered.len() < migrations.len() {
let cycle = (0..migrations.len()).filter(|index| predecessor_counts[*index] > 0).map(|index| migrations[index].source()).collect();
return Err(RunnerError::OrderCycle(cycle));
}
Ok(ordered)
}
/// Rewrite `history` through every migration whose source declaration it references, in dependency order. A migration is pending
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back.
pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<Delta>, resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
let mut revs: HashMap<Rev, Option<Rev>> = history.iter().map(|delta| (delta.id, Some(delta.id))).collect();
let mut deltas = history;
for migration in order_migrations(migrations)? {
if !deltas.iter().any(|delta| references(&delta.kind, migration.source(), resolver)) {
continue;
}
let step = rewrite_history(migration, &deltas, resolver)?;
for rev in revs.values_mut() {
*rev = rev.and_then(|rev| step.revs.get(&rev).copied().flatten());
}
deltas = step.deltas;
}
Ok(RewrittenHistory { deltas, revs })
}
/// Whether `kind` stores a node implementing `declaration`.
pub fn references(kind: &RegistryDelta, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool {
let is_declaration = |implementation: &Implementation| matches!(implementation, Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration));
let implements = |node: &Node| is_declaration(node.implementation());
match kind {
RegistryDelta::AddNode { node, .. } => implements(node),
RegistryDelta::RemoveNode { snapshot, .. } => implements(snapshot),
RegistryDelta::SetNodeImplementation { implementation, .. } => is_declaration(implementation),
_ => false,
}
}
-297
View File
@@ -1,297 +0,0 @@
//! What every migration's tests need: fixtures for one anchor, and the property that rewriting a generated history gives `M` of it at every step.
//! Panics on failure, since it only runs in tests.
use crate::{DeclarationTable, RunnerError, apply_migration, references, rewrite_history};
use document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, decl, literal, registered_migrations};
/// A root network built node by node, for running one migration on.
pub struct Fixture {
pub registry: Registry,
pub table: DeclarationTable,
next_id: u64,
}
impl Fixture {
pub fn new(migration: &dyn NodeMigration) -> Self {
let mut registry = Registry::default();
registry.networks.insert(ROOT_NETWORK, Network::default());
let mut table = DeclarationTable::default();
table.register_migration(migration);
Self { registry, table, next_id: 0 }
}
pub fn add(&mut self, declaration: Declaration, inputs: Vec<NodeInput>) -> NodeId {
self.next_id += 1;
let id = NodeId(self.next_id);
let resource = self.table.register(declaration);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), inputs.len());
for (slot, input) in node.inputs_mut().iter_mut().zip(inputs) {
slot.input = input;
}
self.registry.node_instances.insert(id, node);
id
}
pub fn export(&mut self, input: NodeInput) {
let network = self.registry.networks.get_mut(&ROOT_NETWORK).expect("the fixture creates the root network");
network.exports.push(ExportSlot {
target: Some(input),
..Default::default()
});
}
pub fn migrate(&self, migration: &dyn NodeMigration) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table)
}
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
let Implementation::ProtoNode(resource) = registry.node_instances.get(&node)?.implementation() else {
return None;
};
self.table.declaration(*resource)
}
/// The input slots of `node` in `registry`.
pub fn inputs(&self, registry: &Registry, node: NodeId) -> Vec<NodeInput> {
registry.node_instances[&node].inputs().iter().map(|slot| slot.input.clone()).collect()
}
}
/// The registered migration starting from `source`.
pub fn registered(source: Declaration) -> &'static dyn NodeMigration {
let migration = registered_migrations().into_iter().find(|migration| migration.source() == source);
migration.unwrap_or_else(|| panic!("no migration from {source} is registered"))
}
/// Small deterministic generator, so a failing seed reproduces.
pub struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
// Xorshift64
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
pub fn below(&mut self, bound: usize) -> usize {
(self.next() % bound as u64) as usize
}
pub fn pick<T: Copy>(&mut self, items: &[T]) -> T {
items[self.below(items.len())]
}
}
/// What the source declaration allows, so generated histories only hold states a real document could.
pub struct SourceContract {
pub input_count: usize,
/// A literal the declaration allows in a slot.
pub literal: fn(&mut Random, usize) -> NodeInput,
/// Whether a slot may read an output of another node of the source declaration.
pub reads_own_output: fn(usize) -> bool,
}
impl SourceContract {
pub fn new(input_count: usize, literal: fn(&mut Random, usize) -> NodeInput) -> Self {
Self {
input_count,
literal,
reads_own_output: |_| true,
}
}
}
/// A node generated histories wire to and from the anchors, whose literals no migration reads.
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
const CONSUMER_INPUTS: usize = 2;
struct Generator<'a> {
random: Random,
session: Session,
table: &'a mut DeclarationTable,
source: Declaration,
contract: &'a SourceContract,
}
impl Generator<'_> {
fn commit(&mut self, op: RegistryDelta) {
self.session.stage_computed_ops(vec![op]).expect("generated ops are valid");
let revs = self.session.retire_all().expect("staged ops retire");
if let Some(last) = revs.last() {
self.session.mark_interaction_end(*last);
}
}
fn live_nodes(&self) -> Vec<NodeId> {
let mut nodes: Vec<NodeId> = self.session.registry().node_instances.keys().copied().collect();
nodes.sort_unstable();
nodes
}
fn declaration_of(&self, node: &Node) -> Option<Declaration> {
let Implementation::ProtoNode(resource) = node.implementation() else { return None };
[self.source, CONSUMER].into_iter().find(|declaration| DeclarationTable::resource_id(*declaration) == *resource)
}
/// A literal or a wire to another live node.
fn input_for(&mut self, declaration: Declaration, slot: usize, exclude: Option<NodeId>) -> NodeInput {
let is_source = declaration == self.source;
let reads_own_output = !is_source || (self.contract.reads_own_output)(slot);
let registry = self.session.registry();
let allowed = |node: &NodeId| reads_own_output || self.declaration_of(&registry.node_instances[node]) != Some(self.source);
let candidates: Vec<NodeId> = self.live_nodes().into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect();
if !candidates.is_empty() && self.random.below(2) == 0 {
let node = self.random.pick(&candidates);
return NodeInput::Node { id: node, index: 0 };
}
if is_source {
(self.contract.literal)(&mut self.random, slot)
} else {
literal(self.random.below(10) as f64)
}
}
fn step(&mut self) {
let nodes = self.live_nodes();
match self.random.below(10) {
0..=3 => {
let (declaration, input_count) = if self.random.below(3) == 0 {
(self.source, self.contract.input_count)
} else {
(CONSUMER, CONSUMER_INPUTS)
};
let resource = self.table.register(declaration);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), input_count);
for slot in 0..input_count {
node.inputs_mut()[slot].input = self.input_for(declaration, slot, None);
}
let id = self.session.next_node_id();
self.commit(RegistryDelta::AddNode { id, node });
}
4..=6 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let node = self.session.registry().node_instances[&id].clone();
let Some(declaration) = self.declaration_of(&node) else { return };
if node.inputs().is_empty() {
return;
}
let index = self.random.below(node.inputs().len());
let new_input = self.input_for(declaration, index, Some(id));
if node.inputs()[index].input == new_input {
return;
}
self.commit(RegistryDelta::ChangeNodeInput { id, index: index as u32, new_input });
}
7 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let snapshot = self.session.registry().node_instances[&id].clone();
self.commit(RegistryDelta::RemoveNode { id, snapshot });
}
8 | 9 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let index = self.random.below(2) as u32;
let export = Some(NodeInput::Node { id, index: 0 });
let exports = &self.session.registry().networks[&ROOT_NETWORK].exports;
if exports.get(index as usize).is_some_and(|slot| slot.target == export) {
return;
}
self.commit(RegistryDelta::SetNetworkExport { id: ROOT_NETWORK, index, export });
}
_ => {}
}
}
}
/// A random linear history over `migration`'s source declaration, and the table resolving it.
fn generate(migration: &dyn NodeMigration, contract: &SourceContract, seed: u64, steps: usize) -> (Session, DeclarationTable) {
let mut table = DeclarationTable::default();
table.register_migration(migration);
let mut generator = Generator {
random: Random(seed.max(1)),
session: Session::with_identity(PeerId(1), UserId(1)),
table: &mut table,
source: migration.source(),
contract,
};
generator.commit(RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
});
for _ in 0..steps {
generator.step();
}
(generator.session, table)
}
/// The registry `deltas` build from nothing.
pub fn replay(deltas: &[Delta]) -> Registry {
let mut registry = Registry::default();
for delta in deltas {
apply_retired_op(&mut registry, delta.kind.clone(), delta.timestamp).expect("history replays");
}
registry
}
/// `replay(rewrite(H)) == M(replay(H))` on generated histories, which also proves the rewrite leaves none of the old shape behind.
pub fn check_commutation(migration: &dyn NodeMigration, contract: &SourceContract) {
for seed in 1..50 {
let (session, table) = generate(migration, contract, seed, 40);
let history: Vec<Delta> = session.history().cloned().collect();
let expected = apply_migration(migration, &replay(&history), &table).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
assert!(
replay(&rewritten.deltas).value_equal(&expected),
"seed {seed}: replaying the rewritten history differs from M of the original"
);
let stale = rewritten.deltas.iter().find(|delta| references(&delta.kind, migration.source(), &table));
assert!(stale.is_none(), "seed {seed}: rewritten history still holds the source shape: {stale:?}");
for (index, delta) in rewritten.deltas.iter().enumerate() {
assert!(delta.has_valid_id(), "seed {seed}: rewritten delta {index} has a stale rev");
let expected_parent = index.checked_sub(1).map(|previous| rewritten.deltas[previous].id);
assert_eq!(delta.parent, expected_parent, "seed {seed}: rewritten delta {index} is not chained onto its predecessor");
}
}
}
/// Undo walks the rewritten deltas' reverse priors, so undoing in rewritten history must land on `M` of the undone original.
pub fn check_undo(migration: &dyn NodeMigration, contract: &SourceContract) {
for seed in 1..20 {
let (session, table) = generate(migration, contract, seed, 30);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let mut original = Session::replay_from_history(PeerId(1), UserId(1), history, 0).expect("the generated history replays");
let mut migrated = Session::replay_from_history(PeerId(1), UserId(1), rewritten.deltas, 0).expect("the rewritten history replays");
for undo in 0..5 {
if !original.can_undo() {
break;
}
original.undo().expect("can_undo said so");
migrated.undo().unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: {error}"));
let expected = apply_migration(migration, original.registry(), &table).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
assert!(migrated.registry().value_equal(&expected), "seed {seed}, undo {undo}: undone states diverge");
}
}
}
@@ -1,57 +0,0 @@
use migration_core::{FormatMigration, HistoryPolicy, MigrationError, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, run_format_migrations};
/// A v1 → v2 format step that renames a top-level registry key, exercising the frozen-shape
/// decode/encode round trip.
struct RenameKey;
impl FormatMigration for RenameKey {
fn migrates_from(&self) -> u32 {
1
}
fn migrate_registry(&self, registry: &Payload) -> Result<Payload, MigrationError> {
let mut value: serde_json::Value = registry.decode()?;
if let Some(object) = value.as_object_mut()
&& let Some(old) = object.remove("old_key")
{
object.insert("new_key".to_string(), old);
}
registry.encode_as(&value)
}
fn history_policy(&self) -> HistoryPolicy {
HistoryPolicy::Truncate
}
}
#[test]
fn format_tier_chains_and_bumps_version() {
let mut payloads = DocumentPayloads {
format_version: 1,
registry: Some(Payload::encode(&serde_json::json!({ "old_key": 42 }), PayloadCodec::Json).unwrap()),
history: vec![Payload::new(vec![1, 2, 3], PayloadCodec::Postcard)],
hot_log: Vec::new(),
session: None,
};
let outcome = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap();
assert_eq!(payloads.format_version, 2);
assert_eq!(outcome, HistoryOutcome::Truncated);
assert!(payloads.history.is_empty());
let registry: serde_json::Value = payloads.registry.unwrap().decode().unwrap();
assert_eq!(registry, serde_json::json!({ "new_key": 42 }));
}
#[test]
fn format_tier_errors_on_missing_step() {
let mut payloads = DocumentPayloads {
format_version: 0,
registry: Some(Payload::encode(&serde_json::json!({}), PayloadCodec::Json).unwrap()),
history: Vec::new(),
hot_log: Vec::new(),
session: None,
};
let error = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap_err();
assert!(matches!(error, RunnerError::MissingFormatStep { at_version: 0 }));
}
@@ -1,109 +0,0 @@
//! The RFC's examples, written the way a migration crate would. `#[migration]` generates a unit struct per function, and the
//! registry picks every migration up at startup.
use migration_core::{Downstream, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration, rename};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;
/// Frozen mirror of the `TaggedValue` variants these migrations use.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tagged {
Number(f64),
Bool(bool),
XY(Axis),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Axis {
X,
Y,
}
rename!("graphene_core::ops::AddNode"@1 => "math_nodes::add"@2);
// Later steps of the lineages below, so ordering has chains and pins to respect
rename!("math_nodes::multiply"@1 => "math_nodes::product"@2);
rename!("vector_nodes::split_vec2"@2 => "vector_nodes::split"@3);
/// Adds the opacity and fill toggles.
#[migration("blending_nodes::opacity"@1 => @2)]
pub fn opacity_toggles(inputs: &mut Inputs) {
inputs.insert(1, literal(Tagged::Bool(true)));
inputs.push(literal(Tagged::Bool(false)));
inputs.push(literal(Tagged::Number(100.)));
}
pub const ROTATION: u32 = 2;
/// Rotation is now stored in degrees.
#[migration("transform_nodes::transform"@1 => @2)]
pub fn transform_degrees(node: &Node, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
let rotation = &node.inputs()[ROTATION as usize].input;
let converted = match rotation {
NodeInput::Value { exposed, .. } => {
let Some(Tagged::Number(radians)) = literal_of(rotation) else {
return Err(MigrationError::invariant("rotation is not a number"));
};
NodeInput::Value {
value: encode(&Tagged::Number(radians.to_degrees())),
exposed: *exposed,
}
}
// Only known at runtime, so convert upstream
wired => {
let multiply = upstream.add_node(NewNode {
declaration: decl!("math_nodes::multiply"@1),
inputs: vec![wired.clone(), literal(Tagged::Number(180. / PI))],
});
NodeInput::Node { id: multiply, index: 0 }
}
};
inputs.set(ROTATION, converted);
Ok(())
}
/// The output is now in degrees, so consumers keep receiving radians through a conversion.
#[migration("vector_nodes::angle_between"@1 => @2)]
pub fn angle_between_degrees(node: &Node, downstream: &mut Downstream) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let conversion = downstream.add_node(NewNode {
declaration: decl!("math_nodes::to_radians"@1),
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }],
});
for consumer in consumers {
downstream.connect(OutputConnector { node: conversion, output: 0 }, consumer);
}
}
/// Extract XY becomes Split Vec2 with one output per component. A wired axis selects between them at runtime.
#[migration("vector_nodes::extract_xy"@1 => "vector_nodes::split_vec2"@2)]
pub fn extract_xy_to_split(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream) -> Result<(), MigrationError> {
let axis = &node.inputs()[1].input;
let component = match literal_of::<Tagged>(axis) {
Some(Tagged::XY(Axis::X)) => OutputConnector { node: node.id(), output: 0 },
Some(Tagged::XY(Axis::Y)) => OutputConnector { node: node.id(), output: 1 },
Some(_) => return Err(MigrationError::invariant("axis is not an XY value")),
None if matches!(axis, NodeInput::Value { .. }) => return Err(MigrationError::invariant("axis is not an XY value")),
None => {
let select = downstream.add_node(NewNode {
declaration: decl!("logic_nodes::select_axis"@1),
inputs: vec![axis.clone(), NodeInput::Node { id: node.id(), index: 0 }, NodeInput::Node { id: node.id(), index: 1 }],
});
OutputConnector { node: select, output: 0 }
}
};
// Source state only, so the select node added above isn't among these
for consumer in downstream.consumers(0) {
downstream.connect(component, consumer);
}
inputs.truncate(1);
Ok(())
}
@@ -1,182 +0,0 @@
mod examples;
mod registration;
mod rewrite;
use document_graph_storage::{NodeId, NodeInput, ROOT_NETWORK, Registry};
use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use migration_core::{decl, literal, literal_of};
use migration_runner::RunnerError;
use migration_runner::testing::{Fixture, registered};
fn wire(node: NodeId, index: u32) -> NodeInput {
NodeInput::Node { id: node, index }
}
fn inputs(registry: &Registry, node: NodeId) -> Vec<NodeInput> {
registry.node_instances[&node].inputs().iter().map(|slot| slot.input.clone()).collect()
}
/// The nodes `migrated` has that `source` doesn't.
fn added_nodes(source: &Registry, migrated: &Registry) -> Vec<NodeId> {
let mut added: Vec<NodeId> = migrated.node_instances.keys().filter(|id| !source.node_instances.contains_key(id)).copied().collect();
added.sort_unstable();
added
}
#[test]
fn rename_switches_declaration_and_keeps_inputs() {
let migration = registered(decl!("graphene_core::ops::AddNode"@1));
let mut fixture = Fixture::new(migration);
let add = fixture.add(decl!("graphene_core::ops::AddNode"@1), vec![literal(Tagged::Number(1.)), literal(Tagged::Number(2.))]);
let migrated = fixture.migrate(migration).unwrap();
assert_eq!(fixture.declaration_of(&migrated, add), Some(decl!("math_nodes::add"@2)));
assert_eq!(inputs(&migrated, add), inputs(&fixture.registry, add));
}
#[test]
fn opacity_toggles_build_the_target_layout() {
let mut fixture = Fixture::new(&OpacityToggles);
let content = fixture.add(decl!("math_nodes::add"@1), vec![]);
let opacity = fixture.add(decl!("blending_nodes::opacity"@1), vec![wire(content, 0), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&OpacityToggles).unwrap();
let expected = vec![
wire(content, 0),
literal(Tagged::Bool(true)),
literal(Tagged::Number(50.)),
literal(Tagged::Bool(false)),
literal(Tagged::Number(100.)),
];
assert_eq!(inputs(&migrated, opacity), expected);
assert_eq!(fixture.declaration_of(&migrated, opacity), Some(decl!("blending_nodes::opacity"@2)));
}
#[test]
fn transform_converts_a_literal_rotation() {
let mut fixture = Fixture::new(&TransformDegrees);
let transform = fixture.add(
decl!("transform_nodes::transform"@1),
vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Number(std::f64::consts::PI))],
);
let migrated = fixture.migrate(&TransformDegrees).unwrap();
let rotation = &inputs(&migrated, transform)[ROTATION as usize];
assert_eq!(literal_of::<Tagged>(rotation), Some(Tagged::Number(180.)));
assert!(added_nodes(&fixture.registry, &migrated).is_empty());
}
#[test]
fn transform_converts_a_wired_rotation_upstream() {
let mut fixture = Fixture::new(&TransformDegrees);
let angle = fixture.add(decl!("math_nodes::add"@1), vec![]);
let transform = fixture.add(decl!("transform_nodes::transform"@1), vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), wire(angle, 0)]);
let migrated = fixture.migrate(&TransformDegrees).unwrap();
let [multiply] = added_nodes(&fixture.registry, &migrated)[..] else {
panic!("expected one inserted node")
};
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::multiply"@1)));
assert_eq!(inputs(&migrated, multiply)[0], wire(angle, 0));
assert_eq!(inputs(&migrated, transform)[ROTATION as usize], wire(multiply, 0));
}
#[test]
fn transform_rejects_a_rotation_of_the_wrong_variant() {
let mut fixture = Fixture::new(&TransformDegrees);
fixture.add(
decl!("transform_nodes::transform"@1),
vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Bool(true))],
);
let error = fixture.migrate(&TransformDegrees).unwrap_err();
assert!(matches!(error, RunnerError::Migration { .. }), "{error}");
}
/// The inserted node's ID derives from the migration, anchor, and declaration, so a different source state yields the same node.
#[test]
fn inserted_node_ids_are_stable_across_states() {
let mut fixture = Fixture::new(&TransformDegrees);
let angle = fixture.add(decl!("math_nodes::add"@1), vec![]);
let other_angle = fixture.add(decl!("math_nodes::add"@1), vec![]);
let transform = fixture.add(decl!("transform_nodes::transform"@1), vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), wire(angle, 0)]);
let first = fixture.migrate(&TransformDegrees).unwrap();
fixture.registry.node_instances.get_mut(&transform).unwrap().inputs_mut()[ROTATION as usize].input = wire(other_angle, 0);
let second = fixture.migrate(&TransformDegrees).unwrap();
assert_eq!(added_nodes(&fixture.registry, &first), added_nodes(&fixture.registry, &second));
}
#[test]
fn angle_between_routes_consumers_through_a_conversion() {
let mut fixture = Fixture::new(&AngleBetweenDegrees);
let angle = fixture.add(decl!("vector_nodes::angle_between"@1), vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.))]);
let consumer = fixture.add(decl!("math_nodes::add"@1), vec![literal(Tagged::Number(1.)), wire(angle, 0)]);
fixture.export(wire(angle, 0));
let migrated = fixture.migrate(&AngleBetweenDegrees).unwrap();
let [conversion] = added_nodes(&fixture.registry, &migrated)[..] else {
panic!("expected one inserted node")
};
assert_eq!(inputs(&migrated, conversion), vec![wire(angle, 0)]);
assert_eq!(inputs(&migrated, consumer)[1], wire(conversion, 0));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(conversion, 0)));
}
#[test]
fn angle_between_without_consumers_adds_nothing() {
let mut fixture = Fixture::new(&AngleBetweenDegrees);
let angle = fixture.add(decl!("vector_nodes::angle_between"@1), vec![]);
let migrated = fixture.migrate(&AngleBetweenDegrees).unwrap();
assert!(added_nodes(&fixture.registry, &migrated).is_empty());
assert_eq!(fixture.declaration_of(&migrated, angle), Some(decl!("vector_nodes::angle_between"@2)));
}
#[test]
fn extract_xy_with_a_literal_axis_picks_an_output() {
let mut fixture = Fixture::new(&ExtractXyToSplit);
let extract = fixture.add(decl!("vector_nodes::extract_xy"@1), vec![literal(Tagged::Number(0.)), literal(Tagged::XY(Axis::Y))]);
let consumer = fixture.add(decl!("math_nodes::add"@1), vec![wire(extract, 0)]);
let migrated = fixture.migrate(&ExtractXyToSplit).unwrap();
assert_eq!(inputs(&migrated, consumer), vec![wire(extract, 1)]);
assert_eq!(inputs(&migrated, extract), vec![literal(Tagged::Number(0.))]);
assert_eq!(fixture.declaration_of(&migrated, extract), Some(decl!("vector_nodes::split_vec2"@2)));
}
#[test]
fn extract_xy_with_a_wired_axis_selects_at_runtime() {
let mut fixture = Fixture::new(&ExtractXyToSplit);
let axis = fixture.add(decl!("math_nodes::add"@1), vec![]);
let extract = fixture.add(decl!("vector_nodes::extract_xy"@1), vec![literal(Tagged::Number(0.)), wire(axis, 0)]);
let consumer = fixture.add(decl!("math_nodes::add"@1), vec![wire(extract, 0)]);
let migrated = fixture.migrate(&ExtractXyToSplit).unwrap();
let [select] = added_nodes(&fixture.registry, &migrated)[..] else {
panic!("expected one inserted node")
};
assert_eq!(inputs(&migrated, select), vec![wire(axis, 0), wire(extract, 0), wire(extract, 1)]);
assert_eq!(inputs(&migrated, consumer), vec![wire(select, 0)]);
}
/// One anchor rewires a slot that another anchor's own migration removes. Both runs read the source state, so neither sees the
/// other's edit, and the runner has to reject the combination rather than pick one.
#[test]
fn chained_anchors_conflict_on_a_shared_slot() {
let mut fixture = Fixture::new(&ExtractXyToSplit);
let upstream = fixture.add(decl!("vector_nodes::extract_xy"@1), vec![literal(Tagged::Number(0.)), literal(Tagged::XY(Axis::Y))]);
fixture.add(decl!("vector_nodes::extract_xy"@1), vec![literal(Tagged::Number(0.)), wire(upstream, 0)]);
let error = fixture.migrate(&ExtractXyToSplit).unwrap_err();
assert!(matches!(error, RunnerError::ConflictingSlot(_)), "{error}");
}
@@ -1,195 +0,0 @@
//! What `#[migration]` and `rename!` generate and register, and how the runner orders and chains the registry.
use crate::examples::{ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use document_graph_storage::{Delta, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, RegistryDelta, Session, UserId};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, MigrationError, NodeMigration, Region, decl, literal, registered_migrations};
use migration_runner::testing::replay;
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
#[test]
fn every_migration_registers_once() {
let mut sources: Vec<Declaration> = registered_migrations().iter().map(|migration| migration.source()).collect();
sources.sort();
let mut expected = vec![
decl!("blending_nodes::opacity"@1),
decl!("graphene_core::ops::AddNode"@1),
decl!("math_nodes::multiply"@1),
decl!("transform_nodes::transform"@1),
decl!("vector_nodes::angle_between"@1),
decl!("vector_nodes::extract_xy"@1),
decl!("vector_nodes::split_vec2"@2),
];
expected.sort();
assert_eq!(sources, expected);
}
#[test]
fn generated_migrations_describe_their_parameters() {
assert_eq!(TransformDegrees.target(), decl!("transform_nodes::transform"@2));
assert_eq!(TransformDegrees.pins(), &[decl!("math_nodes::multiply"@1)]);
assert_eq!(TransformDegrees.footprint(), Region::ANCHOR.union(Region::INPUTS).union(Region::UPSTREAM));
assert_eq!(ExtractXyToSplit.target(), decl!("vector_nodes::split_vec2"@2));
assert_eq!(ExtractXyToSplit.pins(), &[decl!("logic_nodes::select_axis"@1)]);
assert!(OpacityToggles.pins().is_empty());
assert_eq!(OpacityToggles.footprint(), Region::ANCHOR.union(Region::INPUTS));
}
fn position(ordered: &[&'static dyn NodeMigration], source: Declaration) -> usize {
ordered.iter().position(|migration| migration.source() == source).unwrap_or_else(|| panic!("{source} is not ordered"))
}
#[test]
fn order_follows_chains_and_pins() {
let ordered = order_migrations(&registered_migrations()).unwrap();
// Transform inserts `multiply@1`, so it must run before `multiply@1` is renamed
assert!(position(&ordered, decl!("transform_nodes::transform"@1)) < position(&ordered, decl!("math_nodes::multiply"@1)));
// Extract XY produces `split_vec2@2`, which the next step in its lineage consumes
assert!(position(&ordered, decl!("vector_nodes::extract_xy"@1)) < position(&ordered, decl!("vector_nodes::split_vec2"@2)));
}
#[test]
fn order_ignores_registration_order() {
let mut reversed = registered_migrations();
reversed.reverse();
let sources = |ordered: Vec<&'static dyn NodeMigration>| ordered.iter().map(|migration| migration.source()).collect::<Vec<_>>();
assert_eq!(sources(order_migrations(&registered_migrations()).unwrap()), sources(order_migrations(&reversed).unwrap()));
}
/// A migration that changes nothing, for ordering cases the examples don't cover.
struct Step {
source: Declaration,
target: Declaration,
pins: &'static [Declaration],
}
impl NodeMigration for Step {
fn source(&self) -> Declaration {
self.source
}
fn target(&self) -> Declaration {
self.target
}
fn pins(&self) -> &'static [Declaration] {
self.pins
}
fn footprint(&self) -> Region {
Region::ANCHOR
}
fn run(&self, _context: &AnchorContext) -> Result<Edits, MigrationError> {
Ok(Edits::default())
}
}
#[test]
fn pins_that_depend_on_each_other_are_a_cycle() {
// Each inserts the other's target, so each must run after the other
static FIRST: Step = Step {
source: decl!("a"@1),
target: decl!("a"@2),
pins: &[decl!("b"@2)],
};
static SECOND: Step = Step {
source: decl!("b"@1),
target: decl!("b"@2),
pins: &[decl!("a"@2)],
};
let error = order_migrations(&[&FIRST, &SECOND]).err().expect("a cycle can't be ordered");
assert!(matches!(error, RunnerError::OrderCycle(_)), "{error}");
}
#[test]
fn order_rejects_two_migrations_from_one_declaration() {
static FIRST: Step = Step {
source: decl!("a"@1),
target: decl!("a"@2),
pins: &[],
};
static SECOND: Step = Step {
source: decl!("a"@1),
target: decl!("b"@2),
pins: &[],
};
let error = order_migrations(&[&FIRST, &SECOND]).err().expect("two migrations from one declaration are ambiguous");
assert!(matches!(error, RunnerError::DuplicateMigration(_)), "{error}");
}
#[test]
fn order_rejects_a_step_skipping_versions() {
static SKIP: Step = Step {
source: decl!("a"@1),
target: decl!("a"@3),
pins: &[],
};
let error = order_migrations(&[&SKIP]).err().expect("a migration steps exactly one version");
assert!(matches!(error, RunnerError::InvalidStep { .. }), "{error}");
}
/// Every registered migration over one history: the transform inserts `multiply@1`, which the later rename turns into `product@2`.
#[test]
fn migrate_history_chains_every_pending_migration() {
let mut table = DeclarationTable::new([decl!("math_nodes::add"@1)]);
for migration in registered_migrations() {
table.register_migration(migration);
}
let mut session = Session::with_identity(PeerId(1), UserId(1));
let mut commit = |op: RegistryDelta| {
session.stage_computed_ops(vec![op]).unwrap();
session.retire_all().unwrap();
};
let node = |declaration: Declaration, inputs: Vec<NodeInput>| {
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(DeclarationTable::resource_id(declaration)), inputs.len());
for (slot, input) in node.inputs_mut().iter_mut().zip(inputs) {
slot.input = input;
}
node
};
let (angle, transform, rename_only) = (NodeId(1), NodeId(2), NodeId(3));
commit(RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
});
commit(RegistryDelta::AddNode {
id: angle,
node: node(decl!("math_nodes::add"@1), vec![]),
});
commit(RegistryDelta::AddNode {
id: transform,
node: node(
decl!("transform_nodes::transform"@1),
vec![literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), NodeInput::Node { id: angle, index: 0 }],
),
});
commit(RegistryDelta::AddNode {
id: rename_only,
node: node(decl!("math_nodes::multiply"@1), vec![]),
});
let history: Vec<Delta> = session.history().cloned().collect();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table).unwrap();
let registry = replay(&migrated.deltas);
let declaration_of = |id: NodeId| match registry.node_instances[&id].implementation() {
Implementation::ProtoNode(resource) => table.declaration(*resource),
Implementation::Network(_) => None,
};
assert_eq!(declaration_of(transform), Some(decl!("transform_nodes::transform"@2)));
assert_eq!(declaration_of(rename_only), Some(decl!("math_nodes::product"@2)));
let NodeInput::Node { id: converter, .. } = registry.node_instances[&transform].inputs()[ROTATION as usize].input else {
panic!("rotation stays wired")
};
assert_eq!(declaration_of(converter), Some(decl!("math_nodes::product"@2)));
// Every original delta maps into the rewritten history
assert!(history.iter().all(|delta| migrated.revs[&delta.id].is_some()));
}
@@ -1,47 +0,0 @@
//! The history properties of `migration_runner::testing` on the examples.
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use migration_core::{decl, literal};
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
fn numbers(input_count: usize) -> SourceContract {
SourceContract::new(input_count, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
#[test]
fn rename_commutes() {
check_commutation(registered(decl!("graphene_core::ops::AddNode"@1)), &numbers(2));
}
#[test]
fn opacity_toggles_commute() {
check_commutation(&OpacityToggles, &numbers(2));
}
#[test]
fn transform_degrees_commutes() {
check_commutation(&TransformDegrees, &numbers(3));
}
#[test]
fn angle_between_degrees_commutes() {
check_commutation(&AngleBetweenDegrees, &numbers(2));
}
#[test]
fn extract_xy_to_split_commutes() {
let contract = SourceContract {
// The axis only accepts what produces an axis, which no extract XY output does
reads_own_output: |slot| slot != 1,
..SourceContract::new(2, |random: &mut Random, slot| match slot {
1 => literal(Tagged::XY(random.pick(&[Axis::X, Axis::Y]))),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
};
check_commutation(&ExtractXyToSplit, &contract);
}
#[test]
fn undo_through_rewritten_history_matches_migrated_undo() {
check_undo(&TransformDegrees, &numbers(3));
}
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "migration-snapshot"
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
authors.workspace = true
publish = false
[dependencies]
syn = { workspace = true }
proc-macro2 = { workspace = true }
quote = { workspace = true }
convert_case = { workspace = true }
-152
View File
@@ -1,152 +0,0 @@
//! Compares every node's API against a baseline commit, to find changes that need a version bump or a migration.
use crate::lineage::{MigrationStep, find_migrations};
use crate::nodes::{NodeSource, find_nodes};
use crate::scaffold::{MIGRATIONS, NODE_CRATES};
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
/// Fail if the nodes at the git ref `baseline` differ from the working tree's in a way documents would notice.
pub fn check_against(workspace: &Path, baseline: &str) -> Result<(), String> {
let current = find_nodes(&workspace.join(NODE_CRATES))?;
let migrations = find_migrations(&workspace.join(MIGRATIONS))?;
let directory = std::env::temp_dir().join(format!("migration-api-baseline-{}", std::process::id()));
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?;
let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() {
return Err(problems.join("\n"));
}
println!("No node API changed without a version bump since {baseline} ({} nodes)", baseline_nodes.len());
Ok(())
}
fn extract_baseline(workspace: &Path, baseline: &str, directory: &Path) -> Result<(), String> {
std::fs::create_dir_all(directory).map_err(|error| format!("{}: {error}", directory.display()))?;
let mut archive = Command::new("git")
.args(["archive", baseline, NODE_CRATES])
.current_dir(workspace)
.stdout(Stdio::piped())
.spawn()
.map_err(|error| format!("running git: {error}"))?;
let Some(tar_input) = archive.stdout.take() else {
return Err("git archive has no output".to_string());
};
let extracted = Command::new("tar")
.args(["-x", "-C"])
.arg(directory)
.stdin(tar_input)
.status()
.map_err(|error| format!("running tar: {error}"))?;
let archived = archive.wait().map_err(|error| format!("running git: {error}"))?;
if !archived.success() || !extracted.success() {
return Err(format!("could not read `{NODE_CRATES}` at the git ref `{baseline}`"));
}
Ok(())
}
/// Why `current` needs a version bump or a migration that it doesn't have, given the nodes at the baseline.
fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[MigrationStep]) -> Vec<String> {
let current_by_identifier: HashMap<&str, &NodeSource> = current.iter().map(|node| (node.identifier.as_str(), node)).collect();
let baseline_identifiers: Vec<&str> = baseline.iter().map(|node| node.identifier.as_str()).collect();
let mut problems = Vec::new();
for old in baseline {
let identifier = &old.identifier;
let version = old.version;
let Some(new) = current_by_identifier.get(identifier.as_str()) else {
if migrations.iter().any(|step| step.source == (identifier.clone(), version)) {
continue;
}
// Moving a module keeps the function and its API, which is what a rename looks like
let moved = current
.iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved {
Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
new.identifier,
version + 1,
new.identifier
),
None => format!("`{identifier}`@{version} disappeared without a migration. Run `cargo run migration new {identifier}@{version} <replacing node>`"),
});
continue;
};
if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
} else if new.version == version && new.signature != old.signature {
problems.push(format!(
"`{identifier}` changed its API without a version bump. Set `version({})` on it in {} and run `cargo run migration new`\n was: {}\n now: {}",
version + 1,
new.file.display(),
old.signature,
new.signature
));
}
}
problems
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn node(identifier: &str, version: u32, signature: &str) -> NodeSource {
NodeSource {
identifier: identifier.to_string(),
version,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"),
signature: signature.to_string(),
}
}
#[test]
fn unchanged_nodes_and_bumped_ones_pass() {
let baseline = [node("a::b", 1, "(x: f64)"), node("a::c", 1, "(x: f64)")];
let current = [node("a::b", 1, "(x: f64)"), node("a::c", 2, "(x: f64, y: f64)")];
assert!(api_problems(&baseline, &current, &[]).is_empty());
}
#[test]
fn a_changed_api_needs_a_bump() {
let problems = api_problems(&[node("a::b", 1, "(x: f64)")], &[node("a::b", 1, "(x: f64, y: f64)")], &[]);
assert_eq!(problems.len(), 1);
assert!(problems[0].contains("Set `version(2)`"), "{}", problems[0]);
}
#[test]
fn a_moved_node_suggests_a_rename_until_it_has_a_migration() {
let baseline = [node("old::b", 3, "(x: f64)")];
let current = [node("new::b", 3, "(x: f64)")];
let problems = api_problems(&baseline, &current, &[]);
assert!(problems[0].contains("rename old::b@3 new::b"), "{}", problems[0]);
let migrations = [MigrationStep {
source: ("old::b".to_string(), 3),
target: ("new::b".to_string(), 4),
}];
assert!(api_problems(&baseline, &current, &migrations).is_empty());
}
#[test]
fn a_removed_node_needs_a_migration() {
let problems = api_problems(&[node("a::gone", 1, "(x: f64)")], &[], &[]);
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
}
}
-132
View File
@@ -1,132 +0,0 @@
//! Checks that every node version bump has a migration leading to it, and that every migration leads somewhere.
use std::collections::BTreeSet;
use std::path::Path;
use syn::parse::{Parse, ParseStream};
/// `identifier@version`.
pub type Declaration = (String, u32);
/// The source and target of one migration in `migration-nodes`.
pub struct MigrationStep {
pub source: Declaration,
pub target: Declaration,
}
/// `"id"@1 => @2` or `"id"@1 => "other"@2`, as `#[migration]` and `rename!` take it.
impl Parse for MigrationStep {
fn parse(input: ParseStream) -> syn::Result<Self> {
let identifier: syn::LitStr = input.parse()?;
input.parse::<syn::Token![@]>()?;
let version: syn::LitInt = input.parse()?;
input.parse::<syn::Token![=>]>()?;
let target_identifier = if input.peek(syn::LitStr) { input.parse::<syn::LitStr>()?.value() } else { identifier.value() };
input.parse::<syn::Token![@]>()?;
let target_version: syn::LitInt = input.parse()?;
Ok(Self {
source: (identifier.value(), version.base10_parse()?),
target: (target_identifier, target_version.base10_parse()?),
})
}
}
/// Every migration step under `directory`, from `#[migration(...)]` functions and `rename!(...)` calls.
pub fn find_migrations(directory: &Path) -> Result<Vec<MigrationStep>, String> {
let mut steps = Vec::new();
let Ok(entries) = std::fs::read_dir(directory) else { return Ok(steps) };
for path in entries.filter_map(Result::ok).map(|entry| entry.path()) {
if path.is_dir() {
steps.extend(find_migrations(&path)?);
continue;
}
if path.extension().is_none_or(|extension| extension != "rs") {
continue;
}
let source = std::fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display()))?;
let parsed = syn::parse_file(&source).map_err(|error| format!("{}: {error}", path.display()))?;
for item in parsed.items {
let step = match item {
syn::Item::Fn(function) => match function.attrs.iter().find(|attribute| attribute.path().is_ident("migration")) {
Some(attribute) => attribute.parse_args::<MigrationStep>(),
None => continue,
},
syn::Item::Macro(call) if call.mac.path.is_ident("rename") => call.mac.parse_body::<MigrationStep>(),
_ => continue,
};
steps.push(step.map_err(|error| format!("{}: {error}", path.display()))?);
}
}
Ok(steps)
}
/// Problems with how `nodes` (current declarations) and `migrations` connect, empty when every lineage is whole.
pub fn lineage_problems(nodes: &[Declaration], migrations: &[MigrationStep]) -> Vec<String> {
let targets: BTreeSet<&Declaration> = migrations.iter().map(|step| &step.target).collect();
let sources: BTreeSet<&Declaration> = migrations.iter().map(|step| &step.source).collect();
let current: BTreeSet<&Declaration> = nodes.iter().collect();
let mut problems = Vec::new();
for node in nodes {
let (identifier, version) = node;
if *version > 1 && !targets.contains(node) {
problems.push(format!("`{identifier}` is at version {version}, but no migration leads to it. Run `cargo run migration new`"));
}
}
// A target is a current declaration, or a step on the way to one
for step in migrations {
if !current.contains(&step.target) && !sources.contains(&step.target) {
let ((source, from), (target, to)) = (&step.source, &step.target);
problems.push(format!(
"the migration from `{source}`@{from} leads to `{target}`@{to}, which no node declares and no migration continues from"
));
}
}
problems
}
#[cfg(test)]
mod tests {
use super::*;
fn declaration(identifier: &str, version: u32) -> Declaration {
(identifier.to_string(), version)
}
fn step(source: Declaration, target: Declaration) -> MigrationStep {
MigrationStep { source, target }
}
#[test]
fn parses_steps_and_replacements() {
let version_step: MigrationStep = syn::parse_str(r#""a::B"@1 => @2"#).unwrap();
assert_eq!((version_step.source, version_step.target), (declaration("a::B", 1), declaration("a::B", 2)));
let replacement: MigrationStep = syn::parse_str(r#""a::B"@2 => "c::D"@3"#).unwrap();
assert_eq!((replacement.source, replacement.target), (declaration("a::B", 2), declaration("c::D", 3)));
}
#[test]
fn whole_lineages_pass() {
let nodes = [declaration("a", 1), declaration("b", 3)];
let migrations = [step(declaration("old", 1), declaration("b", 2)), step(declaration("b", 2), declaration("b", 3))];
assert!(lineage_problems(&nodes, &migrations).is_empty());
}
#[test]
fn bumps_need_a_migration_and_migrations_need_a_destination() {
let nodes = [declaration("bumped", 2)];
let migrations = [step(declaration("gone", 1), declaration("nowhere", 2))];
let problems = lineage_problems(&nodes, &migrations);
assert_eq!(problems.len(), 2);
assert!(problems[0].contains("`bumped` is at version 2"));
assert!(problems[1].contains("leads to `nowhere`@2"));
}
}
-249
View File
@@ -1,249 +0,0 @@
//! `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 api;
mod lineage;
mod nodes;
mod plan;
mod scaffold;
mod step;
mod types;
use plan::{Plan, Snapshots};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use step::Step;
use types::Types;
const SCHEMA: &str = "document/graph-storage/src/schema";
const SNAPSHOTS: &str = "document/migrations/formats/src";
const MANIFEST: &str = "document/format/src/manifest.rs";
const SUPPORTED_VERSION_DECLARATION: &str = "pub const SUPPORTED_FORMAT_VERSION: u32 = ";
fn usage() {
println!();
println!("USAGE:");
println!(" cargo run migration <command>");
println!();
println!("<command>:");
println!(" check Fail if the stored types changed since the latest frozen format version, or a node's version");
println!(" has no migration leading to it");
println!(" check --baseline <git ref>");
println!(" Also fail if a node's API changed since that commit without a version bump, or a node disappeared");
println!(" without a migration");
println!(" snapshot Freeze the stored types as the next format version, with the step from the previous one");
println!(" new Scaffold every step missing between a node's newest migration and its current `version(N)`");
println!(" new <identifier>");
println!(" Scaffold the missing steps of one node");
println!(" new <old identifier>@<version> <identifier>");
println!(" Scaffold the migration replacing a removed node by another");
println!(" rename <old identifier>@<version> <identifier>");
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!();
}
fn main() -> ExitCode {
let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");
let workspace = workspace.canonicalize().unwrap_or(workspace);
let arguments: Vec<String> = std::env::args().skip(1).collect();
let result = match arguments.first().map(String::as_str) {
Some("check") => match &arguments[1..] {
[] => check(&workspace),
[flag, baseline] if flag == "--baseline" => check(&workspace).and_then(|()| api::check_against(&workspace, baseline)),
_ => Err("expected `check` or `check --baseline <git ref>`".to_string()),
},
Some("snapshot") => snapshot(&workspace),
Some(command @ ("new" | "rename")) => scaffold::scaffold(&workspace, command, &arguments[1..]),
Some("help" | "--help") => {
usage();
return ExitCode::SUCCESS;
}
_ => {
usage();
return ExitCode::FAILURE;
}
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("Error: {error}");
ExitCode::FAILURE
}
}
}
fn check(workspace: &Path) -> Result<(), String> {
let plan = Plan::new(&Types::read_schema(&workspace.join(SCHEMA))?, &Snapshots::read(&workspace.join(SNAPSHOTS))?);
let Some(latest) = plan.previous else {
return Err("no frozen format version exists yet, run `cargo run migration snapshot`".to_string());
};
if !plan.is_unchanged() {
return Err(format!(
"the stored types changed since format version {latest}:\n{}\nRun `cargo run migration snapshot` to freeze them as version {} with a format step from {latest}",
plan.describe(),
plan.version
));
}
for version in 2..=latest {
let step = workspace.join(SNAPSHOTS).join(step_path(version));
if !step.exists() {
return Err(format!("format version {version} has no step from {} at {}", version - 1, step.display()));
}
}
let supported = supported_version(workspace)?;
if supported != latest {
return Err(format!("`SUPPORTED_FORMAT_VERSION` is {supported}, but the latest frozen format version is {latest}"));
}
println!("The stored types match format version {latest}");
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter()
.map(|node| (node.identifier, node.version))
.collect();
let migrations = lineage::find_migrations(&workspace.join(scaffold::MIGRATIONS))?;
let problems = lineage::lineage_problems(&nodes, &migrations);
if !problems.is_empty() {
return Err(problems.join("\n"));
}
println!("Every node version has a migration leading to it ({} nodes, {} migrations)", nodes.len(), migrations.len());
Ok(())
}
fn snapshot(workspace: &Path) -> Result<(), String> {
let live = Types::read_schema(&workspace.join(SCHEMA))?;
let snapshots_directory = workspace.join(SNAPSHOTS);
let snapshots = Snapshots::read(&snapshots_directory)?;
let plan = Plan::new(&live, &snapshots);
if let Some(latest) = plan.previous
&& plan.is_unchanged()
{
println!("The stored types match format version {latest}, nothing to freeze");
return Ok(());
}
let file = snapshots_directory.join(format!("v{}.rs", plan.version));
std::fs::write(&file, plan.render(&live)).map_err(|error| format!("{}: {error}", file.display()))?;
format(workspace, &file)?;
register_version(&snapshots_directory.join("lib.rs"), plan.version)?;
println!("Froze format version {} into {}", plan.version, file.display());
if let Some(previous) = plan.previous {
let step = Step::new(&plan, previous, &live, &snapshots);
let step_file = snapshots_directory.join(step_path(plan.version));
std::fs::create_dir_all(snapshots_directory.join("steps")).map_err(|error| format!("creating the steps module: {error}"))?;
std::fs::write(&step_file, step.render()).map_err(|error| format!("{}: {error}", step_file.display()))?;
format(workspace, &step_file)?;
register_step(&snapshots_directory.join("steps/mod.rs"), plan.version)?;
set_supported_version(workspace, plan.version)?;
println!("{}", plan.describe());
println!(
"Wrote the format step from {previous} into {}, and set `SUPPORTED_FORMAT_VERSION` to {}",
step_file.display(),
plan.version
);
println!("Finish the conversions of the changed types where the step's `compile_error!`s point");
for name in step.unconverted() {
println!("Warning: `{name}` changed, but format steps don't convert where it's stored");
}
}
Ok(())
}
fn format(workspace: &Path, file: &PathBuf) -> Result<(), String> {
let status = Command::new("rustfmt")
.arg("--edition=2024")
.arg("--config-path")
.arg(workspace.join("rustfmt.toml"))
.arg(file)
.status()
.map_err(|error| format!("running rustfmt: {error}"))?;
if !status.success() {
return Err(format!("rustfmt failed on {}", file.display()));
}
Ok(())
}
/// Declares `v<version>` in the snapshots crate and points `latest` at it.
fn register_version(library: &Path, version: u32) -> Result<(), String> {
let source = std::fs::read_to_string(library).map_err(|error| format!("{}: {error}", library.display()))?;
let module = format!("pub mod v{version};");
let latest = format!("pub use v{version} as latest;");
let mut lines: Vec<String> = source
.lines()
.filter(|line| !(line.starts_with("pub use v") && line.ends_with(" as latest;")))
.map(str::to_string)
.collect();
if !lines.contains(&module) {
let after_modules = lines.iter().rposition(|line| line.starts_with("pub mod v")).map_or(lines.len(), |index| index + 1);
lines.insert(after_modules, module);
}
let after_modules = lines.iter().rposition(|line| line.starts_with("pub mod v")).map_or(lines.len(), |index| index + 1);
lines.insert(after_modules, latest);
std::fs::write(library, lines.join("\n") + "\n").map_err(|error| format!("{}: {error}", library.display()))
}
/// The step into `version`, relative to the snapshots crate's source.
fn step_path(version: u32) -> PathBuf {
PathBuf::from(format!("steps/v{}_to_v{version}.rs", version - 1))
}
/// Declares the step into `version` in the steps module, creating it and declaring it in the crate on the first step.
fn register_step(steps: &Path, version: u32) -> Result<(), String> {
let module = format!("mod v{}_to_v{version};", version - 1);
let source = std::fs::read_to_string(steps).unwrap_or_else(|_| "//! One format step per version, each registering itself.\n\n".to_string());
if !source.lines().any(|line| line == module) {
std::fs::write(steps, format!("{source}{module}\n")).map_err(|error| format!("{}: {error}", steps.display()))?;
}
let Some(directory) = steps.parent().and_then(Path::parent) else { return Ok(()) };
let library = directory.join("lib.rs");
let library_source = std::fs::read_to_string(&library).map_err(|error| format!("{}: {error}", library.display()))?;
if !library_source.lines().any(|line| line == "mod steps;") {
std::fs::write(&library, format!("{library_source}\nmod steps;\n")).map_err(|error| format!("{}: {error}", library.display()))?;
}
Ok(())
}
fn set_supported_version(workspace: &Path, version: u32) -> Result<(), String> {
let manifest = workspace.join(MANIFEST);
let source = std::fs::read_to_string(&manifest).map_err(|error| format!("{}: {error}", manifest.display()))?;
let updated: Vec<String> = source
.lines()
.map(|line| match line.strip_prefix(SUPPORTED_VERSION_DECLARATION) {
Some(_) => format!("{SUPPORTED_VERSION_DECLARATION}{version};"),
None => line.to_string(),
})
.collect();
std::fs::write(&manifest, updated.join("\n") + "\n").map_err(|error| format!("{}: {error}", manifest.display()))
}
fn supported_version(workspace: &Path) -> Result<u32, String> {
let manifest = workspace.join(MANIFEST);
let source = std::fs::read_to_string(&manifest).map_err(|error| format!("{}: {error}", manifest.display()))?;
source
.lines()
.find_map(|line| line.strip_prefix(SUPPORTED_VERSION_DECLARATION))
.and_then(|rest| rest.trim_end_matches(';').parse().ok())
.ok_or_else(|| format!("{}: no `{SUPPORTED_VERSION_DECLARATION}<number>;`", manifest.display()))
}
-151
View File
@@ -1,151 +0,0 @@
//! 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,
/// The parameters and output as written, without their attributes. Comparing it tells whether stored inputs still fit.
pub signature: String,
}
/// 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<Vec<NodeSource>, 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<PathBuf>) -> 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<String, String> {
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<NodeSource>) {
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<NodeSource>) {
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<String> = 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<NodeSource> {
let attribute = function.attrs.iter().find(|attribute| {
let segments: Vec<String> = attribute.path().segments.iter().map(|segment| segment.ident.to_string()).collect();
matches!(segments.iter().map(String::as_str).collect::<Vec<_>>().as_slice(), ["node_macro", "node"] | ["node"])
})?;
let arguments = attribute.parse_args_with(Punctuated::<syn::Meta, syn::Token![,]>::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::<syn::LitInt>(list.tokens.clone())
{
version = literal.base10_parse().ok()?;
}
}
let function_name = function.sig.ident.to_string();
let parameters = function.sig.inputs.iter().map(|parameter| match parameter {
syn::FnArg::Typed(typed) => {
let (pattern, ty) = (&typed.pat, &typed.ty);
quote::quote!(#pattern: #ty).to_string()
}
syn::FnArg::Receiver(receiver) => quote::quote!(#receiver).to_string(),
});
let output = &function.sig.output;
let signature = format!("({}) {}", parameters.collect::<Vec<_>>().join(", "), quote::quote!(#output));
Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version,
function: function_name,
file: file.to_path_buf(),
signature,
})
}
-189
View File
@@ -1,189 +0,0 @@
//! What the next format version must declare again, and the snapshot file that declares it.
use crate::types::{Entry, ImportLeaf, Types, flatten};
use proc_macro2::{TokenStream, TokenTree};
use quote::{ToTokens, format_ident, quote};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
/// Every frozen version, by number.
pub struct Snapshots {
pub versions: BTreeMap<u32, Types>,
}
impl Snapshots {
/// Every `v<N>.rs` in `directory`.
pub fn read(directory: &Path) -> Result<Self, String> {
let mut versions = BTreeMap::new();
for entry in std::fs::read_dir(directory).map_err(|error| format!("{}: {error}", directory.display()))? {
let path = entry.map_err(|error| error.to_string())?.path();
let Some(version) = path
.file_stem()
.and_then(|stem| stem.to_str())
.and_then(|stem| stem.strip_prefix('v'))
.and_then(|number| number.parse().ok())
else {
continue;
};
versions.insert(version, Types::read_snapshot(&path)?);
}
Ok(Self { versions })
}
pub fn latest(&self) -> Option<u32> {
self.versions.keys().next_back().copied()
}
/// `name` as of `version`, following re-exports to the version defining it.
pub fn entry(&self, version: u32, name: &str) -> Option<&Entry> {
let types = self.versions.get(&version)?;
if let Some(entry) = types.entries.get(name) {
return Some(entry);
}
types.reexports.get(name).and_then(|&earlier| self.entry(earlier, name))
}
fn fingerprint(&self, version: u32, name: &str) -> Option<String> {
self.entry(version, name).map(Entry::fingerprint)
}
fn names(&self, version: u32) -> BTreeSet<String> {
let Some(types) = self.versions.get(&version) else { return BTreeSet::new() };
types.entries.keys().chain(types.reexports.keys()).cloned().collect()
}
}
/// How the live schema differs from the latest snapshot.
pub struct Plan {
pub version: u32,
pub previous: Option<u32>,
/// Types whose definition or impls changed, or that are new.
pub changed: BTreeSet<String>,
pub removed: BTreeSet<String>,
/// `changed` plus every type reaching one, which must be declared again to refer to the new definitions.
pub redeclared: BTreeSet<String>,
pub reexported: BTreeSet<String>,
}
impl Plan {
pub fn new(live: &Types, snapshots: &Snapshots) -> Self {
let previous = snapshots.latest();
let changed: BTreeSet<String> = live
.entries
.iter()
.filter(|(name, entry)| previous.and_then(|version| snapshots.fingerprint(version, name)) != Some(entry.fingerprint()))
.map(|(name, _)| name.clone())
.collect();
let live_names: BTreeSet<String> = live.entries.keys().cloned().collect();
let removed = previous.map(|version| snapshots.names(version)).unwrap_or_default().difference(&live_names).cloned().collect();
// Fixpoint over "names a redeclared type", O(types²) per round
let mut redeclared = changed.clone();
loop {
let reaching: Vec<String> = live
.entries
.iter()
.filter(|(name, entry)| !redeclared.contains(*name) && !entry.named_paths().is_disjoint(&redeclared))
.map(|(name, _)| name.clone())
.collect();
if reaching.is_empty() {
break;
}
redeclared.extend(reaching);
}
let reexported = live_names.difference(&redeclared).cloned().collect();
Self {
version: previous.map_or(1, |version| version + 1),
previous,
changed,
removed,
redeclared,
reexported,
}
}
pub fn is_unchanged(&self) -> bool {
self.redeclared.is_empty() && self.removed.is_empty()
}
/// The snapshot file, before rustfmt.
pub fn render(&self, live: &Types) -> String {
let items: Vec<syn::Item> = live.order.iter().filter(|name| self.redeclared.contains(*name)).flat_map(|name| live.entries[name].items()).collect();
let tokens: TokenStream = items.iter().map(ToTokens::to_token_stream).collect();
let reexports = self.previous.filter(|_| !self.reexported.is_empty()).map(|previous| {
let module = format_ident!("v{previous}");
let names = self.reexported.iter().map(|name| format_ident!("{name}"));
quote!(pub use super::#module::{#(#names),*};)
});
let imports = imports(live, &tokens);
let header = format!(
"//! Format version {}, frozen by `cargo run migration snapshot`. Never edit it: old documents decode through these definitions.\n\n",
self.version
);
// Separate items by blank lines, which rustfmt keeps
let items: Vec<String> = items.iter().map(|item| item.to_token_stream().to_string()).collect();
format!("{header}{}\n\n{}\n", quote!(#reexports #imports), items.join("\n\n"))
}
pub fn describe(&self) -> String {
let list = |names: &BTreeSet<String>| names.iter().map(String::as_str).collect::<Vec<_>>().join(", ");
let mut lines = Vec::new();
if !self.changed.is_empty() {
lines.push(format!(" changed: {}", list(&self.changed)));
}
if !self.removed.is_empty() {
lines.push(format!(" removed: {}", list(&self.removed)));
}
let carried: BTreeSet<String> = self.redeclared.difference(&self.changed).cloned().collect();
if !carried.is_empty() {
lines.push(format!(" declared again because they reach a changed type: {}", list(&carried)));
}
lines.join("\n")
}
}
/// The external imports `items` use, grouped by path.
fn imports(live: &Types, items: &TokenStream) -> TokenStream {
let mut used = BTreeSet::new();
collect_idents(items.clone(), &mut used);
let mut leaves: Vec<ImportLeaf> = Vec::new();
for import in &live.imports {
flatten(&import.tree, &mut Vec::new(), &mut leaves);
}
let mut grouped: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for leaf in leaves.into_iter().filter(|leaf| leaf.binding == "*" || used.contains(&leaf.binding)) {
grouped.entry(leaf.prefix.join("::")).or_default().insert(leaf.written);
}
grouped
.into_iter()
.map(|(prefix, names)| {
let names: Vec<String> = names.into_iter().collect();
let source = match names.as_slice() {
[single] => format!("use {prefix}::{single};"),
_ => format!("use {prefix}::{{{}}};", names.join(", ")),
};
source.parse::<TokenStream>().unwrap_or_default()
})
.collect()
}
fn collect_idents(tokens: TokenStream, idents: &mut BTreeSet<String>) {
for token in tokens {
match token {
TokenTree::Ident(ident) => {
idents.insert(ident.to_string());
}
TokenTree::Group(group) => collect_idents(group.stream(), idents),
_ => {}
}
}
}
@@ -1,364 +0,0 @@
//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate.
use crate::lineage::{MigrationStep, find_migrations};
use crate::nodes::{NodeSource, find_nodes};
use convert_case::{Case, Casing};
use std::path::{Path, PathBuf};
pub const NODE_CRATES: &str = "node-graph";
pub const MIGRATIONS: &str = "document/migrations/nodes/src";
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` 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", []) => {
let steps = missing_steps(&nodes, &find_migrations(&migrations)?);
if steps.is_empty() {
println!("Every node version already has a migration leading to it");
return Ok(());
}
write_version_steps(&migrations, &steps)
}
("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 steps = missing_steps(std::slice::from_ref(node), &find_migrations(&migrations)?);
if steps.is_empty() {
return Err(format!("migrations up to `{}`@{} already exist", node.identifier, node.version));
}
write_version_steps(&migrations, &steps)
}
("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)?;
print_step_hint();
Ok(())
}
("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 <identifier>`, `new <old identifier>@<version> <identifier>`, or `rename <old identifier>@<version> <identifier>`".to_string()),
}
}
/// Each `(node, from)` step still missing between the newest version a migration leads the node to (1 if none) and its current version.
fn missing_steps<'a>(nodes: &'a [NodeSource], migrations: &[MigrationStep]) -> Vec<(&'a NodeSource, u32)> {
nodes
.iter()
.flat_map(|node| {
let targets = migrations.iter().filter(|step| step.target.0 == node.identifier).map(|step| step.target.1);
let migrated = targets.filter(|version| *version <= node.version).max().unwrap_or(1);
(migrated..node.version).map(move |from| (node, from))
})
.collect()
}
fn write_version_steps(migrations: &Path, steps: &[(&NodeSource, u32)]) -> Result<(), String> {
for (node, from) in steps {
let source = format!("\"{}\"@{from} => @{}", node.identifier, from + 1);
write_step(migrations, node, &format!("{}_v{from}", node.function), &source, *from)?;
}
print_step_hint();
Ok(())
}
fn print_step_hint() {
println!("Write each migration where its `compile_error!` points, and describe the change in its doc comment");
}
/// 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 `<identifier>@<version>`, 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<PathBuf, String> {
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 migration = name.to_case(Case::Pascal);
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\n\
#[cfg(test)]\n\
mod tests {{\n\
\tuse super::*;\n\
\tuse migration_runner::testing::{{SourceContract, check_commutation, check_undo}};\n\n\
\tfn contract() -> SourceContract {{\n\
\t\tSourceContract::new(compile_error!(\"How many inputs version {from} stores\"), |random, slot| compile_error!(\"A literal version {from} allows in `slot`, made with `migration_core::literal`\"))\n\
\t}}\n\n\
\t#[test]\n\
\tfn rewrites_history() {{\n\
\t\tcheck_commutation(&{migration}, &contract());\n\
\t\tcheck_undo(&{migration}, &contract());\n\
\t}}\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());
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 <module>;` 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<String> = source.lines().map(str::to_string).collect();
let mut declarations: Vec<String> = 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<String> {
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 exist"), "{again}");
}
#[test]
fn new_without_a_node_scaffolds_every_missing_step() {
let workspace = Workspace::new("all");
std::fs::create_dir_all(workspace.0.join(MIGRATIONS).join("legacy")).unwrap();
std::fs::write(
workspace.0.join(MIGRATIONS).join("legacy/brighten_v1.rs"),
"#[migration(\"legacy::adjust::BrightenNode\"@1 => @2)]\npub fn brighten_v1(inputs: &mut Inputs) {}\n",
)
.unwrap();
scaffold(&workspace.0, "new", &[]).unwrap();
assert!(workspace.read("blending_nodes/opacity_v1.rs").contains("\"blending_nodes::OpacityNode\"@1 => @2"));
assert!(workspace.read("legacy/brighten_v2.rs").contains("\"legacy::adjust::BrightenNode\"@2 => @3"));
assert!(!workspace.0.join(MIGRATIONS).join("blending_nodes/blend_v1.rs").exists());
let found = find_migrations(&workspace.0.join(MIGRATIONS)).unwrap();
let nodes = find_nodes(&workspace.0.join(NODE_CRATES)).unwrap();
assert!(missing_steps(&nodes, &found).is_empty());
}
#[test]
fn new_with_a_node_scaffolds_each_skipped_version() {
let workspace = Workspace::new("skipped");
scaffold(&workspace.0, "new", &arguments(&["brighten"])).unwrap();
assert!(workspace.read("legacy/brighten_v1.rs").contains("@1 => @2"));
assert!(workspace.read("legacy/brighten_v2.rs").contains("@2 => @3"));
}
#[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}");
}
}
-448
View File
@@ -1,448 +0,0 @@
//! 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 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, }")));
}
}
-396
View File
@@ -1,396 +0,0 @@
//! Reads stored type definitions, from the live schema module or a frozen snapshot, into one normalized form.
use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
use quote::ToTokens;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use syn::visit::Visit;
use syn::visit_mut::VisitMut;
/// Types a stored field may name without being part of the schema. Their encoding is owned by std or serde, or, for the
/// resource IDs, promised never to change.
const EXTERNAL_TYPES: &[&str] = &[
"bool",
"char",
"str",
"u8",
"u16",
"u32",
"u64",
"u128",
"usize",
"i8",
"i16",
"i32",
"i64",
"i128",
"isize",
"f32",
"f64",
"String",
"Vec",
"Option",
"Box",
"Cow",
"HashMap",
"BTreeMap",
"HashSet",
"BTreeSet",
"NonZeroU128",
"ResourceId",
"ResourceHash",
];
/// One stored type: its definition and the impls on it.
pub struct Entry {
pub definition: syn::Item,
pub impls: Vec<syn::ItemImpl>,
}
impl Entry {
/// Normalized tokens, equal exactly when the definition and its impls are. Trailing commas don't count, since rustfmt
/// drops them when a snapshot's doc-less definitions fit on one line.
pub fn fingerprint(&self) -> String {
let text = |item: &dyn ToTokens| strip_trailing_commas(item.to_token_stream()).to_string();
let mut impls: Vec<String> = self.impls.iter().map(|implementation| text(implementation)).collect();
impls.sort();
format!("{} {}", text(&self.definition), impls.join(" "))
}
pub fn items(&self) -> impl Iterator<Item = syn::Item> + '_ {
std::iter::once(self.definition.clone()).chain(self.impls.iter().cloned().map(syn::Item::Impl))
}
/// Every identifier a path in the definition or its impls names.
pub fn named_paths(&self) -> BTreeSet<String> {
let mut collector = PathIdents::default();
collector.visit_item(&self.definition);
for implementation in &self.impls {
collector.visit_item_impl(implementation);
}
collector.idents
}
/// The types the stored fields name, without the definition's own generic parameters.
fn stored_types(&self) -> BTreeSet<String> {
let mut collector = StoredTypes::default();
let generics = match &self.definition {
syn::Item::Struct(definition) => {
collector.visit_fields(&definition.fields);
&definition.generics
}
syn::Item::Enum(definition) => {
for variant in &definition.variants {
collector.visit_fields(&variant.fields);
}
&definition.generics
}
syn::Item::Type(definition) => {
collector.visit_type(&definition.ty);
&definition.generics
}
_ => return BTreeSet::new(),
};
let parameters: BTreeSet<String> = generics.type_params().map(|parameter| parameter.ident.to_string()).collect();
collector.idents.difference(&parameters).cloned().collect()
}
}
/// The stored types of one module, in source order, with the imports their definitions use.
#[derive(Default)]
pub struct Types {
pub entries: BTreeMap<String, Entry>,
pub order: Vec<String>,
pub imports: Vec<syn::ItemUse>,
/// Names a snapshot re-exports from an earlier version, and which.
pub reexports: BTreeMap<String, u32>,
}
impl Types {
/// Every `.rs` file of the live schema module, except its `mod.rs`.
pub fn read_schema(directory: &Path) -> Result<Self, String> {
let mut files: Vec<_> = std::fs::read_dir(directory)
.map_err(|error| format!("{}: {error}", directory.display()))?
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path.extension().is_some_and(|extension| extension == "rs") && path.file_name().is_some_and(|name| name != "mod.rs"))
.collect();
files.sort();
let mut types = Self::default();
for file in files {
types.read_file(&file)?;
}
types.check_stored_types()?;
Ok(types)
}
/// One frozen snapshot file.
pub fn read_snapshot(file: &Path) -> Result<Self, String> {
let mut types = Self::default();
types.read_file(file)?;
Ok(types)
}
fn read_file(&mut self, file: &Path) -> Result<(), String> {
let source = std::fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?;
let parsed = syn::parse_file(&source).map_err(|error| format!("{}: {error}", file.display()))?;
// Impls attach to definitions, which may come later in the file
let mut impls = Vec::new();
for item in parsed.items {
let item = normalize(item).map_err(|error| format!("{}: {error}", file.display()))?;
match item {
syn::Item::Use(import) => self.read_import(import),
syn::Item::Struct(syn::ItemStruct { ref ident, .. }) | syn::Item::Enum(syn::ItemEnum { ref ident, .. }) | syn::Item::Type(syn::ItemType { ref ident, .. }) => {
let name = ident.to_string();
if self.entries.contains_key(&name) {
return Err(format!("{}: `{name}` is defined twice", file.display()));
}
self.order.push(name.clone());
self.entries.insert(name, Entry { definition: item, impls: Vec::new() });
}
syn::Item::Impl(implementation) => impls.push(implementation),
other => {
let kind = other.to_token_stream().into_iter().next().map(|token| token.to_string()).unwrap_or_default();
return Err(format!("{}: `{kind}` item: the schema holds type definitions, their impls, and imports only", file.display()));
}
}
}
for implementation in impls {
let Some(name) = self_type_name(&implementation) else {
return Err(format!("{}: an impl on a type that isn't a plain path", file.display()));
};
let Some(entry) = self.entries.get_mut(&name) else {
return Err(format!("{}: impl on `{name}`, which the schema doesn't define", file.display()));
};
entry.impls.push(implementation);
}
Ok(())
}
/// Keeps external imports, records a snapshot's re-exports, and drops imports of sibling schema modules.
fn read_import(&mut self, import: syn::ItemUse) {
let syn::UseTree::Path(root) = &import.tree else {
self.imports.push(import);
return;
};
let root_name = root.ident.to_string();
if root_name == "super"
&& let syn::UseTree::Path(version) = &*root.tree
&& let Some(version_number) = version.ident.to_string().strip_prefix('v').and_then(|number| number.parse().ok())
{
let mut leaves = Vec::new();
flatten(&version.tree, &mut Vec::new(), &mut leaves);
for leaf in leaves {
self.reexports.insert(leaf.binding, version_number);
}
return;
}
if matches!(root_name.as_str(), "super" | "crate" | "self") {
return;
}
self.imports.push(import);
}
/// Every type a stored field names must be frozen with the schema, or have an encoding nobody here can change.
fn check_stored_types(&self) -> Result<(), String> {
for (name, entry) in &self.entries {
for stored in entry.stored_types() {
if !self.entries.contains_key(&stored) && !EXTERNAL_TYPES.contains(&stored.as_str()) {
return Err(format!("`{name}` stores `{stored}`, which is defined outside the schema module"));
}
}
}
Ok(())
}
}
/// One imported name: the path leading to it, the name as written (with any rename), and what it binds.
pub struct ImportLeaf {
pub prefix: Vec<String>,
pub written: String,
pub binding: String,
}
pub fn flatten(tree: &syn::UseTree, prefix: &mut Vec<String>, leaves: &mut Vec<ImportLeaf>) {
match tree {
syn::UseTree::Path(path) => {
prefix.push(path.ident.to_string());
flatten(&path.tree, prefix, leaves);
prefix.pop();
}
syn::UseTree::Name(name) => {
let written = name.ident.to_string();
let binding = if written == "self" { prefix.last().cloned().unwrap_or_default() } else { written.clone() };
leaves.push(ImportLeaf {
prefix: prefix.clone(),
written,
binding,
});
}
syn::UseTree::Rename(rename) => leaves.push(ImportLeaf {
prefix: prefix.clone(),
written: format!("{} as {}", rename.ident, rename.rename),
binding: rename.rename.to_string(),
}),
syn::UseTree::Glob(_) => leaves.push(ImportLeaf {
prefix: prefix.clone(),
written: "*".to_string(),
binding: "*".to_string(),
}),
syn::UseTree::Group(group) => {
for tree in &group.items {
flatten(tree, prefix, leaves);
}
}
}
}
fn self_type_name(implementation: &syn::ItemImpl) -> Option<String> {
let syn::Type::Path(path) = &*implementation.self_ty else { return None };
path.path.segments.last().map(|segment| segment.ident.to_string())
}
/// Strips docs, makes every definition and field public, and resolves paths into the schema to bare names, so the live
/// module and a frozen snapshot of it read the same.
fn normalize(item: syn::Item) -> Result<syn::Item, String> {
let tokens = strip_docs(item.to_token_stream());
let mut item: syn::Item = syn::parse2(tokens).map_err(|error| error.to_string())?;
SchemaPaths.visit_item_mut(&mut item);
let public = || syn::parse_quote!(pub);
match &mut item {
syn::Item::Struct(definition) => {
definition.vis = public();
for field in definition.fields.iter_mut() {
field.vis = public();
}
}
syn::Item::Enum(definition) => definition.vis = public(),
syn::Item::Type(definition) => definition.vis = public(),
syn::Item::Impl(implementation) if implementation.trait_.is_none() => {
for member in &mut implementation.items {
match member {
syn::ImplItem::Fn(function) => function.vis = public(),
syn::ImplItem::Const(constant) => constant.vis = public(),
_ => {}
}
}
}
_ => {}
}
Ok(item)
}
/// Removes `#[doc = ...]` attributes at any depth. Doc edits never change the format.
fn strip_docs(tokens: TokenStream) -> TokenStream {
let mut output = Vec::new();
let mut tokens = tokens.into_iter().peekable();
while let Some(token) = tokens.next() {
if let TokenTree::Punct(punct) = &token
&& punct.as_char() == '#'
&& let Some(TokenTree::Group(group)) = tokens.peek()
&& is_doc_attribute(group)
{
tokens.next();
continue;
}
match token {
TokenTree::Group(group) => {
let mut stripped = Group::new(group.delimiter(), strip_docs(group.stream()));
stripped.set_span(group.span());
output.push(TokenTree::Group(stripped));
}
other => output.push(other),
}
}
output.into_iter().collect()
}
fn strip_trailing_commas(tokens: TokenStream) -> TokenStream {
let mut output: Vec<TokenTree> = tokens
.into_iter()
.map(|token| match token {
TokenTree::Group(group) => {
let mut stripped = Group::new(group.delimiter(), strip_trailing_commas(group.stream()));
stripped.set_span(group.span());
TokenTree::Group(stripped)
}
other => other,
})
.collect();
if matches!(output.last(), Some(TokenTree::Punct(punct)) if punct.as_char() == ',') {
output.pop();
}
output.into_iter().collect()
}
fn is_doc_attribute(group: &Group) -> bool {
group.delimiter() == Delimiter::Bracket && matches!(group.stream().into_iter().next(), Some(TokenTree::Ident(ident)) if ident == "doc")
}
/// Turns `crate::Node`, `super::model::Node` and the like into `Node`. Schema types are capitalized and modules aren't, so
/// leading `crate`, `super`, and lowercase segments go.
struct SchemaPaths;
impl VisitMut for SchemaPaths {
fn visit_path_mut(&mut self, path: &mut syn::Path) {
let starts_in_crate = path.leading_colon.is_none() && path.segments.first().is_some_and(|segment| segment.ident == "crate" || segment.ident == "super");
if starts_in_crate {
let kept: Vec<_> = path
.segments
.iter()
.skip_while(|segment| segment.ident == "crate" || segment.ident == "super" || segment.ident.to_string().starts_with(|character: char| character.is_lowercase()))
.cloned()
.collect();
if !kept.is_empty() {
path.segments = kept.into_iter().collect();
}
}
syn::visit_mut::visit_path_mut(self, path);
}
}
#[derive(Default)]
struct PathIdents {
idents: BTreeSet<String>,
}
impl<'ast> Visit<'ast> for PathIdents {
fn visit_path(&mut self, path: &'ast syn::Path) {
self.idents.extend(path.segments.iter().map(|segment| segment.ident.to_string()));
syn::visit::visit_path(self, path);
}
}
/// The last segment of every type path in the visited fields, generic arguments included.
#[derive(Default)]
struct StoredTypes {
idents: BTreeSet<String>,
}
impl<'ast> Visit<'ast> for StoredTypes {
fn visit_type_path(&mut self, path: &'ast syn::TypePath) {
if let Some(segment) = path.path.segments.last() {
self.idents.insert(segment.ident.to_string());
}
syn::visit::visit_type_path(self, path);
}
// Field attributes like `#[serde(default)]` name no stored types
fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
}
+1 -3
View File
@@ -22,9 +22,7 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
# Local dependencies
graphite-proc-macros = { workspace = true }
graph-craft = { workspace = true }
document-format = { workspace = true, features = ["migrations"] }
migration-formats = { workspace = true }
migration-nodes = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
graphene-hash = { workspace = true }
-4
View File
@@ -23,7 +23,3 @@ pub mod utility_traits;
pub mod utility_types;
pub use document_container::store as document_store;
// Referenced so the linker keeps their self-registering migrations, which run as documents open
use migration_formats as _;
use migration_nodes as _;
@@ -197,7 +197,7 @@ mod tests {
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{file_type:?} should read back: {error}"));
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
// Only JPG lacks transparency, so it lands on white
@@ -623,13 +623,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
@@ -1179,7 +1179,7 @@ impl OverlayContextInternal {
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false).unwrap_or_default();
(text_size, text_list)
});
let text_width = text_size.x;
@@ -3447,6 +3447,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
}
// Load Image's URL is empty until set, it used to be `graphite:null`
if reference == DefinitionIdentifier::Network("Load Image".into())
&& let Some(url) = node.inputs.get(1)
&& matches!(url.as_value(), Some(TaggedValue::String(url)) if url == "graphite:null")
{
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 1),
NodeInput::value(TaggedValue::String(String::new()), url.is_exposed()),
network_path,
);
}
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
for (i, input) in node.inputs.iter().enumerate() {
if let NodeInput::Scope(name) = input
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more