mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a9c44ac98 | ||
|
|
f7e592c255 | ||
|
|
e66eadcb84 | ||
|
|
48ec336287 | ||
|
|
bb446b58b6 | ||
|
|
76a91d8ff2 | ||
|
|
b015150036 | ||
|
|
6aecaf38e9 | ||
|
|
b1d15ce587 | ||
|
|
18a089cf2a | ||
|
|
82f2a76dc9 | ||
|
|
be575d2519 | ||
|
|
b3ffdffbcb | ||
|
|
f36ee54ccd | ||
|
|
3b41d76fbd | ||
|
|
b08b81add2 | ||
|
|
42456f00a7 | ||
|
|
2b63527478 | ||
|
|
d1a58b42f1 | ||
|
|
4aed212796 | ||
|
|
dae6a293e6 | ||
|
|
af393b1aae | ||
|
|
339b9ae8e7 | ||
|
|
82c08464d1 | ||
|
|
a2e62ed47e | ||
|
|
9939966b0e | ||
|
|
342957caba | ||
|
|
8c647e26af | ||
|
|
9d6860d968 | ||
|
|
f56bead5a1 | ||
|
|
0b20fd7869 | ||
|
|
cddd828842 | ||
|
|
a43a630aed | ||
|
|
386b692953 | ||
|
|
d6fa17122f | ||
|
|
d4ffee948f | ||
|
|
d9778ce6a8 | ||
|
|
b18eac389c | ||
|
|
e6ffddec91 | ||
|
|
c13a1edaf3 | ||
|
|
c180edeced | ||
|
|
75f0da035b | ||
|
|
0bc122e78e | ||
|
|
c20da5c3a5 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/f6a8460b0e85d05bb93a9536dc3d6ed6cc331178.tar.gz
|
||||
6e8ea35b8fe9f7a371c5c2570259c0e0be8a52cbdfa747551874724b0c58a576
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/60d4f11cdd8b483f65c1c9f6d4fb1344b878e9b0.tar.gz
|
||||
4ac444388551feef482f469a2c4e86de2a39bfd4a859b144e51a6c1a1be5fd60
|
||||
@@ -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
|
||||
|
||||
@@ -32,6 +32,7 @@ let
|
||||
deps = {
|
||||
crane = lib.call ./deps/crane.nix;
|
||||
rustGPU = lib.call ./deps/rust-gpu.nix;
|
||||
cargoAbout = lib.call ./deps/cargo-about.nix;
|
||||
};
|
||||
|
||||
args = {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# TODO: Remove once nixpkgs ships cargo-about >= 0.9.3, and switch back to `pkgs.cargo-about`
|
||||
{ pkgs, ... }:
|
||||
|
||||
pkgs.cargo-about.overrideAttrs (
|
||||
finalAttrs: _: {
|
||||
version = "0.9.3";
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "EmbarkStudios";
|
||||
repo = "cargo-about";
|
||||
tag = finalAttrs.version;
|
||||
hash = "sha256-Jlr4TYNZkzYo5V77n0YYrx1e8m17ELN/1+ZcR/Bl0K4=";
|
||||
};
|
||||
cargoDeps = pkgs.rustPlatform.fetchCargoVendor {
|
||||
inherit (finalAttrs) pname version src;
|
||||
hash = "sha256-kNGfQQumgvtDPhiQcqc9K2ohhEsTzuySeisHcNcmig8=";
|
||||
};
|
||||
}
|
||||
)
|
||||
+1
-1
@@ -23,7 +23,7 @@ let
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.cargo-about
|
||||
deps.cargoAbout
|
||||
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
|
||||
@@ -85,7 +85,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.cargo-about
|
||||
deps.cargoAbout
|
||||
pkgs.removeReferencesTo
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
];
|
||||
|
||||
Generated
+100
-4
@@ -1332,6 +1332,9 @@ dependencies = [
|
||||
"graph-craft",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"migration-core",
|
||||
"migration-formats",
|
||||
"migration-runner",
|
||||
"postcard",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2156,7 +2159,10 @@ dependencies = [
|
||||
"image",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"migration-formats",
|
||||
"migration-nodes",
|
||||
"preprocessor",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
@@ -2214,7 +2220,6 @@ dependencies = [
|
||||
name = "graphene-std"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"blending-nodes",
|
||||
"brush-nodes",
|
||||
"bytemuck",
|
||||
@@ -2237,8 +2242,10 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"reqwest",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"transform-nodes",
|
||||
"url",
|
||||
"vector-nodes",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
@@ -2429,6 +2436,8 @@ dependencies = [
|
||||
"kurbo",
|
||||
"log",
|
||||
"math-parser",
|
||||
"migration-formats",
|
||||
"migration-nodes",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"once_cell",
|
||||
@@ -2468,6 +2477,7 @@ dependencies = [
|
||||
name = "graphite-wasm-wrapper"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
@@ -3663,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"
|
||||
@@ -5028,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"
|
||||
@@ -6821,7 +6916,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=7306bb4f206d956a8989173237c406b1d7798b35#7306bb4f206d956a8989173237c406b1d7798b35"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -6836,7 +6931,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=7306bb4f206d956a8989173237c406b1d7798b35#7306bb4f206d956a8989173237c406b1d7798b35"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -6850,7 +6945,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=7306bb4f206d956a8989173237c406b1d7798b35#7306bb4f206d956a8989173237c406b1d7798b35"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -7306,6 +7401,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.18",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
|
||||
+15
-3
@@ -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",
|
||||
@@ -37,6 +43,7 @@ members = [
|
||||
"tools/third-party-licenses",
|
||||
"tools/editor-message-tree",
|
||||
"tools/node-docs",
|
||||
"tools/regression",
|
||||
"tools/web-editor-driver",
|
||||
]
|
||||
default-members = [
|
||||
@@ -103,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" }
|
||||
@@ -292,6 +304,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
Binary file not shown.
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.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":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"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":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"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":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplicationLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.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":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"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}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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":0,"output_index":0}},{"Node":{"node_id":3,"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}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"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}},{Line truncated
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1,7 +1,7 @@
|
||||
#[derive(clap::Parser)]
|
||||
#[clap(name = "graphite", version)]
|
||||
pub struct Cli {
|
||||
#[arg(help = "Files to open on startup")]
|
||||
#[arg(help = "Files to open on startup", value_parser = |path: &str| std::path::absolute(path))]
|
||||
pub files: Vec<std::path::PathBuf>,
|
||||
|
||||
#[arg(long, action = clap::ArgAction::SetTrue, help = "Disable hardware accelerated UI rendering")]
|
||||
|
||||
@@ -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"
|
||||
@@ -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()];
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -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(®istry));
|
||||
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,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()
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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, UserId,
|
||||
PeerId, PeerRegistration, Prior, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -112,8 +112,8 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
|
||||
/// Take on a peer's marks as well as this peer's. Returns what the dropped ops named.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
self.retired.absorb(remote);
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
@@ -134,16 +134,19 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Drop retired hot ops and re-derive working without them: their effect returns with their deltas.
|
||||
fn drop_retired_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
fn drop_retired_hot_ops(&mut self) -> Touched {
|
||||
let retired = &self.retired;
|
||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
let mut touched = Touched::default();
|
||||
let mut dropped = false;
|
||||
for hot_op in self.hot_log.extract_if(.., |hot_op| retired.covers(hot_op.id())) {
|
||||
touched.record(&hot_op.op);
|
||||
dropped = true;
|
||||
}
|
||||
if dropped {
|
||||
self.resync_hot_timestamps();
|
||||
self.rebuild_working();
|
||||
}
|
||||
dropped
|
||||
touched
|
||||
}
|
||||
|
||||
/// Apply a retired commit and record it in history.
|
||||
@@ -184,6 +187,12 @@ impl Document {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// A retired op from a peer, against both the retired and the working registry.
|
||||
pub(crate) fn apply_retired_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Retired, op.clone(), timestamp, ApplyMode::Idempotent)?;
|
||||
self.apply_op_idempotent(op, timestamp)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
|
||||
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
|
||||
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
|
||||
@@ -356,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.
|
||||
|
||||
@@ -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())?;
|
||||
@@ -671,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);
|
||||
@@ -698,7 +721,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
Implementation::Network(nested_network_id)
|
||||
}
|
||||
// TODO: Support Extract in the Registry format.
|
||||
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
|
||||
DocumentNodeImplementation::Extract | DocumentNodeImplementation::Definition(_) => return Err(ConversionError::UnsupportedImplementation),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,10 @@ impl History {
|
||||
history
|
||||
}
|
||||
|
||||
pub(crate) fn position(&self, rev: Rev) -> Option<usize> {
|
||||
self.index.get(&rev).copied()
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
self.index.get(&rev).map(|&position| &self.deltas[position])
|
||||
}
|
||||
@@ -50,6 +54,14 @@ impl History {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
/// Whether the deltas from `from` on form a single-parent chain off the delta before them, so are already sorted.
|
||||
pub(crate) fn extends_canonically(&self, from: usize) -> bool {
|
||||
(from..self.deltas.len()).all(|position| {
|
||||
let delta = &self.deltas[position];
|
||||
delta.parent == position.checked_sub(1).map(|previous| self.deltas[previous].id) && !matches!(delta.kind, RegistryDelta::Merge { .. })
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -90,22 +102,14 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
pub(crate) fn at(&self, position: usize) -> Option<&Delta> {
|
||||
self.deltas.get(position)
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
/// Peers holding the same deltas thus hold byte-identical history.
|
||||
pub(crate) fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
@@ -159,6 +163,35 @@ impl History {
|
||||
seen
|
||||
}
|
||||
|
||||
pub(crate) fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
|
||||
self.ancestors([descendant]).contains(&ancestor)
|
||||
}
|
||||
|
||||
/// `tip`, its first-parent ancestors at distance 1, 2, 4, 8, ..., and the root.
|
||||
pub(crate) fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
|
||||
let mut samples = vec![tip];
|
||||
let mut current = tip;
|
||||
let mut distance = 0_usize;
|
||||
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
|
||||
current = parent;
|
||||
distance += 1;
|
||||
if distance.is_power_of_two() {
|
||||
samples.push(current);
|
||||
}
|
||||
}
|
||||
// Copies of one document share the root, which tells a diverged copy from an unrelated document.
|
||||
if samples.last() != Some(¤t) {
|
||||
samples.push(current);
|
||||
}
|
||||
samples
|
||||
}
|
||||
|
||||
/// Every delta not reachable from `known`, in topological order.
|
||||
pub(crate) fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
let known = self.ancestors(known);
|
||||
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
@@ -217,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,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) };
|
||||
|
||||
@@ -10,7 +10,9 @@ pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod schema;
|
||||
pub mod session;
|
||||
mod touched;
|
||||
pub mod value;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -21,30 +23,29 @@ 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 value::{Value, ValueError, from_value, to_value};
|
||||
pub use touched::Touched;
|
||||
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};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use to_runtime::Declarations;
|
||||
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
}
|
||||
@@ -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,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();
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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::*;
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)>>,
|
||||
}
|
||||
+2
-2
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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, 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.
|
||||
@@ -288,14 +309,99 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Move the shared head back to its ancestor `target`, leaving the line since as a branch. Returns the move to
|
||||
/// broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to.
|
||||
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
if from == Some(target) {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let touched = self.touched_since(Some(target))?;
|
||||
let snapshot = self.fold_at(Some(target))?;
|
||||
|
||||
self.document.head = Some(target);
|
||||
self.document.retired_snapshot = snapshot;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.publish_up_to(target);
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
head: Some(target),
|
||||
copies: Vec::new(),
|
||||
},
|
||||
touched,
|
||||
))
|
||||
}
|
||||
|
||||
/// Follow a peer's [`HeadMove`], returning what the walked-over ops named. Changes nothing when the head is not
|
||||
/// where the move started, since this peer has then diverged, or when the copies don't chain from an ancestor of
|
||||
/// the head to the move's head.
|
||||
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
|
||||
if self.document.head != moved.from {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
expected: moved.from,
|
||||
found: self.document.head,
|
||||
});
|
||||
}
|
||||
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
|
||||
let touched = self.touched_since(base)?;
|
||||
let mut tip = base;
|
||||
for copy in &moved.copies {
|
||||
if copy.parent != tip || matches!(copy.kind, RegistryDelta::Merge { .. }) {
|
||||
return Err(CrdtError::MalformedHeadMove);
|
||||
}
|
||||
tip = Some(copy.id);
|
||||
}
|
||||
if tip != moved.head {
|
||||
return Err(CrdtError::MalformedHeadMove);
|
||||
}
|
||||
|
||||
// Like `follow`, a failed fold leaves only the copies behind in history.
|
||||
for copy in &moved.copies {
|
||||
self.document.clock.observe(copy.timestamp);
|
||||
self.document.history.push(copy.clone());
|
||||
}
|
||||
let snapshot = self.fold_at(moved.head)?;
|
||||
self.document.head = moved.head;
|
||||
self.document.retired_snapshot = snapshot;
|
||||
if !moved.copies.is_empty() {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
if let Some(head) = moved.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
|
||||
/// on the head's line.
|
||||
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
|
||||
let history = &self.document.history;
|
||||
let line = history.ancestors(self.document.head);
|
||||
if let Some(base) = base
|
||||
&& !line.contains(&base)
|
||||
{
|
||||
return Err(CrdtError::NotAncestor(base));
|
||||
}
|
||||
let kept = history.ancestors(base);
|
||||
let mut touched = Touched::default();
|
||||
for delta in history.iter().filter(|delta| line.contains(&delta.id) && !kept.contains(&delta.id)) {
|
||||
touched.record(&delta.kind);
|
||||
}
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
|
||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
||||
&self.document.retired
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
|
||||
self.document.absorb_retired_marks(remote);
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
self.document.absorb_retired_marks(remote)
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -304,41 +410,13 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
self.fold_at(self.document.head)
|
||||
}
|
||||
|
||||
fn fold_at(&self, head: Option<Rev>) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(head);
|
||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
@@ -404,6 +482,162 @@ impl Session {
|
||||
closed
|
||||
}
|
||||
|
||||
/// Takes a retirer's deltas and moves the head to `head` (by default the batch's last delta) without minting a
|
||||
/// merge. A batch not extending this head refolds the snapshot, leaving the old tip as a branch.
|
||||
pub fn follow(&mut self, incoming: Vec<Delta>, head: Option<Rev>) -> Result<MergeOutcome, CrdtError> {
|
||||
let before = self.document.head;
|
||||
let length_before = self.document.history.len();
|
||||
let named = head.is_some();
|
||||
let head = head.or_else(|| incoming.last().map(|delta| delta.id)).or(before);
|
||||
if let Some(head) = head
|
||||
&& !self.document.history.contains(head)
|
||||
&& !incoming.iter().any(|delta| delta.id == head)
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(head));
|
||||
}
|
||||
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = delta.all_parents().find(|&parent| !self.document.history.contains(parent)) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
// A late copy of a line this head is already past changes nothing unless the head is named.
|
||||
let stale = |head: Rev| !named && before.is_some_and(|before| self.document.history.is_ancestor(head, before));
|
||||
if self.document.history.len() == length_before && (head == before || head.is_some_and(stale)) {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
let mut chain = Vec::new();
|
||||
let mut current = head;
|
||||
let extends = loop {
|
||||
if current == before {
|
||||
break true;
|
||||
}
|
||||
let Some(rev) = current else { break false };
|
||||
let Some(delta) = self.document.history.get(rev) else { break false };
|
||||
if self.document.history.position(rev).is_some_and(|position| position < length_before) {
|
||||
break false;
|
||||
}
|
||||
// A merge may join a branch abandoned here, so the snapshot is refolded from the whole ancestry.
|
||||
if delta.all_parents().count() > 1 {
|
||||
break false;
|
||||
}
|
||||
chain.push(delta.clone());
|
||||
current = delta.parent;
|
||||
};
|
||||
|
||||
self.document.head = head;
|
||||
if extends {
|
||||
for delta in chain.into_iter().rev() {
|
||||
self.document.apply_retired_op_idempotent(delta.kind, delta.timestamp)?;
|
||||
}
|
||||
} else {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok(head.map_or(MergeOutcome::NoOp, MergeOutcome::FastForward))
|
||||
}
|
||||
|
||||
/// Integrates another peer's retired deltas, in causal order: fast-forwards when they extend `head`, otherwise
|
||||
/// joins `head` and the incoming tips with a [`RegistryDelta::Merge`].
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
|
||||
let length_before = self.document.history.len();
|
||||
let head_before = self.document.head;
|
||||
|
||||
// Applied to both registries, since working is the snapshot plus the hot log.
|
||||
let mut absorbed_ids = HashSet::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_retired_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed_ids.insert(delta.id);
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
if absorbed_ids.is_empty() {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
let extends = self.document.history.extends_canonically(length_before);
|
||||
if !extends {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
|
||||
let history = &self.document.history;
|
||||
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
|
||||
let parents: Vec<Rev> = if extends && self.document.head == last_before {
|
||||
// The chain hangs off `head`, so its end is the only tip.
|
||||
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
|
||||
} else {
|
||||
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
|
||||
candidates.extend(self.document.head);
|
||||
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
|
||||
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
|
||||
};
|
||||
|
||||
let outcome = match parents.as_slice() {
|
||||
[tip] => MergeOutcome::FastForward(*tip),
|
||||
_ => {
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(parents, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
|
||||
self.document.history.push(merge);
|
||||
MergeOutcome::Merged(merge_rev)
|
||||
}
|
||||
};
|
||||
self.document.head = outcome.head();
|
||||
// The line moved past what was undone, and a peer holds everything up to here.
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
|
||||
// A merge, or a batch sorted in ahead of the tail, may bring in effects that applying it did not.
|
||||
let mut refold = !extends || matches!(outcome, MergeOutcome::Merged(_));
|
||||
if !refold && let MergeOutcome::FastForward(tip) = outcome {
|
||||
refold = !self.fold_in_skipped(tip, head_before, &absorbed_ids)?;
|
||||
}
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Folds in the deltas between `from` and `tip` that the batch did not bring, such as steps undone here. `false`
|
||||
/// when the walk meets a merge or misses `from`.
|
||||
fn fold_in_skipped(&mut self, tip: Rev, from: Option<Rev>, absorbed: &HashSet<Rev>) -> Result<bool, CrdtError> {
|
||||
let mut skipped = Vec::new();
|
||||
let mut current = Some(tip);
|
||||
while current != from {
|
||||
let Some(delta) = current.and_then(|rev| self.document.history.get(rev)) else { return Ok(false) };
|
||||
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
|
||||
return Ok(false);
|
||||
}
|
||||
if !absorbed.contains(&delta.id) {
|
||||
skipped.push(delta.clone());
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
for delta in skipped.into_iter().rev() {
|
||||
self.document.apply_retired_op_idempotent(delta.kind, delta.timestamp)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
@@ -545,6 +779,29 @@ impl Session {
|
||||
self.document.history.iter()
|
||||
}
|
||||
|
||||
/// A sample of `head`'s ancestry, for a peer to work out what this session lacks.
|
||||
pub fn known_revs(&self) -> Vec<Rev> {
|
||||
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The deltas on `head`'s ancestry not reachable from `known`. Abandoned branches stay local, since merging one
|
||||
/// would bring an undone step back. The head counts as published from then on.
|
||||
pub fn deltas_unknown_to(&mut self, known: impl IntoIterator<Item = Rev>) -> Vec<Delta> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let deltas: Vec<Delta> = self
|
||||
.document
|
||||
.history
|
||||
.deltas_unknown_to(known)
|
||||
.into_iter()
|
||||
.filter(|delta| reachable.contains(&delta.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
if let Some(head) = self.document.head.filter(|_| !deltas.is_empty()) {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -682,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)
|
||||
@@ -720,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);
|
||||
@@ -736,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();
|
||||
@@ -834,6 +1056,12 @@ pub enum CrdtError {
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
NothingToRedo,
|
||||
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
|
||||
CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
|
||||
#[error("Delta {0} is not on the head's line")]
|
||||
NotAncestor(Rev),
|
||||
#[error("Head move copies do not chain from its base to its head")]
|
||||
MalformedHeadMove,
|
||||
#[error("Node {0} already exists")]
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
@@ -841,3 +1069,30 @@ pub enum CrdtError {
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
|
||||
/// A shared head move, as [`Session::move_head_to`] produces it and [`Session::apply_head_move`] follows it.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HeadMove {
|
||||
pub from: Option<Rev>,
|
||||
pub head: Option<Rev>,
|
||||
/// Steps minted again on top of the line's new end.
|
||||
pub copies: Vec<Delta>,
|
||||
}
|
||||
|
||||
/// How [`Session::merge`] or [`Session::follow`] moved the head.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MergeOutcome {
|
||||
NoOp,
|
||||
FastForward(Rev),
|
||||
Merged(Rev),
|
||||
}
|
||||
|
||||
impl MergeOutcome {
|
||||
/// `None` when nothing changed.
|
||||
pub fn head(self) -> Option<Rev> {
|
||||
match self {
|
||||
Self::NoOp => None,
|
||||
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -9,7 +9,7 @@ fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
pub(super) fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
|
||||
@@ -170,73 +170,6 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
|
||||
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
|
||||
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
#[test]
|
||||
fn resurrection_reaches_across_a_merge() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
})
|
||||
.expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
|
||||
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("resurrection must find the AddNetwork on the merged-in branch");
|
||||
}
|
||||
|
||||
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
|
||||
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
|
||||
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
|
||||
@@ -951,7 +884,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone.
|
||||
fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
@@ -965,7 +898,7 @@ fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
}
|
||||
|
||||
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
pub(super) fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
let delta = crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(value)),
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::to_runtime::ConversionError;
|
||||
use crate::{Declarations, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
|
||||
|
||||
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A root network holding a proto node and a group, with another proto node and a nested group inside
|
||||
/// the group, so projection is exercised two networks deep.
|
||||
fn nested_network() -> NodeNetwork {
|
||||
let inner = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
|
||||
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let group = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
|
||||
(
|
||||
RuntimeNodeId(21),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
|
||||
implementation: DocumentNodeImplementation::Network(inner),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
|
||||
(
|
||||
RuntimeNodeId(2),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
|
||||
implementation: DocumentNodeImplementation::Network(group),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A node projected alone must match the whole-document conversion, metadata included, since a mirror
|
||||
/// patched from projections has to match one rebuilt whole.
|
||||
#[test]
|
||||
fn projecting_a_node_matches_the_whole_conversion() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
for &id in registry.node_instances.keys() {
|
||||
let projected = projection.node(id).expect("every stored node projects");
|
||||
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
|
||||
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
|
||||
|
||||
assert_eq!(
|
||||
whole.nested_network(&path).and_then(|network| network.nodes.get(&local_id)),
|
||||
Some(&projected.node),
|
||||
"node {id} projected differently than the whole conversion converts it"
|
||||
);
|
||||
|
||||
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
|
||||
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
|
||||
|
||||
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
|
||||
let expected_nested: BTreeSet<_> = node_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.storage_id)
|
||||
.collect();
|
||||
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
|
||||
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
|
||||
|
||||
let expected_networks: BTreeSet<_> = network_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.network_id)
|
||||
.collect();
|
||||
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
|
||||
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_network_entry_projects_its_dense_exports_and_path() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
|
||||
let root = projection.network_entry(ROOT_NETWORK).expect("root");
|
||||
assert!(root.network_path.is_empty());
|
||||
assert_eq!(root.exports, whole.exports);
|
||||
|
||||
for &network_id in registry.networks.keys() {
|
||||
let entry = projection.network_entry(network_id).expect("every stored network projects");
|
||||
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
|
||||
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
|
||||
assert_eq!(entry.scope_injections, nested.scope_injections);
|
||||
if let Some(owner) = projection.owner(network_id) {
|
||||
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
|
||||
assert_eq!(
|
||||
entry.network_path,
|
||||
[owner_path.as_slice(), &[owner_local]].concat(),
|
||||
"a network's path ends in the node implementing it"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A network no node implements is not in the runtime, so nothing inside it has an address.
|
||||
#[test]
|
||||
fn an_unreachable_network_has_no_address() {
|
||||
let mut registry = Registry::default();
|
||||
registry.networks.insert(NetworkId(5), Network::default());
|
||||
let mut node = Node::dummy();
|
||||
node.network = NetworkId(5);
|
||||
registry.node_instances.insert(NodeId(9), node);
|
||||
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
assert_eq!(projection.network_path(NetworkId(5)), None);
|
||||
assert_eq!(projection.node_address(NodeId(9)), None);
|
||||
assert!(matches!(projection.node(NodeId(9)), Err(ConversionError::NetworkNotFound(_))));
|
||||
}
|
||||
|
||||
/// The runtime holds a copy of a network under each node implementing it, so one several nodes implement has no single
|
||||
/// address, and the root, which a node may name too, has no owner.
|
||||
#[test]
|
||||
fn a_network_several_nodes_implement_has_no_owner_and_neither_has_the_root() {
|
||||
let mut registry = Registry::default();
|
||||
registry.networks.insert(ROOT_NETWORK, Network::default());
|
||||
registry.networks.insert(NetworkId(5), Network::default());
|
||||
for (id, implemented) in [(1, NetworkId(5)), (2, NetworkId(5)), (3, ROOT_NETWORK)] {
|
||||
let mut node = Node::dummy();
|
||||
node.network = ROOT_NETWORK;
|
||||
node.implementation = crate::Implementation::Network(implemented);
|
||||
registry.node_instances.insert(NodeId(id), node);
|
||||
}
|
||||
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
assert_eq!(projection.owner(NetworkId(5)), None);
|
||||
assert_eq!(projection.network_path(NetworkId(5)), None);
|
||||
assert_eq!(projection.owner(ROOT_NETWORK), None);
|
||||
assert_eq!(projection.network_path(ROOT_NETWORK), Some(Vec::new()));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Peers exchanging retired history: syncing, following and merging lines, moving the shared head, and undo against what
|
||||
//! other peers hold.
|
||||
|
||||
use crate::{CrdtError, Delta, History, Implementation, MergeOutcome, Network, NetworkId, Node, NodeId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session, UserId, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::bookkeeping::{add_network, set_attribute};
|
||||
use super::crdt::{change_node_attribute, commit_retired};
|
||||
|
||||
/// Commits `op` as one interaction, with nothing hot.
|
||||
fn step(session: &mut Session, op: RegistryDelta) -> Rev {
|
||||
session.commit_op_for_test(op).expect("commit");
|
||||
session.document.working_registry = session.document.retired_snapshot.clone();
|
||||
let rev = session.head_rev().expect("committed");
|
||||
session.mark_interaction_end(rev);
|
||||
rev
|
||||
}
|
||||
|
||||
fn sync(from: &mut Session, to: &mut Session) -> MergeOutcome {
|
||||
let deltas = from.deltas_unknown_to(to.known_revs());
|
||||
to.merge(deltas).expect("merge")
|
||||
}
|
||||
|
||||
fn document_attribute(session: &Session, key: &str) -> Option<Value> {
|
||||
session.retired_registry().attributes.get(key).filter(|value| !value.deleted).map(|value| value.value.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_step_after_a_merge_further_back_can_be_undone() {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
step(&mut a, set_attribute("base", 0));
|
||||
step(&mut a, set_attribute("a0", 0));
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
|
||||
step(&mut a, set_attribute("a", 1));
|
||||
step(&mut b, set_attribute("b", 1));
|
||||
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::Merged(_)));
|
||||
|
||||
step(&mut a, set_attribute("mine", 1));
|
||||
assert!(a.can_undo(), "the head interaction is this user's own single step; the merge is further back");
|
||||
a.undo().expect("undo");
|
||||
assert_eq!(document_attribute(&a, "mine"), None);
|
||||
assert!(document_attribute(&a, "b").is_some(), "undo stopped at the merge");
|
||||
assert_eq!(a.retired_registry(), &a.snapshot_from_history().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_step_after_a_fast_forward_onto_unmarked_remote_deltas_can_be_undone() {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
step(&mut a, set_attribute("base", 0));
|
||||
step(&mut a, set_attribute("a0", 0));
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
|
||||
for i in 0..3 {
|
||||
let staged = b.stage_ops([set_attribute("remote", i)]).unwrap();
|
||||
b.retire(staged.last().unwrap().timestamp).unwrap();
|
||||
}
|
||||
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(_)));
|
||||
|
||||
step(&mut a, set_attribute("mine", 1));
|
||||
assert!(a.can_undo(), "the head interaction is this user's own single step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_step_handed_to_a_peer_is_published() {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
step(&mut a, set_attribute("base", 0));
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
step(&mut b, set_attribute("b", 1));
|
||||
step(&mut b, set_attribute("b", 2));
|
||||
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(_)));
|
||||
|
||||
assert!(!b.can_undo(), "A holds the step, so it is published");
|
||||
sync(&mut a, &mut b);
|
||||
sync(&mut b, &mut a);
|
||||
assert_eq!(a.retired_registry(), b.retired_registry());
|
||||
}
|
||||
|
||||
/// The tips as a scan finds them, for checking the maintained set against.
|
||||
fn scanned_tips(history: &History) -> Vec<Rev> {
|
||||
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
|
||||
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
|
||||
tips.sort_unstable();
|
||||
tips
|
||||
}
|
||||
|
||||
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
|
||||
fn branched_pair() -> (Session, Session) {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
|
||||
let mut b = a.clone();
|
||||
b.document.peer = PeerId(2);
|
||||
b.document.clock = crate::LamportClock::new(PeerId(2));
|
||||
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
|
||||
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
|
||||
(a, b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_indexes_follow_pushes_merges_and_reloads() {
|
||||
let (mut a, b) = branched_pair();
|
||||
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
|
||||
a.merge(b.cloned_deltas()).expect("merge");
|
||||
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
|
||||
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
|
||||
|
||||
let (id, hash) = (ResourceId::new(), ResourceHash::from(b"bytes".as_slice()));
|
||||
let entry = ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN);
|
||||
a.commit_op_for_test(RegistryDelta::AddResource { id, entry }).expect("add");
|
||||
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
|
||||
let snapshot = a.retired_registry().resources[&id].clone();
|
||||
a.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot }).expect("remove");
|
||||
assert!(a.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
|
||||
|
||||
let reloaded = History::from_ordered(a.cloned_deltas());
|
||||
assert_eq!(reloaded.tips(), a.document.history.tips());
|
||||
assert!(reloaded.resource_hashes().contains(&hash));
|
||||
assert!(a.history().all(|delta| reloaded.contains(delta.id)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merge_appends_a_chain_and_sorts_a_branch_into_place() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
|
||||
let mut guest = host.clone();
|
||||
guest.document.peer = PeerId(2);
|
||||
for op in [set_attribute("x", 1), add_network(5), set_attribute("y", 2)] {
|
||||
host.commit_op_for_test(op).expect("host step");
|
||||
}
|
||||
let (a, b) = branched_pair();
|
||||
|
||||
let ids = |history: &History| history.iter().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
for (mut receiver, mut sender, missing, fast_forward) in [(guest, host, 3, true), (a, b, 1, false)] {
|
||||
let before = receiver.history_len();
|
||||
let incoming: Vec<Delta> = sender.deltas_unknown_to(receiver.known_revs());
|
||||
assert_eq!(incoming.len(), missing, "only what the receiver lacks is sent");
|
||||
let outcome = receiver.merge(incoming).expect("merge");
|
||||
|
||||
let mut sorted = receiver.document.history.clone();
|
||||
sorted.canonical_sort();
|
||||
assert_eq!(ids(&sorted), ids(&receiver.document.history));
|
||||
assert_eq!(receiver.document.history.extends_canonically(before), fast_forward);
|
||||
assert_eq!(receiver.document.history.tips(), scanned_tips(&receiver.document.history));
|
||||
if fast_forward {
|
||||
assert_eq!(outcome, MergeOutcome::FastForward(sender.head_rev().expect("head")));
|
||||
assert_eq!(ids(&receiver.document.history), ids(&sender.document.history), "no merge delta");
|
||||
assert!(receiver.retired_registry().value_equal(sender.retired_registry()));
|
||||
assert_eq!(sender.merge(receiver.cloned_deltas()).expect("merge back"), MergeOutcome::NoOp);
|
||||
} else {
|
||||
assert!(matches!(outcome, MergeOutcome::Merged(_)), "{outcome:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undone_branch_is_kept_to_itself() {
|
||||
let mut author = Session::with_peer(PeerId(1));
|
||||
author.commit_op_for_test(set_attribute("base", 0)).expect("base");
|
||||
let base = author.head_rev().expect("base rev");
|
||||
author.mark_interaction_end(base);
|
||||
let mut peer = author.clone();
|
||||
peer.document.peer = PeerId(2);
|
||||
|
||||
author.commit_op_for_test(set_attribute("undone", 1)).expect("the step to undo");
|
||||
let undone = author.head_rev().expect("rev");
|
||||
author.mark_interaction_end(undone);
|
||||
author.undo().expect("undo");
|
||||
assert_eq!(author.head_rev(), Some(base));
|
||||
author.commit_op_for_test(set_attribute("kept", 2)).expect("a new branch");
|
||||
let kept = author.head_rev().expect("rev");
|
||||
|
||||
let sent: Vec<Rev> = author.deltas_unknown_to(peer.known_revs()).into_iter().map(|delta| delta.id).collect();
|
||||
assert_eq!(sent, vec![kept], "only the branch the cursor is on goes out, not the undone step");
|
||||
assert!(author.delta(undone).is_some(), "the undone step stays in the author's DAG for a history panel");
|
||||
|
||||
let incoming: Vec<Delta> = sent.iter().filter_map(|&rev| author.delta(rev).cloned()).collect();
|
||||
let outcome = peer.merge(incoming).expect("merge");
|
||||
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if rev == kept), "{outcome:?}");
|
||||
assert!(peer.retired_registry().attributes.get("kept").is_some_and(|value| !value.deleted));
|
||||
assert!(!peer.retired_registry().attributes.contains_key("undone"), "the undone step never reached the peer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn following_a_merge_refolds_the_branch_it_joins() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(1)).expect("root");
|
||||
let mut guest = Session::with_peer(PeerId(2));
|
||||
let root: Vec<Delta> = host.history().cloned().collect();
|
||||
guest.follow(root, host.head_rev()).expect("follow the root");
|
||||
|
||||
// The guest retires a step of its own while apart, then follows the host's line, which leaves it behind.
|
||||
guest.commit_op_for_test(add_network(2)).expect("own step");
|
||||
let own: Vec<Delta> = guest.history().filter(|delta| delta.author == PeerId(2)).cloned().collect();
|
||||
host.commit_op_for_test(add_network(3)).expect("host step");
|
||||
let line: Vec<Delta> = host.history().cloned().collect();
|
||||
guest.follow(line, host.head_rev()).expect("follow the host");
|
||||
assert!(!guest.retired_registry().networks.contains_key(&NetworkId(2)), "the guest's own step is off the line");
|
||||
|
||||
// The host merges the guest's step and the guest follows to the joined head.
|
||||
host.merge(own).expect("merge");
|
||||
let merged: Vec<Delta> = host.history().cloned().collect();
|
||||
guest.follow(merged, host.head_rev()).expect("follow the merge");
|
||||
|
||||
let fold = guest.snapshot_from_history().expect("fold");
|
||||
assert_eq!(guest.retired_registry(), &fold, "the snapshot is the fold of the joined head's ancestry");
|
||||
assert!(guest.retired_registry().networks.contains_key(&NetworkId(2)), "the branch is back on the line");
|
||||
assert_eq!(guest.retired_registry(), host.retired_registry());
|
||||
assert!(guest.registry().value_equal(guest.retired_registry()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_copy_of_a_followed_line_leaves_the_head_but_a_known_step_ahead_moves_it() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("a", 1)).unwrap();
|
||||
host.commit_op_for_test(set_attribute("b", 1)).unwrap();
|
||||
let deltas = host.cloned_deltas();
|
||||
let (first, second) = (deltas[0].id, deltas[1].id);
|
||||
|
||||
let mut guest = Session::with_peer(PeerId(2));
|
||||
guest.follow(deltas.clone(), None).unwrap();
|
||||
assert_eq!(guest.head_rev(), Some(second));
|
||||
|
||||
// The first step again, as a broadcast delayed past the second arrives.
|
||||
assert!(matches!(guest.follow(vec![deltas[0].clone()], None).unwrap(), MergeOutcome::NoOp));
|
||||
assert_eq!(guest.head_rev(), Some(second));
|
||||
|
||||
// The host moves back and then restores the step, which mints the same delta again.
|
||||
guest.follow(Vec::new(), Some(first)).unwrap();
|
||||
assert_eq!(guest.head_rev(), Some(first));
|
||||
guest.follow(vec![deltas[1].clone()], None).unwrap();
|
||||
assert_eq!(guest.head_rev(), Some(second));
|
||||
assert!(guest.retired_registry().value_equal(&host.snapshot_from_history().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn following_to_an_unknown_head_is_rejected_and_changes_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("a", 1)).unwrap();
|
||||
let mut guest = Session::with_peer(PeerId(2));
|
||||
guest.follow(host.cloned_deltas(), None).unwrap();
|
||||
let (head, registry) = (guest.head_rev(), guest.retired_registry().clone());
|
||||
|
||||
host.commit_op_for_test(set_attribute("b", 1)).unwrap();
|
||||
let unknown = host.head_rev().unwrap();
|
||||
assert!(matches!(guest.follow(Vec::new(), Some(unknown)), Err(crate::CrdtError::NotFoundInHistory(rev)) if rev == unknown));
|
||||
assert_eq!(guest.head_rev(), head);
|
||||
assert_eq!(guest.retired_registry(), ®istry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undone_step_leaves_no_stamp_behind_for_a_concurrent_write_to_lose_to() {
|
||||
let mut a = Session::with_peer(PeerId(3));
|
||||
step(&mut a, set_attribute("base", 1));
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
let concurrent = b.stage_ops([set_attribute("k", 20)]).unwrap().last().unwrap().timestamp;
|
||||
|
||||
step(&mut a, set_attribute("k", 10));
|
||||
a.undo().unwrap();
|
||||
step(&mut a, set_attribute("other", 1));
|
||||
sync(&mut a, &mut b);
|
||||
b.retire(concurrent).unwrap();
|
||||
sync(&mut b, &mut a);
|
||||
|
||||
assert_eq!(document_attribute(&a, "k"), document_attribute(&b, "k"));
|
||||
assert_eq!(a.retired_registry(), &a.snapshot_from_history().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_forward_onto_an_undone_step_folds_it_back_in() {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
let first = step(&mut a, set_attribute("first", 1));
|
||||
step(&mut a, set_attribute("second", 2));
|
||||
// A copy that left without being recorded, as when a crash comes between sending it and persisting the frontier.
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a.clone(), &mut b);
|
||||
a.undo().unwrap();
|
||||
assert_eq!(a.head_rev(), Some(first));
|
||||
|
||||
let third = step(&mut b, set_attribute("third", 3));
|
||||
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(rev) if rev == third));
|
||||
assert!(document_attribute(&a, "second").is_some());
|
||||
assert!(a.retired_registry().value_equal(&a.snapshot_from_history().unwrap()));
|
||||
assert!(!a.can_redo(), "the undone step is on the line again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_takes_only_this_users_own_steps_and_stops_at_a_merge() {
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
step(&mut a, set_attribute("first", 1));
|
||||
step(&mut a, set_attribute("second", 2));
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
assert!(!b.can_undo(), "the steps are the other user's");
|
||||
assert!(matches!(b.undo(), Err(crate::CrdtError::NothingToUndo)));
|
||||
|
||||
step(&mut a, set_attribute("a", 1));
|
||||
step(&mut b, set_attribute("b", 1));
|
||||
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::Merged(_)));
|
||||
assert!(!a.can_undo(), "the head is a merge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
|
||||
|
||||
assert!(matches!(merge_a, MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_revives_a_network_removed_on_a_merged_branch() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(add_network(network_id.0)).expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 is newer than its removal, so it brings 7 back from its tombstone.
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("a write newer than the removal revives the network");
|
||||
assert!(session_a.retired_registry().networks.contains_key(&network_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_concurrent_remove_and_attribute_change_commute() {
|
||||
let node = Node::new(NetworkId(5), Implementation::Network(NetworkId(5)), 0);
|
||||
let mut base = Session::with_peer(PeerId(1));
|
||||
commit_retired(&mut base, add_network(5));
|
||||
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
|
||||
|
||||
let mut remover = base.clone();
|
||||
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
|
||||
let mut changer = Session::with_peer(PeerId(2));
|
||||
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
|
||||
commit_retired(&mut changer, change_node_attribute(NodeId(7), "tint", serde_json::json!(75)));
|
||||
|
||||
// One delta from each branch, neither an ancestor of the other.
|
||||
let removal = remover.cloned_deltas().pop().expect("removal delta");
|
||||
let change = changer.cloned_deltas().pop().expect("change delta");
|
||||
let merged = |order: [Δ 2]| {
|
||||
let mut session = base.clone();
|
||||
session.merge(order.map(Delta::clone).to_vec()).expect("merge failed");
|
||||
session.retired_registry().clone()
|
||||
};
|
||||
assert_eq!(merged([&removal, &change]), merged([&change, &removal]));
|
||||
}
|
||||
|
||||
/// The retirer moves the head back: the line since stays as a branch, and a follower folds to the same state.
|
||||
#[test]
|
||||
fn moving_the_head_back_leaves_the_line_since_as_a_branch_everyone_follows() {
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let [first, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
|
||||
host.commit_op_for_test(set_attribute(key, value)).expect("step");
|
||||
let rev = host.head_rev().expect("rev");
|
||||
host.mark_interaction_end(rev);
|
||||
rev
|
||||
});
|
||||
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
|
||||
let (moved, touched) = host.move_head_to(first).expect("move");
|
||||
assert_eq!(moved.from, Some(third));
|
||||
assert_eq!(moved.head, Some(first));
|
||||
assert!(moved.copies.is_empty(), "nothing is minted: the line since is left behind");
|
||||
assert!(touched.is_empty(), "document attributes name no graph entity");
|
||||
let snapshot = host.retired_registry();
|
||||
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the second step's write is gone");
|
||||
assert!(snapshot.attributes.get("c").is_none_or(|value| value.deleted), "the third step's write is gone");
|
||||
assert_eq!(snapshot.attributes.get("a").map(|value| &value.value), Some(&Value::from(serde_json::json!(1))));
|
||||
assert!(host.delta(second).is_some() && host.delta(third).is_some(), "the steps left behind stay as a branch");
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
|
||||
guest.apply_head_move(&moved).expect("follow");
|
||||
assert_eq!(guest.head_rev(), Some(first));
|
||||
assert!(guest.retired_registry().value_equal(host.retired_registry()), "the follower folds to the same state");
|
||||
}
|
||||
|
||||
/// A move only applies from the head it started at: a peer elsewhere has diverged and is left as it was.
|
||||
#[test]
|
||||
fn a_head_move_from_another_head_is_rejected_and_changes_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
|
||||
let first = host.head_rev().expect("rev");
|
||||
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
|
||||
|
||||
let (moved, _) = host.move_head_to(first).expect("move");
|
||||
let registry = guest.retired_registry().clone();
|
||||
assert!(matches!(guest.apply_head_move(&moved), Err(CrdtError::CursorMismatch { found, .. }) if found == Some(first)));
|
||||
assert_eq!(guest.head_rev(), Some(first));
|
||||
assert_eq!(guest.retired_registry(), ®istry);
|
||||
}
|
||||
|
||||
/// Across a merge the move drops both merged branches, reports what each named, and takes either side as its target.
|
||||
#[test]
|
||||
fn a_head_move_back_across_a_merge_drops_both_branches() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(1)).expect("base");
|
||||
let base = host.head_rev().expect("rev");
|
||||
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
host.commit_op_for_test(add_network(2)).expect("host step");
|
||||
let host_step = host.head_rev().expect("rev");
|
||||
guest.commit_op_for_test(add_network(3)).expect("guest step");
|
||||
let guest_step = guest.head_rev().expect("rev");
|
||||
assert!(matches!(host.merge(guest.cloned_deltas()).expect("merge"), MergeOutcome::Merged(_)));
|
||||
|
||||
let mut moved_to_base = host.clone();
|
||||
let (_, touched) = moved_to_base.move_head_to(base).expect("move to the base");
|
||||
assert!(touched.networks.is_superset(&[NetworkId(2), NetworkId(3)].into()), "both branches are left behind: {touched:?}");
|
||||
assert!(!moved_to_base.retired_registry().networks.contains_key(&NetworkId(2)));
|
||||
assert!(!moved_to_base.retired_registry().networks.contains_key(&NetworkId(3)));
|
||||
|
||||
for (target, kept, dropped) in [(host_step, 2, 3), (guest_step, 3, 2)] {
|
||||
let mut moved = host.clone();
|
||||
moved.move_head_to(target).expect("either side of the merge is an ancestor");
|
||||
assert!(moved.retired_registry().networks.contains_key(&NetworkId(kept)));
|
||||
assert!(!moved.retired_registry().networks.contains_key(&NetworkId(dropped)));
|
||||
let sibling = if target == host_step { guest_step } else { host_step };
|
||||
assert!(matches!(moved.move_head_to(sibling), Err(CrdtError::NotAncestor(rev)) if rev == sibling));
|
||||
}
|
||||
}
|
||||
|
||||
/// A follower takes on the copies a move minted on top of its base and folds to the line they end.
|
||||
#[test]
|
||||
fn a_head_move_with_copies_is_followed_onto_them() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
|
||||
let first = host.head_rev().expect("rev");
|
||||
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
|
||||
let second = host.head_rev().expect("rev");
|
||||
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
|
||||
let copy = Delta::new(Some(first), PeerId(1), crate::TimeStamp { counter: 50, peer: PeerId(1) }, set_attribute("c", 3), Vec::new());
|
||||
let moved = crate::HeadMove {
|
||||
from: Some(second),
|
||||
head: Some(copy.id),
|
||||
copies: vec![copy.clone()],
|
||||
};
|
||||
let touched = guest.apply_head_move(&moved).expect("follow");
|
||||
assert!(touched.is_empty(), "the walked-over step wrote a document attribute");
|
||||
assert_eq!(guest.head_rev(), Some(copy.id));
|
||||
assert!(guest.clock_counter() >= 50, "a later edit here outdates the copy");
|
||||
assert!(guest.delta(copy.id).is_some() && guest.delta(second).is_some(), "the copy joins history and the old step stays");
|
||||
let snapshot = guest.retired_registry();
|
||||
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the step walked over is gone");
|
||||
assert_eq!(snapshot.attributes.get("c").map(|value| &value.value), Some(&Value::from(serde_json::json!(3))));
|
||||
assert!(guest.registry().value_equal(guest.retired_registry()));
|
||||
assert!(snapshot.value_equal(&guest.snapshot_from_history().expect("fold")));
|
||||
}
|
||||
|
||||
/// Copies that don't chain from the base to the move's head are refused before anything changes.
|
||||
#[test]
|
||||
fn a_malformed_head_move_changes_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
|
||||
let first = host.head_rev().expect("rev");
|
||||
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
|
||||
let second = host.head_rev().expect("rev");
|
||||
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
let (history_len, registry) = (guest.history_len(), guest.retired_registry().clone());
|
||||
|
||||
let copy = |counter, parent| Delta::new(parent, PeerId(1), crate::TimeStamp { counter, peer: PeerId(1) }, set_attribute("c", counter as u32), Vec::new());
|
||||
let off_first = copy(50, Some(first));
|
||||
let off_base_again = copy(51, Some(first));
|
||||
for moved in [
|
||||
// The copies end somewhere other than the move's head.
|
||||
crate::HeadMove {
|
||||
from: Some(second),
|
||||
head: Some(second),
|
||||
copies: vec![off_first.clone()],
|
||||
},
|
||||
// The second copy hangs off the base instead of the first copy.
|
||||
crate::HeadMove {
|
||||
from: Some(second),
|
||||
head: Some(off_base_again.id),
|
||||
copies: vec![off_first.clone(), off_base_again.clone()],
|
||||
},
|
||||
] {
|
||||
assert!(matches!(guest.apply_head_move(&moved), Err(CrdtError::MalformedHeadMove)));
|
||||
assert_eq!(guest.head_rev(), Some(second));
|
||||
assert_eq!(guest.history_len(), history_len);
|
||||
assert_eq!(guest.retired_registry(), ®istry);
|
||||
assert!(guest.registry().value_equal(guest.retired_registry()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Peers hold the line up to where the head moved, so a silent undo must not reach behind it.
|
||||
#[test]
|
||||
fn a_head_move_publishes_the_new_head() {
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let [_, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
|
||||
host.commit_op_for_test(set_attribute(key, value)).expect("step");
|
||||
let rev = host.head_rev().expect("rev");
|
||||
host.mark_interaction_end(rev);
|
||||
rev
|
||||
});
|
||||
host.publish_up_to(third);
|
||||
let mut guest = Session::load(PeerId(2), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
guest.publish_up_to(third);
|
||||
|
||||
let (moved, _) = host.move_head_to(second).expect("move");
|
||||
assert!(!host.can_undo(), "the step the room holds stays put");
|
||||
guest.apply_head_move(&moved).expect("follow");
|
||||
assert!(!guest.can_undo(), "the follower holds the same line");
|
||||
}
|
||||
@@ -112,6 +112,118 @@ fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// A node in runtime form with the metadata entries for it and everything nested under it, paths absolute.
|
||||
pub struct ProjectedNode {
|
||||
/// The runtime path of the network the node sits in.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
pub node: DocumentNode,
|
||||
/// The node's own entry first, then one per nested node.
|
||||
pub node_entries: Vec<NodeMetadataEntry>,
|
||||
/// One per network the node's implementation nests, outermost first.
|
||||
pub network_entries: Vec<NetworkMetadataEntry>,
|
||||
}
|
||||
|
||||
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
|
||||
pub struct ProjectedNetwork {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub exports: Vec<GraphCraftNodeInput>,
|
||||
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
|
||||
pub metadata: NetworkMetadataEntry,
|
||||
}
|
||||
|
||||
/// Converts single registry entities to runtime form, for keeping a runtime mirror in step without
|
||||
/// rebuilding it.
|
||||
pub struct RuntimeProjection<'a> {
|
||||
context: ConversionContext<'a>,
|
||||
/// The node whose implementation each nested network is, or `None` where several nodes implement it.
|
||||
owners: FxHashMap<NetworkId, Option<NodeId>>,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
|
||||
let mut owners = FxHashMap::default();
|
||||
for (&id, node) in &self.node_instances {
|
||||
if let Implementation::Network(network) = node.implementation
|
||||
&& network != ROOT_NETWORK
|
||||
{
|
||||
owners.entry(network).and_modify(|owner| *owner = None).or_insert(Some(id));
|
||||
}
|
||||
}
|
||||
RuntimeProjection {
|
||||
context: ConversionContext::new(self, declarations),
|
||||
owners,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeProjection<'_> {
|
||||
/// The node implementing `network`, or `None` for the root, for a network no node implements, and for one several
|
||||
/// nodes implement, which the runtime holds a copy of under each and no single path addresses.
|
||||
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
|
||||
self.owners.get(&network).copied().flatten()
|
||||
}
|
||||
|
||||
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
|
||||
/// `None` for a network the root does not reach, which the runtime does not hold.
|
||||
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
|
||||
let mut chain: Vec<(NodeId, &Node)> = Vec::new();
|
||||
let mut current = network;
|
||||
while current != ROOT_NETWORK {
|
||||
let owner = self.owner(current)?;
|
||||
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
|
||||
if chain.iter().any(|&(id, _)| id == owner) {
|
||||
return None;
|
||||
}
|
||||
let node = self.context.registry.node_instances.get(&owner)?;
|
||||
chain.push((owner, node));
|
||||
current = node.network;
|
||||
}
|
||||
Some(chain.into_iter().rev().map(|(id, node)| runtime_node_id(id, node)).collect())
|
||||
}
|
||||
|
||||
/// Where the node sits in the runtime: the path of its network, and its id within that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
|
||||
}
|
||||
|
||||
/// The node and everything nested under it, converted as a whole-document conversion would.
|
||||
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
|
||||
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
|
||||
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
|
||||
let local_id = runtime_node_id(id, node);
|
||||
|
||||
if let Implementation::Network(nested) = node.implementation {
|
||||
detect_network_cycle(&self.context, nested)?;
|
||||
}
|
||||
|
||||
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
|
||||
let mut network_entries = Some(Vec::new());
|
||||
Ok(ProjectedNode {
|
||||
node: convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?,
|
||||
network_path,
|
||||
local_id,
|
||||
node_entries: node_entries.expect("seeded above"),
|
||||
network_entries: network_entries.expect("seeded above"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The network's exports, scope injections and metadata, without its nodes.
|
||||
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
|
||||
let registry = self.context.registry;
|
||||
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
|
||||
Ok(ProjectedNetwork {
|
||||
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
|
||||
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
|
||||
exports: convert_exports(registry, id, network)?,
|
||||
network_path,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
@@ -201,25 +313,30 @@ fn convert_network(
|
||||
}
|
||||
}
|
||||
|
||||
// Input attributes aren't round-tripped for exports — Reflection/Import inputs don't appear there.
|
||||
let empty_attrs = crate::Attributes::new();
|
||||
let exports: Vec<GraphCraftNodeInput> = network
|
||||
.exports
|
||||
.iter()
|
||||
.filter_map(|slot| slot.target.as_ref())
|
||||
.map(|input| convert_input(context.registry, network_id, input, &empty_attrs))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let exports = convert_exports(context.registry, network_id, network)?;
|
||||
let scope_injections = read_scope_injections(context.registry, network_id, &network.attributes)?;
|
||||
|
||||
Ok(NodeNetwork {
|
||||
exports,
|
||||
nodes,
|
||||
scope_injections,
|
||||
definitions: FxHashMap::default(),
|
||||
generated: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The network's exports, compacted into the runtime's dense list.
|
||||
fn convert_exports(registry: &Registry, network_id: NetworkId, network: &crate::Network) -> Result<Vec<GraphCraftNodeInput>, ConversionError> {
|
||||
// Input attributes aren't round-tripped for exports — Reflection/Import inputs don't appear there.
|
||||
let empty_attrs = crate::Attributes::new();
|
||||
network
|
||||
.exports
|
||||
.iter()
|
||||
.filter_map(|slot| slot.target.as_ref())
|
||||
.map(|input| convert_input(registry, network_id, input, &empty_attrs))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rebuild a network's `scope_injections` from its serialized attribute blob, resolving each stored
|
||||
/// storage node ID back to its runtime-local ID. Mirrors `from_runtime::write_scope_injections`.
|
||||
fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes: &crate::Attributes) -> Result<FxHashMap<String, (RuntimeNodeId, Type)>, ConversionError> {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Which entities a run of ops named, so a runtime mirror of the registry can be brought back into line
|
||||
//! without a full rebuild.
|
||||
//!
|
||||
//! Over-approximate on purpose: an op is recorded whether or not it changed anything, and the mirror
|
||||
//! settles the outcome by comparing each entity's stored and mirrored forms. That is cheaper than having
|
||||
//! every apply arm report its outcome, and stays correct when an op revives an entity it only references.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::{Implementation, NetworkId, NodeId, NodeInput, RegistryDelta};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Touched {
|
||||
pub nodes: BTreeSet<NodeId>,
|
||||
pub networks: BTreeSet<NetworkId>,
|
||||
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
|
||||
pub resources: bool,
|
||||
}
|
||||
|
||||
impl Touched {
|
||||
/// Records every entity `op` names: its target and whatever it references.
|
||||
pub fn record(&mut self, op: &RegistryDelta) {
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
self.nodes.insert(*id);
|
||||
self.networks.insert(node.network);
|
||||
if let Implementation::Network(network) = node.implementation {
|
||||
self.networks.insert(network);
|
||||
}
|
||||
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
self.nodes.insert(*id);
|
||||
if let Implementation::Network(network) = implementation {
|
||||
self.networks.insert(*network);
|
||||
}
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } | RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs([new_input]);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
self.networks.insert(*id);
|
||||
self.reference_inputs(export);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
self.networks.insert(*id);
|
||||
}
|
||||
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
|
||||
self.resources = true;
|
||||
}
|
||||
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: Touched) {
|
||||
self.nodes.extend(other.nodes);
|
||||
self.networks.extend(other.networks);
|
||||
self.resources |= other.resources;
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
|
||||
}
|
||||
|
||||
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
|
||||
for input in inputs {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{AttributeDelta, Network, Node};
|
||||
|
||||
#[test]
|
||||
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
|
||||
assert!(touched.networks.is_empty());
|
||||
assert!(!touched.resources);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_touches_the_network_and_the_node_it_targets() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(3),
|
||||
index: 0,
|
||||
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
|
||||
});
|
||||
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta { key: "key".into(), value: None },
|
||||
});
|
||||
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
|
||||
assert!(touched.is_empty());
|
||||
|
||||
touched.record(&RegistryDelta::SetResourceHash {
|
||||
id: crate::ResourceId::new(),
|
||||
hash: None,
|
||||
});
|
||||
assert!(touched.resources);
|
||||
assert!(touched.nodes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_add_touches_the_node_its_network_and_what_its_inputs_reference() {
|
||||
let mut node = Node::dummy();
|
||||
let network = node.network;
|
||||
node.inputs.push(crate::InputSlot {
|
||||
input: NodeInput::Node { id: NodeId(9), index: 0 },
|
||||
timestamp: crate::TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
});
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
|
||||
touched.record(&RegistryDelta::AddNetwork {
|
||||
id: NetworkId(5),
|
||||
network: Network::default(),
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
|
||||
assert_eq!(touched.networks, BTreeSet::from([network, NetworkId(5)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implementing_a_node_by_a_network_touches_both() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::SetNodeImplementation {
|
||||
id: NodeId(1),
|
||||
implementation: Implementation::Network(NetworkId(2)),
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1)]));
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(2)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_a_node_implemented_by_a_network_touches_that_network_too() {
|
||||
let mut node = Node::dummy();
|
||||
let network = node.network;
|
||||
node.implementation = Implementation::Network(NetworkId(2));
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::AddNode { id: NodeId(1), node });
|
||||
|
||||
assert_eq!(touched.networks, BTreeSet::from([network, NetworkId(2)]));
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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)*
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}"))),
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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"]
|
||||
@@ -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;
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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(()),
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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(®istry.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(®istered_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(®istered_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(®istered_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()));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! The history properties of `migration_runner::testing` on the examples.
|
||||
|
||||
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
|
||||
|
||||
fn numbers(input_count: usize) -> SourceContract {
|
||||
SourceContract::new(input_count, |random, _| literal(Tagged::Number(random.below(10) as f64)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_commutes() {
|
||||
check_commutation(registered(decl!("graphene_core::ops::AddNode"@1)), &numbers(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_toggles_commute() {
|
||||
check_commutation(&OpacityToggles, &numbers(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_degrees_commutes() {
|
||||
check_commutation(&TransformDegrees, &numbers(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_between_degrees_commutes() {
|
||||
check_commutation(&AngleBetweenDegrees, &numbers(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_xy_to_split_commutes() {
|
||||
let contract = SourceContract {
|
||||
// The axis only accepts what produces an axis, which no extract XY output does
|
||||
reads_own_output: |slot| slot != 1,
|
||||
..SourceContract::new(2, |random: &mut Random, slot| match slot {
|
||||
1 => literal(Tagged::XY(random.pick(&[Axis::X, Axis::Y]))),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
};
|
||||
check_commutation(&ExtractXyToSplit, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_through_rewritten_history_matches_migrated_undo() {
|
||||
check_undo(&TransformDegrees, &numbers(3));
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "migration-snapshot"
|
||||
description = "The `cargo run migration` CLI: freezes Graphite's stored document types per format version and scaffolds node migrations"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
syn = { workspace = true }
|
||||
proc-macro2 = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Compares every node's API against a baseline commit, to find changes that need a version bump or a migration.
|
||||
|
||||
use crate::lineage::{MigrationStep, find_migrations};
|
||||
use crate::nodes::{NodeSource, find_nodes};
|
||||
use crate::scaffold::{MIGRATIONS, NODE_CRATES};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Fail if the nodes at the git ref `baseline` differ from the working tree's in a way documents would notice.
|
||||
pub fn check_against(workspace: &Path, baseline: &str) -> Result<(), String> {
|
||||
let current = find_nodes(&workspace.join(NODE_CRATES))?;
|
||||
let migrations = find_migrations(&workspace.join(MIGRATIONS))?;
|
||||
|
||||
let directory = std::env::temp_dir().join(format!("migration-api-baseline-{}", std::process::id()));
|
||||
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
|
||||
// Removal failing only leaves a temporary directory behind
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
let baseline_nodes = baseline_nodes?;
|
||||
|
||||
let problems = api_problems(&baseline_nodes, ¤t, &migrations);
|
||||
if !problems.is_empty() {
|
||||
return Err(problems.join("\n"));
|
||||
}
|
||||
|
||||
println!("No node API changed without a version bump since {baseline} ({} nodes)", baseline_nodes.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_baseline(workspace: &Path, baseline: &str, directory: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(directory).map_err(|error| format!("{}: {error}", directory.display()))?;
|
||||
|
||||
let mut archive = Command::new("git")
|
||||
.args(["archive", baseline, NODE_CRATES])
|
||||
.current_dir(workspace)
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|error| format!("running git: {error}"))?;
|
||||
let Some(tar_input) = archive.stdout.take() else {
|
||||
return Err("git archive has no output".to_string());
|
||||
};
|
||||
|
||||
let extracted = Command::new("tar")
|
||||
.args(["-x", "-C"])
|
||||
.arg(directory)
|
||||
.stdin(tar_input)
|
||||
.status()
|
||||
.map_err(|error| format!("running tar: {error}"))?;
|
||||
let archived = archive.wait().map_err(|error| format!("running git: {error}"))?;
|
||||
if !archived.success() || !extracted.success() {
|
||||
return Err(format!("could not read `{NODE_CRATES}` at the git ref `{baseline}`"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why `current` needs a version bump or a migration that it doesn't have, given the nodes at the baseline.
|
||||
fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[MigrationStep]) -> Vec<String> {
|
||||
let current_by_identifier: HashMap<&str, &NodeSource> = current.iter().map(|node| (node.identifier.as_str(), node)).collect();
|
||||
let baseline_identifiers: Vec<&str> = baseline.iter().map(|node| node.identifier.as_str()).collect();
|
||||
|
||||
let mut problems = Vec::new();
|
||||
for old in baseline {
|
||||
let identifier = &old.identifier;
|
||||
let version = old.version;
|
||||
|
||||
let Some(new) = current_by_identifier.get(identifier.as_str()) else {
|
||||
if migrations.iter().any(|step| step.source == (identifier.clone(), version)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Moving a module keeps the function and its API, which is what a rename looks like
|
||||
let moved = current
|
||||
.iter()
|
||||
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
||||
problems.push(match moved {
|
||||
Some(new) => format!(
|
||||
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
|
||||
new.identifier,
|
||||
version + 1,
|
||||
new.identifier
|
||||
),
|
||||
None => format!("`{identifier}`@{version} disappeared without a migration. Run `cargo run migration new {identifier}@{version} <replacing node>`"),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
|
||||
if new.version < version {
|
||||
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
|
||||
} else if new.version == version && new.signature != old.signature {
|
||||
problems.push(format!(
|
||||
"`{identifier}` changed its API without a version bump. Set `version({})` on it in {} and run `cargo run migration new`\n was: {}\n now: {}",
|
||||
version + 1,
|
||||
new.file.display(),
|
||||
old.signature,
|
||||
new.signature
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
problems
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn node(identifier: &str, version: u32, signature: &str) -> NodeSource {
|
||||
NodeSource {
|
||||
identifier: identifier.to_string(),
|
||||
version,
|
||||
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
|
||||
file: PathBuf::from("lib.rs"),
|
||||
signature: signature.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_nodes_and_bumped_ones_pass() {
|
||||
let baseline = [node("a::b", 1, "(x: f64)"), node("a::c", 1, "(x: f64)")];
|
||||
let current = [node("a::b", 1, "(x: f64)"), node("a::c", 2, "(x: f64, y: f64)")];
|
||||
assert!(api_problems(&baseline, ¤t, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_api_needs_a_bump() {
|
||||
let problems = api_problems(&[node("a::b", 1, "(x: f64)")], &[node("a::b", 1, "(x: f64, y: f64)")], &[]);
|
||||
assert_eq!(problems.len(), 1);
|
||||
assert!(problems[0].contains("Set `version(2)`"), "{}", problems[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_node_suggests_a_rename_until_it_has_a_migration() {
|
||||
let baseline = [node("old::b", 3, "(x: f64)")];
|
||||
let current = [node("new::b", 3, "(x: f64)")];
|
||||
|
||||
let problems = api_problems(&baseline, ¤t, &[]);
|
||||
assert!(problems[0].contains("rename old::b@3 new::b"), "{}", problems[0]);
|
||||
|
||||
let migrations = [MigrationStep {
|
||||
source: ("old::b".to_string(), 3),
|
||||
target: ("new::b".to_string(), 4),
|
||||
}];
|
||||
assert!(api_problems(&baseline, ¤t, &migrations).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_node_needs_a_migration() {
|
||||
let problems = api_problems(&[node("a::gone", 1, "(x: f64)")], &[], &[]);
|
||||
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user