Compare commits

..
Author SHA1 Message Date
Dennis Kobert 9a9c44ac98 Convert the changing-seasons demo again from its reworked file 2026-10-30 12:59:43 +00:00
Dennis Kobert f7e592c255 Migrate the Mix node to Mix Colors 2026-10-30 12:53:26 +00:00
Dennis Kobert e66eadcb84 Check the regression corpus in CI 2026-10-30 12:46:44 +00:00
Dennis Kobert 48ec336287 Add a contributor guide to writing document migrations 2026-10-30 12:46:44 +00:00
Dennis Kobert bb446b58b6 Run the migration checks and tests in CI 2026-10-30 12:46:44 +00:00
Dennis Kobert 76a91d8ff2 Convert the demo artwork again from the rebased code 2026-10-30 12:46:44 +00:00
Dennis Kobert b015150036 Add init, ingest, and upgrade --check to the regression tool 2026-10-30 12:46:44 +00:00
Dennis Kobert 6aecaf38e9 Compare node APIs against a baseline commit in migration check 2026-10-30 12:46:44 +00:00
Dennis Kobert b1d15ce587 Share migration test fixtures and history properties through migration_runner::testing 2026-10-30 12:46:43 +00:00
Dennis Kobert 18a089cf2a Migrate documents as the editor opens them 2026-10-30 12:46:43 +00:00
Dennis Kobert 82f2a76dc9 Frame regression references to the artwork bounds 2026-10-30 12:46:43 +00:00
Dennis Kobert be575d2519 Add .gdd versions of the demo artwork 2026-10-30 12:46:43 +00:00
Dennis Kobert b3ffdffbcb Open documents through migrations in the CLI and add a regression tool 2026-10-30 12:46:43 +00:00
Dennis Kobert f36ee54ccd Run format steps and node migrations when a document opens 2026-10-30 12:44:54 +00:00
Dennis Kobert 3b41d76fbd Scaffold every missing node migration step with a bare migration new 2026-10-30 12:44:54 +00:00
Dennis Kobert b08b81add2 Check that every node version bump has a migration 2026-10-30 12:44:54 +00:00
Dennis Kobert 42456f00a7 Scaffold node migrations from node versions in source 2026-10-30 12:44:54 +00:00
Dennis Kobert 2b63527478 Generate self-registering format steps with each frozen version 2026-10-30 12:44:54 +00:00
Dennis Kobert d1a58b42f1 Freeze stored document types per format version 2026-10-30 12:44:54 +00:00
Dennis Kobert 4aed212796 Add #[migration] and rename! with self-registration and ordering 2026-10-30 12:43:53 +00:00
Dennis Kobert dae6a293e6 Prototype node migrations with history rewrite 2026-10-30 12:43:52 +00:00
Dennis Kobert af393b1aae Update migration rfc 2026-10-30 12:43:41 +00:00
Dennis Kobert 339b9ae8e7 WIP prototype migrations 2026-10-30 12:43:41 +00:00
Dennis Kobert 82c08464d1 Frame CLI exports to the artwork bounds (#4860)
* Frame CLI exports to the artwork bounds

* Include strokes in the bounds CLI exports frame to

* Count every item of a layer in the bounds CLI exports frame to

* Count every item of a layer in the bounds the editor exports
2026-10-30 12:35:09 +00:00
Timon a2e62ed47e Report GPU and resource failures as node errors (#4846)
* Allow lazy scope inputs

* Report a missing GPU instead of panicking

* Return pipeline errors instead of panicking

* Stop logging error paths outside the document

* Report missing resources as errors

* Report Vello failures in Rasterize

* Better GPU test error handling
2026-10-30 12:22:06 +00:00
Dennis Kobert 9939966b0e Visit each network definition once in recursive walks (#4857)
* Visit each definition once in recursive walks and validation

* Rename DefinitionId to NetworkId to mirror the storage model

* Review fixes

* Make test more precise
2026-10-30 12:42:40 +01:00
275 changed files with 13926 additions and 8750 deletions

No files matched your search

+1 -1
View File
@@ -56,7 +56,7 @@ jobs:
CARGO_TERM_COLOR: always
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from Binaryen
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend and Binaryen
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.127"
+91 -1
View File
@@ -135,7 +135,7 @@ jobs:
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder of its own
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
steps:
- name: 📥 Clone repository
@@ -158,6 +158,96 @@ 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
+45
View File
@@ -0,0 +1,45 @@
name: "Provide Shaders"
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
- name: 📤 Upload graphene raster nodes shaders to artifacts repository
run: |
bash .github/workflows/scripts/artifact-upload.bash \
${{ vars.ARTIFACTS_REPO_OWNER }} \
${{ vars.ARTIFACTS_REPO_NAME }} \
${{ vars.ARTIFACTS_REPO_BRANCH }} \
rev/${{ github.sha }}/raster_nodes_shaders_entrypoint.wgsl \
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
- name: 📤 Push shaders to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
+2
View File
@@ -31,6 +31,7 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
cargoAbout = lib.call ./deps/cargo-about.nix;
};
@@ -56,6 +57,7 @@ in
default = graphite;
graphite = (lib.call ./pkgs/graphite.nix) { };
graphite-dev = (lib.call ./pkgs/graphite.nix) { dev = true; };
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
+55
View File
@@ -0,0 +1,55 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
filtered_args=()
for arg in "$@"; do
case "$arg" in
+nightly|+nightly-*) ;;
*) filtered_args+=("$arg") ;;
esac
done
exec ${toolchain}/bin/cargo ${"\${filtered_args[@]}"}
'';
rustc_codegen_spirv =
(pkgs.makeRustPlatform {
cargo = toolchain;
rustc = toolchain;
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-QluNI2TdJI0j2CBOeAbB9DfOv+8LqzWk7siZyT1WWLU=";
};
cargoHash = "sha256-vvviUccnip+j60Ml1vqLNJ49KyEF40VLUoV1TMALHMs=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
"--features=use-compiled-tools"
"--no-default-features"
];
doCheck = false;
});
in
{
toolchain = toolchain;
env = {
RUST_GPU_PATH_OVERRIDE = "${cargo}/bin:${toolchain}/bin";
RUSTC_CODEGEN_SPIRV_PATH = "${rustc_codegen_spirv}/lib/librustc_codegen_spirv.so";
};
}
+2 -6
View File
@@ -47,17 +47,13 @@ let
# Plotting tools
pkgs.graphviz
];
libs = [
pkgs.vulkan-loader
];
env = {
VK_ADD_DRIVER_FILES = "${pkgs.mesa}/share/vulkan/icd.d/lvp_icd.${pkgs.stdenv.hostPlatform.uname.processor}.json";
};
}
deps.rustGPU
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
@@ -0,0 +1,28 @@
{
info,
deps,
self,
system,
...
}:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "graphite-raster-nodes-shaders";
inherit (info) version src;
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
strictDeps = true;
env = deps.rustGPU.env;
buildPhase = ''
cargo build -r -p raster-nodes-shaders
'';
installPhase = ''
cp target/spirv-builder/spirv-unknown-naga-wgsl/release/deps/raster_nodes_shaders_entrypoint.wgsl $out
'';
doCheck = false;
}
+2
View File
@@ -35,6 +35,7 @@ let
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
}
);
@@ -96,6 +97,7 @@ deps.crane.lib.buildPackage (
makeCacheWritable = true;
env = {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
Generated
+471 -42
View File
@@ -313,6 +313,7 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
dependencies = [
"bytemuck",
"serde_core",
]
@@ -335,7 +336,7 @@ name = "blending-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"serde",
@@ -377,7 +378,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphic-types",
"half",
@@ -395,7 +396,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"serde",
]
@@ -487,6 +488,29 @@ dependencies = [
"serde",
]
[[package]]
name = "cargo-gpu-install"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668b4bd1b59810c4f907eeb36bb0f0a450c824219b2e599b9b8ef2b3ae056e94"
dependencies = [
"anyhow",
"cargo_metadata 0.21.0",
"directories",
"log",
"serde",
"spirv-builder",
]
[[package]]
name = "cargo-platform"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84982c6c0ae343635a3a4ee6dedef965513735c8b183caa7289fa6e27399ebd4"
dependencies = [
"serde",
]
[[package]]
name = "cargo-platform"
version = "0.3.3"
@@ -526,6 +550,37 @@ dependencies = [
"notify-debouncer-full",
]
[[package]]
name = "cargo-util-schemas"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dc1a6f7b5651af85774ae5a34b4e8be397d9cf4bc063b7e6dbd99a841837830"
dependencies = [
"semver",
"serde",
"serde-untagged",
"serde-value",
"thiserror 2.0.18",
"toml 0.8.23",
"unicode-xid",
"url",
]
[[package]]
name = "cargo_metadata"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cfca2aaa699835ba88faf58a06342a314a950d2b9686165e038286c30316868"
dependencies = [
"camino",
"cargo-platform 0.2.0",
"cargo-util-schemas",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "cargo_metadata"
version = "0.23.1"
@@ -533,7 +588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
dependencies = [
"camino",
"cargo-platform",
"cargo-platform 0.3.3",
"semver",
"serde",
"serde_json",
@@ -564,7 +619,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb823e721b3ea203f4635e71532db2b010696c074518eb4f6154fd7f47fc6fcb"
dependencies = [
"anyhow",
"cargo_metadata",
"cargo_metadata 0.23.1",
"cef-dll-sys",
"clap",
"libloading 0.9.0",
@@ -726,6 +781,8 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
@@ -802,7 +859,7 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
name = "control-protocol"
version = "0.0.0"
dependencies = [
"glam",
"glam 0.33.10",
"serde",
"serde_json",
]
@@ -891,19 +948,17 @@ dependencies = [
"ctor",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-hash",
"half",
"image",
"kurbo",
"log",
"lyon_geom",
"no-std-types",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"parley",
"petgraph",
"petgraph 0.7.1",
"polycool",
"rand",
"rand_chacha",
@@ -1171,6 +1226,15 @@ dependencies = [
"crypto-common",
]
[[package]]
name = "directories"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs"
version = "6.0.0"
@@ -1268,6 +1332,9 @@ dependencies = [
"graph-craft",
"graphene-resource",
"log",
"migration-core",
"migration-formats",
"migration-runner",
"postcard",
"serde",
"serde_json",
@@ -1363,7 +1430,7 @@ name = "dyn-any"
version = "0.3.1"
dependencies = [
"dyn-any-derive",
"glam",
"glam 0.33.10",
"reqwest",
]
@@ -1461,6 +1528,16 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7"
dependencies = [
"serde",
"typeid",
]
[[package]]
name = "errno"
version = "0.3.13"
@@ -1506,6 +1583,15 @@ dependencies = [
"regex-syntax 0.8.6",
]
[[package]]
name = "fastnoise-lite"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e5f3c3cc9081e5d0e18bcd50e80cd33cba47fc22f88a9da9c33ecd1c87ea5c0"
dependencies = [
"num-traits",
]
[[package]]
name = "fastrand"
version = "2.3.0"
@@ -1893,6 +1979,36 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.33.10"
@@ -1900,6 +2016,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
dependencies = [
"bytemuck",
"libm",
"serde_core",
]
@@ -1952,7 +2069,7 @@ dependencies = [
"core-types",
"criterion",
"dyn-any",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-application-io",
@@ -1987,7 +2104,7 @@ name = "graphene-animation"
version = "0.0.0"
dependencies = [
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"kurbo",
"serde",
@@ -2000,7 +2117,7 @@ dependencies = [
"blake3",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"log",
@@ -2017,7 +2134,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-application-io",
"log",
"serde",
@@ -2042,6 +2159,8 @@ dependencies = [
"image",
"interpreted-executor",
"log",
"migration-formats",
"migration-nodes",
"preprocessor",
"serde_json",
"tokio",
@@ -2055,7 +2174,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-animation",
"graphene-hash",
"graphic-types",
@@ -2071,7 +2190,7 @@ dependencies = [
name = "graphene-hash"
version = "0.0.0"
dependencies = [
"glam",
"glam 0.33.10",
"graphene-hash-derive",
"kurbo",
]
@@ -2106,7 +2225,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-application-io",
"graphene-canvas-utils",
@@ -2144,7 +2263,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"rand",
@@ -2160,7 +2279,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"node-macro",
"raster-types",
@@ -2181,7 +2300,7 @@ dependencies = [
"dirs",
"fd-lock",
"futures",
"glam",
"glam 0.33.10",
"graphite-desktop-ui",
"graphite-desktop-wrapper",
"interprocess",
@@ -2306,7 +2425,7 @@ dependencies = [
"dyn-any",
"env_logger",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-hash",
"graphene-std",
@@ -2317,6 +2436,8 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"migration-formats",
"migration-nodes",
"node-macro",
"num_enum",
"once_cell",
@@ -2910,7 +3031,7 @@ dependencies = [
"criterion",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-core",
@@ -3188,7 +3309,7 @@ dependencies = [
"ena",
"itertools 0.14.0",
"lalrpop-util",
"petgraph",
"petgraph 0.7.1",
"regex",
"regex-syntax 0.8.6",
"sha3",
@@ -3497,7 +3618,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-core",
"graphic-types",
"log",
@@ -3518,6 +3639,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "matrixmultiply"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "memchr"
version = "2.7.5"
@@ -3542,6 +3673,76 @@ 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"
@@ -3623,6 +3824,7 @@ dependencies = [
"naga-types",
"num-traits",
"once_cell",
"petgraph 0.8.2",
"rustc-hash 1.1.0",
"spirv",
"thiserror 2.0.18",
@@ -3641,6 +3843,21 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "ndarray"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
dependencies = [
"matrixmultiply",
"num-complex",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -3689,6 +3906,27 @@ dependencies = [
"libc",
]
[[package]]
name = "no-std-types"
version = "0.0.0"
dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"graphene-hash",
"half",
"log",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"serde",
"spirv-std",
"tsify",
"wasm-bindgen",
]
[[package]]
name = "node-docs"
version = "0.0.0"
@@ -3708,6 +3946,7 @@ dependencies = [
"convert_case 0.12.0",
"core-types",
"indoc",
"no-std-types",
"proc-macro-crate",
"proc-macro-error2",
"proc-macro2",
@@ -3791,6 +4030,15 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -4013,6 +4261,15 @@ dependencies = [
"libredox",
]
[[package]]
name = "ordered-float"
version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
dependencies = [
"num-traits",
]
[[package]]
name = "ordered-float"
version = "4.6.0"
@@ -4102,7 +4359,7 @@ name = "path-bool-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"linesweeper",
"log",
@@ -4147,6 +4404,17 @@ dependencies = [
"indexmap",
]
[[package]]
name = "petgraph"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54acf3a685220b533e437e264e4d932cfbdc4cc7ec0cd232ed73c08d03b8a7ca"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4407,7 +4675,7 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-std",
"interpreted-executor",
@@ -4627,16 +4895,25 @@ dependencies = [
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam",
"glam 0.33.10",
"graphene-core",
"graphene-hash",
"graphene-resource",
"image",
"kurbo",
"ndarray",
"no-std-types",
"node-macro",
"num-traits",
"num_enum",
"rand",
"rand_chacha",
"raster-nodes-shaders",
"raster-types",
"serde",
"spirv-std",
"tokio",
"tsify",
"vector-types",
@@ -4644,6 +4921,22 @@ dependencies = [
"wgpu-executor",
]
[[package]]
name = "raster-nodes-shaders"
version = "0.0.0"
dependencies = [
"cargo-gpu-install",
"env_logger",
"log",
]
[[package]]
name = "raster-nodes-shaders-entrypoint"
version = "0.0.0"
dependencies = [
"raster-nodes",
]
[[package]]
name = "raster-types"
version = "0.0.0"
@@ -4652,7 +4945,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"image",
"node-macro",
@@ -4663,6 +4956,12 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raw-string"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0501e134c6905fee1f10fed25b0a7e1261bf676cffac9543a7d0730dec01af2"
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -4681,6 +4980,12 @@ dependencies = [
"objc2-quartz-core",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.11.0"
@@ -4803,6 +5108,21 @@ 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"
@@ -4817,7 +5137,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"graphic-types",
@@ -4839,7 +5159,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-core",
"graphic-types",
"kurbo",
@@ -4969,6 +5289,16 @@ dependencies = [
"memchr",
]
[[package]]
name = "rspirv"
version = "0.13.0+sdk-1.4.341.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091dca2e1d6fd3098417b5ec88e77e80d1ba5945750943419dc976858082c296"
dependencies = [
"rustc-hash 1.1.0",
"spirv",
]
[[package]]
name = "rustc-demangle"
version = "0.1.26"
@@ -4987,6 +5317,20 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_codegen_spirv-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d703f5624720c5b6012f4b88d6e6766f43ed50d80144eaffd6791c3270754cdc"
dependencies = [
"rspirv",
"semver",
"serde",
"serde_json",
"spirv",
"thiserror 2.0.18",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -5244,6 +5588,27 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-untagged"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34836a629bcbc6f1afdf0907a744870039b1e14c0561cb26094fa683b158eff3"
dependencies = [
"erased-serde",
"serde",
"typeid",
]
[[package]]
name = "serde-value"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
dependencies = [
"ordered-float 2.10.1",
"serde",
]
[[package]]
name = "serde-wasm-bindgen"
version = "0.6.5"
@@ -5511,7 +5876,7 @@ name = "snapping"
version = "0.0.0"
dependencies = [
"criterion",
"glam",
"glam 0.33.10",
"kurbo",
]
@@ -5552,8 +5917,62 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
dependencies = [
"bitflags 2.13.2",
"serde",
]
[[package]]
name = "spirv-builder"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57fa119866f0311546e5309b18770b72141c25d185452c11a812be2c7b9d84e9"
dependencies = [
"cargo_metadata 0.21.0",
"log",
"memchr",
"raw-string",
"rustc_codegen_spirv-types",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "spirv-std"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d98471765e294d4dd6289350e3633b5c5ba57bb382c3287d83e69ee737179e0"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"glam 0.30.10",
"glam 0.31.1",
"glam 0.32.1",
"glam 0.33.10",
"libm",
"num-traits",
"spirv-std-macros",
"spirv-std-types",
]
[[package]]
name = "spirv-std-macros"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13a6a0d063d4dd003e43818135b7aa4a30c41c48b5d0efe2cac02220448d4f19"
dependencies = [
"proc-macro2",
"quote",
"spirv-std-types",
"syn 3.0.6",
]
[[package]]
name = "spirv-std-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "655632248eaaa205cea4656bc73c8285cbd8109fc784010b24ea6bd0bab79ac1"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -5772,6 +6191,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "text-nodes"
version = "0.0.0"
@@ -5780,7 +6208,7 @@ dependencies = [
"core-types",
"dyn-any",
"fancy-regex",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"ipsum",
@@ -6185,7 +6613,7 @@ name = "transform-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"rand",
@@ -6439,7 +6867,7 @@ dependencies = [
"delaunator",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-core",
"graphene-hash",
"graphic-types",
@@ -6467,14 +6895,14 @@ dependencies = [
"core-types",
"dyn-any",
"fixedbitset",
"glam",
"glam 0.33.10",
"graphene-hash",
"kurbo",
"log",
"lyon_geom",
"node-macro",
"num-traits",
"petgraph",
"petgraph 0.7.1",
"polycool",
"robust",
"rustc-hash 2.1.1",
@@ -6764,7 +7192,7 @@ dependencies = [
"clap",
"control-protocol",
"getrandom 0.3.3",
"glam",
"glam 0.33.10",
"image",
"interprocess",
"serde",
@@ -6872,6 +7300,7 @@ dependencies = [
"hashbrown 0.17.1",
"js-sys",
"log",
"naga",
"parking_lot",
"portable-atomic",
"profiling",
@@ -6966,13 +7395,13 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-application-io",
"half",
"log",
"node-macro",
"raster-types",
"rendering",
"thiserror 2.0.18",
"vello_gpu",
"web-sys",
"wgpu",
@@ -7013,7 +7442,7 @@ dependencies = [
"objc2-metal",
"objc2-quartz-core",
"once_cell",
"ordered-float",
"ordered-float 4.6.0",
"parking_lot",
"portable-atomic",
"portable-atomic-util",
+25 -3
View File
@@ -11,6 +11,12 @@ 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",
@@ -22,6 +28,8 @@ members = [
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/nodes/raster/shaders",
"node-graph/nodes/raster/shaders/entrypoint",
"node-graph/graph-craft",
"node-graph/graphene-cli",
"node-graph/nodes/gstd",
@@ -35,6 +43,7 @@ members = [
"tools/third-party-licenses",
"tools/editor-message-tree",
"tools/node-docs",
"tools/regression",
"tools/web-editor-driver",
]
default-members = [
@@ -81,6 +90,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
@@ -100,6 +110,11 @@ 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" }
@@ -152,6 +167,7 @@ wgpu = { version = "30.0", default-features = false, features = [
"webgl",
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
"fragile-send-sync-non-atomic-wasm",
"spirv",
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
@@ -193,7 +209,7 @@ color = "0.3"
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"std",
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
@@ -219,7 +235,7 @@ pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.4"
num-traits = "0.2"
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
"full",
@@ -253,6 +269,10 @@ open = "5.3"
spin = "0.10"
clap = "4.5"
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
spirv-std = { version = "0.10.0", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
@@ -260,12 +280,14 @@ linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints]
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[profile.dev]
opt-level = 1
[profile.dev.package]
no-std-types = { opt-level = 1 }
core-types= { opt-level = 1 }
interpreted-executor = { opt-level = 1 } # This is a mitigation for https://github.com/rustwasm/wasm-pack/issues/981 which is needed because the node_registry function is too large
graphite-proc-macros = { opt-level = 1 }
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[322234583139821148,{"inputs":[{"Node":{"node_id":6589978257209505606,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"trLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplicLine truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[4388711862172196665,{"inputs":[{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}]Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"GeLine truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}]},"import_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_dedLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"nameLine truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_dedupLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+1 -1
View File
@@ -187,7 +187,7 @@ allow-git = []
[sources.allow-org]
# 1 or more github.com organizations to allow git sources for
github = ["linebender"]
github = ["linebender", "Rust-GPU"]
# 1 or more gitlab.com organizations to allow git sources for
#gitlab = [""]
# 1 or more bitbucket.org organizations to allow git sources for
+1 -1
View File
@@ -15,7 +15,7 @@ publish.workspace = true
workspace = true
[features]
gpu = ["graphite-editor/gpu"]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
+6
View File
@@ -23,6 +23,8 @@ 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]
@@ -30,6 +32,8 @@ 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 }
@@ -39,6 +43,8 @@ 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,6 +121,45 @@ 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>,
@@ -300,6 +339,25 @@ 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,6 +47,10 @@ 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 {
pub trait Layout: Send + Sync {
fn manifest_basename(&self) -> &str;
fn session_basename(&self) -> &str;
fn registry_basename(&self) -> &str;
+70 -42
View File
@@ -14,9 +14,11 @@ 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::{Delta, HotOp, PeerId, Registry, Session, UserId};
use document_graph_storage::{PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -26,19 +28,21 @@ 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>;
@@ -81,6 +85,8 @@ 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
@@ -132,28 +138,45 @@ impl<L: Layout> Gdd<L> {
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
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;
#[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 peer = session_state.peer_id;
let user = session_state.user_id;
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)?,
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)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -165,16 +188,32 @@ 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);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
for hot_op in hot_log {
session.replay_hot_op(hot_op)?;
}
Ok(Self {
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only migrations change the opened document"))]
let mut gdd = 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
@@ -200,6 +239,7 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
migrated: false,
})
}
}
@@ -220,23 +260,6 @@ 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
@@ -260,6 +283,11 @@ 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
@@ -0,0 +1,62 @@
//! 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 = 1;
pub const SUPPORTED_FORMAT_VERSION: u32 = 2;
/// 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
@@ -0,0 +1,180 @@
//! 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))
}
}
+19 -1
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,6 +182,24 @@ 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> {
+111
View File
@@ -0,0 +1,111 @@
// 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}");
});
}
+1 -21
View File
@@ -1,5 +1,4 @@
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
use serde::{Deserialize, Serialize};
use crate::{AttributeDelta, AttributeValue, Attributes, TimeStamp, Value, ValueError, from_value, to_value};
use std::collections::{BTreeMap, btree_map};
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
@@ -8,16 +7,6 @@ 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 }
@@ -33,15 +22,6 @@ 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()
+7 -151
View File
@@ -1,32 +1,4 @@
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,
}
use crate::{Attributes, Delta, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Value, attr, compute_rev};
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
@@ -82,6 +54,12 @@ 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)
@@ -101,128 +79,6 @@ 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::*;
+57 -39
View File
@@ -1,6 +1,6 @@
use std::collections::HashSet;
use crate::{AttributeDelta, NetworkId, Node, NodeId, Registry, RegistryDelta, ResourceEntry, ResourceId};
use crate::{AttributeDelta, NetworkId, 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,12 +51,8 @@ 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];
// 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 {
// A moved node has no in-place op, so the only path is remove + re-add
if from_node.network != to_node.network {
deltas.push(RegistryDelta::RemoveNode {
id: node_id,
snapshot: from_node.clone(),
@@ -65,16 +61,34 @@ 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.
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(),
});
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(),
});
}
}
}
@@ -82,13 +96,15 @@ pub fn compute_deltas(from: &Registry, to: &Registry) -> Vec<RegistryDelta> {
deltas.push(RegistryDelta::ChangeNodeAttribute { id: node_id, 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,
});
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,
});
}
}
}
}
@@ -184,15 +200,6 @@ 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();
@@ -272,15 +279,12 @@ mod tests {
assert!(matches!(deltas[0], RegistryDelta::AddNode { id: NodeId(42), .. }));
}
/// 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.
/// 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.
#[test]
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();
fn compute_deltas_restates_inputs_on_length_change() {
let mut from = Registry::default();
from.node_instances.insert(NodeId(42), base.clone());
from.node_instances.insert(NodeId(42), Node::dummy());
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().inputs.push(crate::InputSlot {
@@ -291,11 +295,25 @@ mod tests {
let deltas = compute_deltas(&from, &to);
assert!(
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:?}"
matches!(deltas.as_slice(), [RegistryDelta::SetNodeInputs { id: NodeId(42), inputs }] if inputs.len() == 1),
"a slot count change must emit one SetNodeInputs, 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;
+14 -1
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, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
PeerId, PeerRegistration, Prior, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
};
#[derive(Clone, Debug)]
@@ -365,6 +365,19 @@ 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.
+33 -8
View File
@@ -1,6 +1,7 @@
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;
@@ -138,6 +139,32 @@ 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())?;
@@ -625,6 +652,8 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*import_index).try_into().map_err(|_| ConversionError::IndexOverflow(*import_index))?,
},
GraphCraftNodeInput::Reflection(_) => NodeInput::Reflection,
// GPU-specific; not modeled in the Registry format.
GraphCraftNodeInput::Inline(_) => return Err(ConversionError::UnsupportedImplementation),
})
}
@@ -669,14 +698,10 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
return Ok(Implementation::ProtoNode(*id));
}
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);
// 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}")))?;
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
+32
View File
@@ -250,3 +250,35 @@ 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
}
+1 -40
View File
@@ -1,18 +1,6 @@
use crate::RegistryDelta;
use crate::{NetworkId, NodeId, PeerId, RegistryDelta, Rev, TimeStamp};
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)
@@ -25,14 +13,6 @@ 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> {
@@ -59,25 +39,6 @@ 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) };
+6 -9
View File
@@ -10,6 +10,7 @@ pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod schema;
pub mod session;
mod touched;
pub mod value;
@@ -22,22 +23,18 @@ pub mod metadata_source;
pub mod to_runtime;
pub use attributes::*;
pub use crdt::*;
pub use document::*;
pub use history::History;
pub use history::{History, rehash_deltas};
pub use ids::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use schema::*;
pub use session::*;
pub use touched::Touched;
pub use value::{Value, ValueError, from_value, to_value};
pub use value::{ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
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,
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,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
+19 -93
View File
@@ -1,27 +1,5 @@
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,
}
use crate::registry::attributes_value_equal;
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
impl Node {
pub fn implementation(&self) -> &Implementation {
@@ -37,6 +15,21 @@ 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 {
@@ -74,19 +67,10 @@ impl Node {
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(crate::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 {
@@ -103,47 +87,6 @@ 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 {
@@ -164,27 +107,10 @@ 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::TimeStamp;
use crate::{ExportSlot, NodeId, TimeStamp};
fn target_slot(node_id: u64) -> ExportSlot {
ExportSlot {
+1 -105
View File
@@ -1,111 +1,7 @@
use crate::{
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
Tombstone,
};
use serde::{Deserialize, Serialize};
use crate::{AttributeValue, Implementation, InputSlot, Network, NetworkField, NetworkId, Node, NodeField, NodeId, NodeInput, Prior, Registry, RegistryDelta, ResourceId, Tombstone};
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();
+3 -44
View File
@@ -1,57 +1,16 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp};
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<&Node> {
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&crate::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<&Network> {
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&crate::Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
+2 -149
View File
@@ -1,27 +1,5 @@
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,
}
use crate::{PeerId, Priority, ResourceEntry, SourceKey, SourceValue, TimeStamp, Value, from_value, to_value};
use graphene_resource::ResourceHash;
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
@@ -34,67 +12,6 @@ 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.
@@ -205,70 +122,6 @@ 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::*;
@@ -0,0 +1,22 @@
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
@@ -0,0 +1,149 @@
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
@@ -0,0 +1,40 @@
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
@@ -0,0 +1,27 @@
//! 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
@@ -0,0 +1,106 @@
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
@@ -0,0 +1,103 @@
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>,
},
}
@@ -0,0 +1,44 @@
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,
}
@@ -0,0 +1,149 @@
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);
}
}
@@ -0,0 +1,38 @@
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)>>,
}
@@ -1,10 +1,10 @@
//! Persistent cursor state for the local peer. Separate from [`crate::Manifest`] because the
//! Persistent cursor state for the local peer. Separate from the document 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 document_graph_storage::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
use super::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
+108
View File
@@ -0,0 +1,108 @@
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)
}
}
+23 -37
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, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId,
Value, to_value,
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,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
@@ -96,6 +96,27 @@ 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.
@@ -918,19 +939,6 @@ 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)
@@ -956,12 +964,6 @@ 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);
@@ -972,22 +974,6 @@ 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,3 +767,15 @@ 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);
}
+4 -108
View File
@@ -1,6 +1,6 @@
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use crate::Value;
use serde::Serialize;
use serde::de::DeserializeOwned;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
@@ -10,111 +10,6 @@ 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;
@@ -163,6 +58,7 @@ pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[test]
fn round_trips_through_postcard() {
+24
View File
@@ -0,0 +1,24 @@
[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
@@ -0,0 +1,32 @@
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>,
}
@@ -0,0 +1,41 @@
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
@@ -0,0 +1,29 @@
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
@@ -0,0 +1,54 @@
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
@@ -0,0 +1,47 @@
//! 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
@@ -0,0 +1,47 @@
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
@@ -0,0 +1,47 @@
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
@@ -0,0 +1,30 @@
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
@@ -0,0 +1,24 @@
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
@@ -0,0 +1,441 @@
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
@@ -0,0 +1,20 @@
[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
@@ -0,0 +1,11 @@
//! 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;
@@ -0,0 +1,3 @@
//! One format step per version, each registering itself.
mod v1_to_v2;
@@ -0,0 +1,22 @@
//! 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
@@ -0,0 +1,483 @@
//! 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
@@ -0,0 +1,25 @@
//! 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
@@ -0,0 +1,242 @@
//! 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
@@ -0,0 +1,22 @@
[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
@@ -0,0 +1,89 @@
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
@@ -0,0 +1,258 @@
//! `#[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
@@ -0,0 +1,90 @@
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
@@ -0,0 +1,18 @@
[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
@@ -0,0 +1,4 @@
//! 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;
@@ -0,0 +1,39 @@
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]);
}
}
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `raster_nodes`.
mod mix_colors_from_mix_node;
+22
View File
@@ -0,0 +1,22 @@
[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
@@ -0,0 +1,73 @@
//! 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
@@ -0,0 +1,48 @@
//! 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
@@ -0,0 +1,260 @@
//! 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
@@ -0,0 +1,104 @@
//! 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
@@ -0,0 +1,297 @@
//! 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");
}
}
}
@@ -0,0 +1,57 @@
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 }));
}
@@ -0,0 +1,109 @@
//! 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(())
}
@@ -0,0 +1,182 @@
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}");
}
@@ -0,0 +1,195 @@
//! 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()));
}
Loaded 100 of 275 files, more files were not shown because too many files have changed in this diff. Show more