mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bedc211954 | ||
|
|
65c04a49f1 | ||
|
|
63981ffa62 | ||
|
|
c4a2c93d57 | ||
|
|
abf6e599a9 | ||
|
|
9350e2f3b2 | ||
|
|
be72f25f9a | ||
|
|
ddf91d237a | ||
|
|
5f8dd62107 | ||
|
|
6eec6ae17c | ||
|
|
ca7706826f | ||
|
|
8d675ab949 | ||
|
|
3788ceb0bb | ||
|
|
afc60d23b3 | ||
|
|
de08019677 | ||
|
|
c88d9d366f | ||
|
|
e45a397abf | ||
|
|
b40c57d200 | ||
|
|
1d3ebc5454 | ||
|
|
db32addcb0 | ||
|
|
045cdfd5ee | ||
|
|
1d6b93a6d1 | ||
|
|
baced334ec | ||
|
|
4c4e0ba39b | ||
|
|
fbbae5876b | ||
|
|
fba33376bc | ||
|
|
a8104cf230 | ||
|
|
778e979c41 | ||
|
|
5ee999b847 | ||
|
|
9044a9c09a | ||
|
|
a1ff88ae30 | ||
|
|
d96f03fe90 | ||
|
|
708cca339d | ||
|
|
6e9208c004 | ||
|
|
412979278e | ||
|
|
7f7262c3cd | ||
|
|
8206b4cc88 | ||
|
|
b05af55d50 | ||
|
|
39b8d23a34 | ||
|
|
1199d312e4 | ||
|
|
b2cffdfd26 | ||
|
|
6479e0aeba | ||
|
|
bfd85cab6f | ||
|
|
67e5b899d4 | ||
|
|
488c992250 | ||
|
|
640aded2b2 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
|
||||
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
|
||||
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
"containerEnv": {
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
|
||||
"CARGO_ABOUT_VERSION": "0.9.2",
|
||||
"BINARYEN_VERSION": "130",
|
||||
"CARGO_BINSTALL_VERSION": "1.23.0"
|
||||
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
steps:
|
||||
@@ -348,7 +348,7 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
@@ -617,7 +617,7 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
|
||||
@@ -174,23 +174,12 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
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"
|
||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||
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
|
||||
cargo test --workspace --all-features
|
||||
--exclude 'graphite-desktop*'
|
||||
--exclude third-party-licenses
|
||||
&& cargo test --package third-party-licenses
|
||||
|
||||
# Render the documents of the regression corpus and compare them with their reference images
|
||||
regression-corpus:
|
||||
@@ -215,7 +204,7 @@ jobs:
|
||||
- name: 📥 Clone regression corpus
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: tagtraumen/graphite-corpus
|
||||
repository: GraphiteEditor/document-corpus
|
||||
path: target/regression-corpus
|
||||
lfs: true
|
||||
|
||||
@@ -237,16 +226,10 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
|
||||
|
||||
- name: 🖼️ Check the corpus renders against its references
|
||||
id: corpus
|
||||
continue-on-error: true
|
||||
run: cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
|
||||
|
||||
- name: ⚠️ Warn about mismatched renders
|
||||
if: ${{ steps.corpus.outcome == 'failure' }}
|
||||
run: echo "::warning title=Regression corpus::Some corpus documents render differently from their references. Their renders and diffs are in the regression-mismatches artifact."
|
||||
|
||||
- name: 📤 Upload the renders and diffs of mismatches
|
||||
if: ${{ steps.corpus.outcome == 'failure' }}
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: regression-mismatches
|
||||
@@ -279,14 +262,8 @@ jobs:
|
||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||
|
||||
- name: 🔬 Check migrations against the base commit
|
||||
id: migrations
|
||||
continue-on-error: true
|
||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||
|
||||
- name: ⚠️ Warn about missing migrations
|
||||
if: ${{ steps.migrations.outcome == 'failure' }}
|
||||
run: echo "::warning title=Migrations::Some node changes lack a version bump or a migration. The log of the check above lists them."
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
rust-fmt:
|
||||
needs: skip-check
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ let
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.wasm-bindgen-cli_0_2_129
|
||||
deps.cargoAbout
|
||||
|
||||
pkgs.rustc
|
||||
|
||||
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.wasm-bindgen-cli_0_2_129
|
||||
deps.cargoAbout
|
||||
pkgs.removeReferencesTo
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
|
||||
Generated
+2000
-2367
File diff suppressed because it is too large.
Load diff
+29
-26
@@ -19,6 +19,7 @@ members = [
|
||||
"document/migrations/nodes",
|
||||
"document/migrations/compiled",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -117,6 +118,7 @@ migration-formats = { path = "document/migrations/formats" }
|
||||
migration-compiled = { path = "document/migrations/compiled" }
|
||||
migration-nodes = { path = "document/migrations/nodes" }
|
||||
peer-transport = { path = "document/peer-transport" }
|
||||
document-live = { path = "document/live" }
|
||||
raster-nodes = { path = "node-graph/nodes/raster" }
|
||||
graphene-std = { path = "node-graph/nodes/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
@@ -141,13 +143,14 @@ serde_bytes = "0.11"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
||||
futures = "0.3"
|
||||
web-time = "1.1"
|
||||
env_logger = "0.11"
|
||||
log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
ctor = "1.0"
|
||||
convert_case = "0.12"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
fancy-regex = "0.20.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
indoc = "2.0.5"
|
||||
derivative = "2.2"
|
||||
@@ -173,10 +176,10 @@ wgpu = { version = "30.0", default-features = false, features = [
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.129" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.104"
|
||||
web-sys = { version = "=0.3.104", features = [
|
||||
js-sys = "=0.3.106"
|
||||
web-sys = { version = "=0.3.106", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -207,25 +210,25 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
usvg = "0.47"
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
skrifa = "0.44"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.33", default-features = false, features = [
|
||||
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.10"
|
||||
glam = { version = "0.34", default-features = false, features = [
|
||||
"std",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
"debug-glam-assert",
|
||||
"all-types",
|
||||
] }
|
||||
base64 = "0.22"
|
||||
base64 = "0.23"
|
||||
blake3 = "1.5"
|
||||
mmap-io = { version = "0.9", features = ["hugepages"] }
|
||||
mmap-io = { version = "1.0", features = ["hugepages"] }
|
||||
image = { version = "0.25", default-features = false, features = [
|
||||
"png",
|
||||
"jpeg",
|
||||
@@ -242,10 +245,10 @@ image = { version = "0.25", default-features = false, features = [
|
||||
pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
num_enum = { version = "0.7", default-features = false }
|
||||
num-derive = "0.4"
|
||||
num-derive = "0.5"
|
||||
num-traits = "0.2"
|
||||
tsify = { version = "0.5", default-features = false, features = ["js"] }
|
||||
syn = { version = "2.0", default-features = false, features = [
|
||||
syn = { version = "3.0", default-features = false, features = [
|
||||
"full",
|
||||
"derive",
|
||||
"parsing",
|
||||
@@ -259,14 +262,14 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
lyon_geom = "1.0"
|
||||
delaunator = "1.0"
|
||||
robust = "1.2"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
ollev = "0.1.1"
|
||||
dirs = "6.0"
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
gungraun = { version = "0.20" }
|
||||
ndarray = "0.17"
|
||||
ollev = "0.2.0"
|
||||
dirs = "7.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
include_dir = "0.7"
|
||||
@@ -274,14 +277,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
spin = "0.12"
|
||||
clap = "4.5"
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
linesweeper = "0.4"
|
||||
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.29"
|
||||
linesweeper = "0.5"
|
||||
smallvec = "1.13.2"
|
||||
zip = { version = "8", default-features = false }
|
||||
zip = { version = "9", default-features = false }
|
||||
|
||||
[workspace.lints]
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
<a href="https://graphite.art/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
|
||||
@@ -83,3 +81,13 @@ Are you a graphics programmer or Rust developer? Graphite aims to be one of the
|
||||
## License
|
||||
|
||||
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
We're grateful to these programs and organizations for the grants and services that help make Graphite possible.
|
||||
|
||||
[<img width="600" alt="European Commission, NGI Zero, and NLnet Foundation" src="https://github.com/user-attachments/assets/d5b3c623-710a-4809-916b-263e80c28184" />](https://nlnet.nl/commonsfund/)
|
||||
|
||||
[<img width="600" alt="Google Summer of Code" src="https://github.com/user-attachments/assets/37284dfe-fccd-4abd-904c-1165ff36da53" />](https://summerofcode.withgoogle.com/)
|
||||
|
||||
[<img width="300" alt="CI Powered by Blacksmith" src="https://github.com/user-attachments/assets/72bd48c2-ab21-4aed-b0a5-d440a8662128" />](https://www.blacksmith.sh/)
|
||||
+36
-27
@@ -1,11 +1,10 @@
|
||||
use rand::Rng;
|
||||
use rand::RngExt;
|
||||
use rfd::AsyncFileDialog;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, SyncSender};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::application::ApplicationHandler;
|
||||
@@ -43,14 +42,14 @@ pub(crate) struct App {
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
desktop_wrapper: DesktopWrapper,
|
||||
runtime_command_sender: Sender<RuntimeCommand>,
|
||||
ui: UiInstance,
|
||||
ui_frame_received: bool,
|
||||
start_render_sender: SyncSender<()>,
|
||||
ui_initialized: Option<Instant>,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
ui_frame_received: bool,
|
||||
ui_startup_buffer: Vec<Vec<u8>>,
|
||||
preferences: preferences::DesktopPreferences,
|
||||
launch_documents: Option<Vec<PathBuf>>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exiting: bool,
|
||||
exit_reason: ExitReason,
|
||||
}
|
||||
|
||||
@@ -74,9 +73,7 @@ impl App {
|
||||
})
|
||||
.expect("Error setting Ctrl-C handler");
|
||||
|
||||
let exiting = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
|
||||
let (runtime_command_sender, start_render_receiver) = std::sync::mpsc::channel();
|
||||
|
||||
let async_runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.thread_name("graphite-async")
|
||||
@@ -90,9 +87,9 @@ impl App {
|
||||
let editor_wake = move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
};
|
||||
let runtime_wake_sender = start_render_sender.clone();
|
||||
let runtime_wake_sender = runtime_command_sender.clone();
|
||||
let runtime_wake = move || {
|
||||
let _ = runtime_wake_sender.try_send(());
|
||||
let _ = runtime_wake_sender.send(RuntimeCommand::Run);
|
||||
};
|
||||
let wgpu_executor = WgpuExecutor::with_context(wgpu_context).expect("Failed to create WgpuExecutor");
|
||||
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
|
||||
@@ -106,17 +103,23 @@ impl App {
|
||||
);
|
||||
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let exiting_clone = exiting.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut update = false;
|
||||
loop {
|
||||
if update {
|
||||
node_runtime.update();
|
||||
}
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
|
||||
if start_render_receiver.recv_timeout(timeout).is_err() {
|
||||
node_runtime.begin_frame();
|
||||
}
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
|
||||
let first = start_render_receiver.recv_timeout(Duration::from_millis(100)).unwrap_or(RuntimeCommand::Update);
|
||||
update = false;
|
||||
for reason in std::iter::once(first).chain(start_render_receiver.try_iter()) {
|
||||
match reason {
|
||||
RuntimeCommand::Update => update = true,
|
||||
RuntimeCommand::Run => {}
|
||||
RuntimeCommand::Exit => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -138,12 +141,12 @@ impl App {
|
||||
desktop_wrapper,
|
||||
ui,
|
||||
ui_frame_received: false,
|
||||
start_render_sender,
|
||||
runtime_command_sender,
|
||||
ui_initialized: None,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
ui_startup_buffer: Vec::new(),
|
||||
preferences,
|
||||
launch_documents: Some(launch_documents),
|
||||
exiting,
|
||||
exiting: false,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
}
|
||||
}
|
||||
@@ -154,10 +157,10 @@ impl App {
|
||||
}
|
||||
|
||||
fn exit(&mut self, reason: Option<ExitReason>) {
|
||||
if self.exiting.swap(true, Ordering::Relaxed) {
|
||||
if std::mem::replace(&mut self.exiting, true) {
|
||||
return;
|
||||
}
|
||||
let _ = self.start_render_sender.send(());
|
||||
let _ = self.runtime_command_sender.send(RuntimeCommand::Exit);
|
||||
if let Some(reason) = reason {
|
||||
self.exit_reason = reason;
|
||||
}
|
||||
@@ -464,7 +467,7 @@ impl App {
|
||||
if self.ui_initialized.is_some() {
|
||||
self.ui.send(UiCommand::Message(message));
|
||||
} else {
|
||||
self.web_communication_startup_buffer.push(message);
|
||||
self.ui_startup_buffer.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,7 +476,7 @@ impl App {
|
||||
AppEvent::WebCommunicationInitialized => {
|
||||
self.ui_initialized = Some(Instant::now());
|
||||
self.ui_frame_received = false;
|
||||
for message in self.web_communication_startup_buffer.drain(..) {
|
||||
for message in self.ui_startup_buffer.drain(..) {
|
||||
self.ui.send(UiCommand::Message(message));
|
||||
}
|
||||
}
|
||||
@@ -649,7 +652,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
Err(other) => tracing::error!("Render error: {:?}", other),
|
||||
}
|
||||
let _ = self.start_render_sender.try_send(());
|
||||
let _ = self.runtime_command_sender.send(RuntimeCommand::Update);
|
||||
}
|
||||
|
||||
if !self.ui_frame_received
|
||||
@@ -759,6 +762,12 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
}
|
||||
|
||||
enum RuntimeCommand {
|
||||
Update,
|
||||
Run,
|
||||
Exit,
|
||||
}
|
||||
|
||||
pub(crate) enum ExitReason {
|
||||
Shutdown,
|
||||
Restart,
|
||||
|
||||
@@ -45,11 +45,3 @@ pub(crate) fn app_resources_dir() -> PathBuf {
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
pub(crate) fn delete_old_cef_browser_directory() {
|
||||
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
|
||||
if old_browser_dir.is_dir() {
|
||||
let _ = std::fs::remove_dir_all(&old_browser_dir);
|
||||
}
|
||||
}
|
||||
@@ -74,9 +74,6 @@ pub fn start() -> ExitCode {
|
||||
|
||||
dirs::clear_dir(&ui::temp_dir_root());
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
|
||||
|
||||
@@ -28,12 +28,13 @@ wgpu-sync = { workspace = true }
|
||||
winit = { workspace = true, features = ["serde"] }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
cef = { workspace = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
ipc-channel = "0.22"
|
||||
ipc-channel = "0.23"
|
||||
|
||||
# Linux-specific dependencies
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
|
||||
@@ -8,7 +8,7 @@ const APP_DIRECTORY_NAME: &str = "graphite";
|
||||
const APP_DIRECTORY_NAME: &str = "Graphite";
|
||||
|
||||
pub(crate) fn app_tmp_dir() -> PathBuf {
|
||||
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
|
||||
let path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
|
||||
if let Err(e) = fs::create_dir_all(&path) {
|
||||
tracing::error!("Failed to create temp directory at {path:?}: {e}");
|
||||
}
|
||||
|
||||
@@ -48,6 +48,10 @@ impl ImplApp for BrowserProcessAppImpl {
|
||||
cmd.append_switch(Some(&"disable-default-apps".into()));
|
||||
cmd.append_switch(Some(&"disable-breakpad".into()));
|
||||
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
|
||||
cmd.append_switch_with_value(
|
||||
Some(&"host-resolver-rules".into()),
|
||||
Some(&"MAP * ~NOTFOUND, EXCLUDE fonts.googleapis.com, EXCLUDE fonts.gstatic.com".into()),
|
||||
);
|
||||
|
||||
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
|
||||
let disabled_features_switch = Some(&"disable-features".into());
|
||||
|
||||
@@ -27,7 +27,6 @@ wgpu-executor = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -99,6 +99,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerClipboardWrite { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
|
||||
}
|
||||
// No web origin here, so use the hosted editor
|
||||
FrontendMessage::TriggerSessionLinkCopy { token } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
|
||||
content: format!("https://editor.graphite.rs/?session={token}"),
|
||||
});
|
||||
}
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
@@ -64,7 +63,7 @@ impl DesktopWrapper {
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Archive for Zip {
|
||||
if !entry.is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.name().to_string();
|
||||
let name = entry.name().map_err(zip_err)?.to_string();
|
||||
validate_path(&name)?;
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
@@ -91,7 +91,7 @@ impl MmappedBytes {
|
||||
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
|
||||
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
|
||||
let len = file.len();
|
||||
file.as_slice(0, len)
|
||||
file.as_slice_bytes(0, len)
|
||||
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
|
||||
Ok(Self(file))
|
||||
}
|
||||
@@ -105,7 +105,7 @@ impl MmappedBytes {
|
||||
impl AsRef<[u8]> for MmappedBytes {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
let len = self.0.len();
|
||||
match self.0.as_slice(0, len) {
|
||||
match self.0.as_slice_bytes(0, len) {
|
||||
Ok(slice) => slice,
|
||||
Err(error) => {
|
||||
log::error!("Failed to obtain mmap slice: {error}");
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Blob records in the working copy, one `blobs/<hash>` file each.
|
||||
//!
|
||||
//! A record holds a blob in full or as a copy delta against an older blob of the same node input. Most edits change only a
|
||||
//! few bytes of a value, so a delta is small. Records are not compressed. This lets an archive codec compress across them.
|
||||
//!
|
||||
//! Record layout is a kind byte, then the 32 base hash bytes for a delta, then the payload.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use document_graph_storage::{BlobHash, ResourceHash};
|
||||
|
||||
use crate::layout::Layout;
|
||||
|
||||
const FULL: u8 = 0;
|
||||
const DELTA: u8 = 1;
|
||||
|
||||
/// The decoded bytes of every blob the document names.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct BlobStore {
|
||||
pub(crate) bytes: BlobBytes,
|
||||
/// The records of blobs stored as deltas. Other blobs are stored in full.
|
||||
delta_records: HashMap<BlobHash, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BlobStore {
|
||||
/// Hold a new blob and return the record to write for it. The record is a delta when `base` is held.
|
||||
/// Returns `None` for a blob that is already held.
|
||||
pub(crate) fn insert(&mut self, hash: BlobHash, bytes: Vec<u8>, base: Option<BlobHash>) -> Option<Vec<u8>> {
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let record = match base.and_then(|base| Some((base, self.bytes.get(&base)?))) {
|
||||
Some((base, base_bytes)) => {
|
||||
let record = delta_record(base, base_bytes, &bytes);
|
||||
self.delta_records.insert(hash, record.clone());
|
||||
record
|
||||
}
|
||||
None => full_record(&bytes),
|
||||
};
|
||||
|
||||
self.bytes.insert(hash, bytes);
|
||||
Some(record)
|
||||
}
|
||||
|
||||
/// [`insert`](Self::insert) every blob in hash order. A base goes in before the blobs that use it.
|
||||
pub(crate) fn insert_all(&mut self, blobs: NewBlobs) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let NewBlobs { bytes: mut blobs, bases } = blobs;
|
||||
let mut hashes: Vec<_> = blobs.keys().copied().collect();
|
||||
hashes.sort_unstable();
|
||||
|
||||
let mut records = Vec::new();
|
||||
for hash in hashes {
|
||||
for hash in chain_to(hash, |hash| bases.get(hash).filter(|base| blobs.contains_key(base)).copied()) {
|
||||
let Some(bytes) = blobs.remove(&hash) else { continue };
|
||||
if let Some(record) = self.insert(hash, bytes, bases.get(&hash).copied()) {
|
||||
records.push((hash, record));
|
||||
}
|
||||
}
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// The record of every held blob in hash order. A base comes before the blobs that use it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn records(&self) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut hashes: Vec<_> = self.bytes.keys().copied().collect();
|
||||
hashes.sort_unstable();
|
||||
|
||||
let mut listed = HashSet::new();
|
||||
let mut records = Vec::new();
|
||||
for hash in hashes {
|
||||
let unlisted_base = |hash: &BlobHash| record_base(self.delta_records.get(hash)?).filter(|base| !listed.contains(base) && self.bytes.contains_key(base));
|
||||
for hash in chain_to(hash, unlisted_base) {
|
||||
if listed.insert(hash)
|
||||
&& let Some(record) = self.delta_records.get(&hash).cloned().or_else(|| self.full_record(&hash))
|
||||
{
|
||||
records.push((hash, record));
|
||||
}
|
||||
}
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Hold the blobs of records from a peer and return the records to write.
|
||||
/// Skips a record that is malformed, fails its hash check or needs a base that is not held.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn absorb(&mut self, records: Vec<(BlobHash, Vec<u8>)>) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut pending = records;
|
||||
let mut held = Vec::new();
|
||||
|
||||
// A record can arrive before its base, so repeat until a pass holds nothing new
|
||||
loop {
|
||||
let waiting = pending.len();
|
||||
pending.retain(|(hash, record)| {
|
||||
if self.bytes.contains_key(hash) {
|
||||
return false;
|
||||
}
|
||||
let bytes = match decode_record(record) {
|
||||
Some(Record::Full(bytes)) => bytes.to_vec(),
|
||||
Some(Record::Delta { base, delta }) => {
|
||||
let Some(base_bytes) = self.bytes.get(&base) else { return true };
|
||||
let Some(bytes) = apply_copy_delta(base_bytes, delta) else { return false };
|
||||
bytes
|
||||
}
|
||||
None => return false,
|
||||
};
|
||||
|
||||
match self.hold_checked(*hash, bytes, record.clone()) {
|
||||
Ok(()) => held.push((*hash, record.clone())),
|
||||
Err(error) => log::warn!("{error}"),
|
||||
}
|
||||
false
|
||||
});
|
||||
if pending.is_empty() || pending.len() == waiting {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
held
|
||||
}
|
||||
|
||||
/// A full record of the held blob `hash`.
|
||||
pub(crate) fn full_record(&self, hash: &BlobHash) -> Option<Vec<u8>> {
|
||||
Some(full_record(self.bytes.get(hash)?))
|
||||
}
|
||||
|
||||
/// Drop a blob whose record never got written.
|
||||
pub(crate) fn forget(&mut self, hash: &BlobHash) {
|
||||
self.bytes.remove(hash);
|
||||
self.delta_records.remove(hash);
|
||||
}
|
||||
|
||||
/// Read and decode the record of `hash` and the records of its bases. Each blob is checked against its hash.
|
||||
pub(crate) async fn load(&mut self, hash: BlobHash, working: &AnyContainer, layout: &impl Layout) -> Result<(), String> {
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Follow the bases down to a held blob or a full record, then apply the deltas in reverse
|
||||
let mut deltas = Vec::new();
|
||||
let mut visited = HashSet::new();
|
||||
let mut current = hash;
|
||||
let mut bytes = loop {
|
||||
if let Some(bytes) = self.bytes.get(¤t) {
|
||||
break bytes.clone();
|
||||
}
|
||||
if !visited.insert(current) {
|
||||
return Err(format!("Blob {hash} sits on a chain that loops back to {current}"));
|
||||
}
|
||||
|
||||
let record = working.read(&layout.blob_path(¤t)).await.map_err(|error| format!("Blob {current} could not be read: {error}"))?;
|
||||
let record = record.as_slice().to_vec();
|
||||
match decode_record(&record).ok_or_else(|| format!("Blob {current} has a malformed record"))? {
|
||||
Record::Full(bytes) => {
|
||||
let bytes = bytes.to_vec();
|
||||
self.hold_checked(current, bytes.clone(), record)?;
|
||||
break bytes;
|
||||
}
|
||||
Record::Delta { base, delta } => {
|
||||
deltas.push((current, delta.to_vec(), record));
|
||||
current = base;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (hash, delta, record) in deltas.into_iter().rev() {
|
||||
bytes = apply_copy_delta(&bytes, &delta).ok_or_else(|| format!("Blob {hash} has a malformed delta"))?;
|
||||
self.hold_checked(hash, bytes.clone(), record)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hold_checked(&mut self, hash: BlobHash, bytes: Vec<u8>, record: Vec<u8>) -> Result<(), String> {
|
||||
if BlobHash::of(&bytes) != hash {
|
||||
return Err(format!("Blob {hash} decodes to bytes of a different hash"));
|
||||
}
|
||||
|
||||
self.bytes.insert(hash, bytes);
|
||||
if record.first() == Some(&DELTA) {
|
||||
self.delta_records.insert(hash, record);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `hash` and the chain of bases that `base_of` returns, deepest base first. Stops if the chain loops.
|
||||
fn chain_to(hash: BlobHash, base_of: impl Fn(&BlobHash) -> Option<BlobHash>) -> Vec<BlobHash> {
|
||||
let mut chain = vec![hash];
|
||||
let mut visited = HashSet::from([hash]);
|
||||
while let Some(base) = chain.last().and_then(&base_of)
|
||||
&& visited.insert(base)
|
||||
{
|
||||
chain.push(base);
|
||||
}
|
||||
chain.reverse();
|
||||
chain
|
||||
}
|
||||
|
||||
/// The base hash and the payload of a delta record.
|
||||
fn split_delta_record(record: &[u8]) -> Option<(BlobHash, &[u8])> {
|
||||
let (&DELTA, rest) = record.split_first()? else { return None };
|
||||
let (base, delta) = rest.split_first_chunk::<32>()?;
|
||||
Some((BlobHash(ResourceHash::from(*base)), delta))
|
||||
}
|
||||
|
||||
/// The base hash of a delta record.
|
||||
#[cfg(feature = "network")]
|
||||
fn record_base(record: &[u8]) -> Option<BlobHash> {
|
||||
split_delta_record(record).map(|(base, _)| base)
|
||||
}
|
||||
|
||||
enum Record<'a> {
|
||||
Full(&'a [u8]),
|
||||
Delta { base: BlobHash, delta: &'a [u8] },
|
||||
}
|
||||
|
||||
fn full_record(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut record = vec![FULL];
|
||||
record.extend_from_slice(bytes);
|
||||
record
|
||||
}
|
||||
|
||||
fn delta_record(base: BlobHash, base_bytes: &[u8], bytes: &[u8]) -> Vec<u8> {
|
||||
let mut record = vec![DELTA];
|
||||
record.extend_from_slice(&<[u8; 32]>::from(&base.0));
|
||||
record.extend(copy_delta(base_bytes, bytes));
|
||||
record
|
||||
}
|
||||
|
||||
fn decode_record(record: &[u8]) -> Option<Record<'_>> {
|
||||
match *record.first()? {
|
||||
FULL => Some(Record::Full(&record[1..])),
|
||||
DELTA => split_delta_record(record).map(|(base, delta)| Record::Delta { base, delta }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// A copy delta is a list of COPY and INSERT operations. COPY takes a byte range from the base. INSERT carries new bytes.
|
||||
// Like git's delta encoding, it indexes aligned blocks of the base and finds them at any offset in the target.
|
||||
const COPY_BLOCK: usize = 16;
|
||||
const COPY: u8 = 0;
|
||||
const INSERT: u8 = 1;
|
||||
|
||||
/// A delta that decodes to more bytes is rejected. A small delta from a peer could otherwise copy the same base range
|
||||
/// until it fills memory. This matches the peer transport's packet limit, so no larger blob could be sent in full.
|
||||
const MAX_BLOB_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Expected O(base + target) time. Each base block is indexed once and each unmatched target byte is looked up once.
|
||||
fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
let block_key = |bytes: &[u8]| -> u128 {
|
||||
let mut key = [0; COPY_BLOCK];
|
||||
key.copy_from_slice(&bytes[..COPY_BLOCK]);
|
||||
u128::from_le_bytes(key)
|
||||
};
|
||||
|
||||
let mut index = HashMap::new();
|
||||
for offset in (0..base.len().saturating_sub(COPY_BLOCK - 1)).step_by(COPY_BLOCK) {
|
||||
index.entry(block_key(&base[offset..])).or_insert(offset);
|
||||
}
|
||||
|
||||
let mut output = Vec::new();
|
||||
let mut literal_start = 0;
|
||||
let mut position = 0;
|
||||
while position + COPY_BLOCK <= target.len() {
|
||||
let Some(&base_offset) = index.get(&block_key(&target[position..])) else {
|
||||
position += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
// A match can start before the aligned block, so also extend it backward into the pending literal
|
||||
let backward = base[..base_offset].iter().rev().zip(target[literal_start..position].iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let forward = base[base_offset..].iter().zip(&target[position..]).take_while(|(a, b)| a == b).count();
|
||||
|
||||
push_insert(&mut output, &target[literal_start..position - backward]);
|
||||
output.push(COPY);
|
||||
push_varint(&mut output, base_offset - backward);
|
||||
push_varint(&mut output, backward + forward);
|
||||
|
||||
position += forward;
|
||||
literal_start = position;
|
||||
}
|
||||
push_insert(&mut output, &target[literal_start..]);
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
fn apply_copy_delta(base: &[u8], mut delta: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut output = Vec::new();
|
||||
while let Some((&operation, rest)) = delta.split_first() {
|
||||
delta = rest;
|
||||
match operation {
|
||||
COPY => {
|
||||
let offset = read_varint(&mut delta)?;
|
||||
let length = read_varint(&mut delta)?;
|
||||
if output.len().checked_add(length)? > MAX_BLOB_BYTES {
|
||||
return None;
|
||||
}
|
||||
output.extend_from_slice(base.get(offset..offset.checked_add(length)?)?);
|
||||
}
|
||||
INSERT => {
|
||||
let length = read_varint(&mut delta)?;
|
||||
let (literal, rest) = delta.split_at_checked(length)?;
|
||||
output.extend_from_slice(literal);
|
||||
delta = rest;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
fn push_insert(output: &mut Vec<u8>, literal: &[u8]) {
|
||||
if literal.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
output.push(INSERT);
|
||||
push_varint(output, literal.len());
|
||||
output.extend_from_slice(literal);
|
||||
}
|
||||
|
||||
fn push_varint(output: &mut Vec<u8>, mut value: usize) {
|
||||
while value >= 0x80 {
|
||||
output.push(value as u8 | 0x80);
|
||||
value >>= 7;
|
||||
}
|
||||
output.push(value as u8);
|
||||
}
|
||||
|
||||
fn read_varint(delta: &mut &[u8]) -> Option<usize> {
|
||||
let mut value = 0;
|
||||
for shift in (0..usize::BITS).step_by(7) {
|
||||
let (&byte, rest) = delta.split_first()?;
|
||||
*delta = rest;
|
||||
value |= ((byte & 0x7f) as usize).checked_shl(shift)?;
|
||||
if byte < 0x80 {
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hashed(bytes: &[u8]) -> (BlobHash, Vec<u8>) {
|
||||
(BlobHash::of(bytes), bytes.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_delta_round_trips() {
|
||||
let base: Vec<u8> = (0..4096_u32).flat_map(|i| (i * 7).to_le_bytes()).collect();
|
||||
let mut target = base.clone();
|
||||
target.splice(100..108, [1, 2, 3]);
|
||||
target[9000] ^= 0xff;
|
||||
target.extend_from_slice(b"tail");
|
||||
|
||||
let delta = copy_delta(&base, &target);
|
||||
assert!(delta.len() < 200, "a few edits encode as a small delta, got {} bytes", delta.len());
|
||||
assert_eq!(apply_copy_delta(&base, &delta).unwrap(), target);
|
||||
assert_eq!(apply_copy_delta(&[], ©_delta(&[], &target)).unwrap(), target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_decode_to_what_was_inserted() {
|
||||
let mut store = BlobStore::default();
|
||||
let (base_hash, base) = hashed(&[7; 2048]);
|
||||
let mut changed = base.clone();
|
||||
changed[1000] = 0;
|
||||
let (changed_hash, changed) = hashed(&changed);
|
||||
|
||||
let full = store.insert(base_hash, base.clone(), None).unwrap();
|
||||
let delta = store.insert(changed_hash, changed.clone(), Some(base_hash)).unwrap();
|
||||
assert!(store.insert(changed_hash, changed.clone(), Some(base_hash)).is_none(), "a held blob writes nothing");
|
||||
|
||||
assert!(matches!(decode_record(&full), Some(Record::Full(bytes)) if bytes == base));
|
||||
let Some(Record::Delta { base: decoded_base, delta }) = decode_record(&delta) else {
|
||||
panic!("a delta record")
|
||||
};
|
||||
assert_eq!(decoded_base, base_hash);
|
||||
assert_eq!(apply_copy_delta(&base, delta).unwrap(), changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_deltas_are_rejected() {
|
||||
assert!(apply_copy_delta(b"short", &[COPY, 0, 10]).is_none());
|
||||
assert!(apply_copy_delta(b"", &[INSERT, 5, 1]).is_none());
|
||||
assert!(apply_copy_delta(b"", &[9]).is_none());
|
||||
|
||||
let base = vec![0; 1024 * 1024];
|
||||
let mut expanding = Vec::new();
|
||||
for _ in 0..=MAX_BLOB_BYTES / base.len() {
|
||||
expanding.push(COPY);
|
||||
push_varint(&mut expanding, 0);
|
||||
push_varint(&mut expanding, base.len());
|
||||
}
|
||||
assert!(apply_copy_delta(&base, &expanding).is_none(), "a delta past the size limit is rejected");
|
||||
assert!(decode_record(&[DELTA, 1, 2]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -58,4 +58,8 @@ pub enum Error {
|
||||
#[cfg(feature = "network")]
|
||||
#[error("network error: {0}")]
|
||||
Network(#[from] peer_transport::PacketError),
|
||||
/// The room knows this device by its peer, so the user can't change.
|
||||
#[cfg(feature = "network")]
|
||||
#[error("the user cannot change while the document is connected")]
|
||||
UserChangeWhileConnected,
|
||||
}
|
||||
@@ -181,6 +181,19 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
export_session.embed_resource_sources(links_to_promote)?;
|
||||
|
||||
// If the export includes history, also embed every resource referenced by the history.
|
||||
if options.include_history {
|
||||
let current: std::collections::HashSet<ResourceHash> = export_session.registry().resources.values().filter_map(|entry| entry.hash).collect();
|
||||
for hash in export_session.all_referenced_resource_hashes() {
|
||||
if current.contains(&hash) || working_copy_hashes.contains(&hash) {
|
||||
continue;
|
||||
}
|
||||
if let Some(resource) = byte_store.load(hash).await {
|
||||
embedded_bytes.push((hash, resource));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let mut session_state = self.exported_session_state(&export_session);
|
||||
|
||||
@@ -234,18 +247,33 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
}
|
||||
|
||||
// Every resource in path order, whether its bytes sit in the working copy or come from the byte store, so where
|
||||
// they sat does not change the archive. `None` marks bytes the working copy already holds.
|
||||
let mut resources: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let resources_dir = self.layout.resources_dir();
|
||||
if self.working.list_dirs("").await?.iter().any(|d| d == resources_dir) {
|
||||
resources.extend(self.working.list(resources_dir).await?.into_iter().map(|path| (path, None)));
|
||||
// Every resource and blob record in path order. The archive is the same wherever the bytes are stored.
|
||||
// `None` marks bytes the working copy already holds.
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
resources.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
for (path, resource) in resources {
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
}
|
||||
}
|
||||
None if has_directory(self.layout.blobs_dir()) => {
|
||||
entries.extend(self.working.list(self.layout.blobs_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
for (path, resource) in entries {
|
||||
if let Some(resource) = resource {
|
||||
sink.write_entry(&path, resource.as_ref())?;
|
||||
continue;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! read/write call site. Working-copy creation, exports, and migrations may all hit the same
|
||||
//! basename with different codecs.
|
||||
|
||||
use document_graph_storage::BlobHash;
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
pub trait Layout: Send + Sync {
|
||||
@@ -15,6 +16,10 @@ pub trait Layout: Send + Sync {
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The directory of blob records.
|
||||
fn blobs_dir(&self) -> &str;
|
||||
/// The path of one blob record.
|
||||
fn blob_path(&self, hash: &BlobHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
/// new format can be validated against (and recovered from) the old one. Dropped once `.gdd`
|
||||
/// becomes the sole source of truth.
|
||||
@@ -51,6 +56,12 @@ impl Layout for GddV1Layout {
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String {
|
||||
format!("{}/{hash}", self.resources_dir())
|
||||
}
|
||||
fn blobs_dir(&self) -> &str {
|
||||
"blobs"
|
||||
}
|
||||
fn blob_path(&self, hash: &BlobHash) -> String {
|
||||
format!("{}/{hash}", self.blobs_dir())
|
||||
}
|
||||
fn legacy_path(&self) -> &str {
|
||||
"legacy.graphite"
|
||||
}
|
||||
|
||||
+68
-11
@@ -24,6 +24,7 @@ use document_graph_storage::{HistoryMetadata, MetadataFact, PeerId, Registry, Se
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::{ResourceHash, ResourceStorage};
|
||||
|
||||
mod blob_store;
|
||||
pub mod codec;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
@@ -47,6 +48,8 @@ pub use layout::{GddV1Layout, Layout};
|
||||
pub use manifest::{Manifest, PayloadCodecs};
|
||||
pub use resource::ResourceProxy;
|
||||
|
||||
use blob_store::BlobStore;
|
||||
|
||||
/// The default [`Layout`], so callers write `GddV1` for the common `Gdd<GddV1Layout>` handle.
|
||||
pub type GddV1 = Gdd<GddV1Layout>;
|
||||
|
||||
@@ -94,6 +97,7 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) manifest: Manifest,
|
||||
/// See [`HistoryMetadata`].
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
pub(crate) wall_clock_ms: Option<f64>,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
@@ -103,17 +107,44 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) migrated: bool,
|
||||
/// Where resource bytes live. `None` means the working copy's own content-addressed store.
|
||||
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
|
||||
/// Every blob the document names.
|
||||
pub(crate) blobs: BlobStore,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// What changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
pub(crate) remote_changes: RemoteChanges,
|
||||
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
|
||||
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
/// Whether the document belongs in its room, persisted so a reopen reconnects.
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
|
||||
/// Changes to the working registry that the runtime mirror has not seen yet, such as peer edits and undos of retired
|
||||
/// steps. The mirror reconciles just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: document_graph_storage::Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole-file rewrites deferred to the end of a poll, so a batch of remote packets costs one rewrite per file.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
@@ -139,9 +170,14 @@ impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
Self {
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
byte_store: self.byte_store.clone(),
|
||||
blobs: self.blobs.clone(),
|
||||
migrated: self.migrated,
|
||||
shared: self.shared,
|
||||
interactions_seen: self.interactions_seen.clone(),
|
||||
own_last_staged_ms: self.own_last_staged_ms,
|
||||
own_staged_since_tick: self.own_staged_since_tick,
|
||||
..Self::assemble(self.session.clone(), self.working.clone(), self.layout.clone(), self.manifest.clone(), self.metadata.clone())
|
||||
}
|
||||
}
|
||||
@@ -156,16 +192,21 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
metadata,
|
||||
wall_clock_ms: None,
|
||||
view_settings: Default::default(),
|
||||
network_view_settings: Default::default(),
|
||||
byte_store: None,
|
||||
blobs: BlobStore::default(),
|
||||
migrated: false,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
remote_changes: RemoteChanges::default(),
|
||||
undo_requested: None,
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
@@ -186,10 +227,10 @@ impl<L: Layout + Default> Gdd<L> {
|
||||
|
||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||
let layout = L::default();
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
||||
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +261,11 @@ impl<L: Layout> Gdd<L> {
|
||||
Self::open_in_with(working, layout, byte_store, host).await
|
||||
}
|
||||
|
||||
/// Reads the manifest without opening the copy, which may be another writer's.
|
||||
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
|
||||
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
|
||||
}
|
||||
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
@@ -251,7 +297,7 @@ impl<L: Layout> Gdd<L> {
|
||||
#[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)?;
|
||||
let (format_outcome, migrated_blobs) = migrate::migrate_format(&mut records, codecs, manifest.format_version)?.unzip();
|
||||
#[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")]
|
||||
@@ -326,6 +372,13 @@ impl<L: Layout> Gdd<L> {
|
||||
..Self::assemble(session, working, layout, manifest, metadata)
|
||||
};
|
||||
|
||||
#[cfg(feature = "migrations")]
|
||||
if let Some(blobs) = migrated_blobs {
|
||||
gdd.keep_blobs_durably(blobs).await?;
|
||||
}
|
||||
// Node migrations read values stored in blobs, so load them first
|
||||
gdd.load_blobs().await;
|
||||
|
||||
#[cfg(feature = "migrations")]
|
||||
{
|
||||
let migrated_nodes = gdd.migrate_nodes(inputs.byte_store, inputs.host).await?;
|
||||
@@ -344,18 +397,18 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||
/// the manifest and writes each payload with its recorded codec.
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
user_id: user,
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &Sorted(&session_state))?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
let session = Session::with_identity(peer, user);
|
||||
io::write_single(&working, layout.registry_basename(), codecs.registry, &Sorted(session.registry()))?;
|
||||
|
||||
Ok(Self::assemble(session, working, layout, manifest, HistoryMetadata::default()))
|
||||
@@ -450,6 +503,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.session.all_referenced_resource_hashes()
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> std::collections::HashSet<ResourceHash> {
|
||||
self.session.resource_gc_roots()
|
||||
}
|
||||
|
||||
/// Drop the session and return the working-copy container + layout.
|
||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||
(self.working, self.layout)
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC
|
||||
pub const FORMAT_MAGIC: &str = "gdd";
|
||||
|
||||
/// Newest format version this build can open, which older documents migrate to. `cargo run migration snapshot` bumps it when the stored types change.
|
||||
pub const SUPPORTED_FORMAT_VERSION: u32 = 3;
|
||||
pub const SUPPORTED_FORMAT_VERSION: u32 = 4;
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_container::AsyncContainer;
|
||||
use document_graph_storage::BlobHash;
|
||||
use document_graph_storage::blob::NewBlobs;
|
||||
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
|
||||
use graphene_resource::LoadResource;
|
||||
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec};
|
||||
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
|
||||
use migration_runner::{DocumentPayloads, HistoryOutcome, MigrationBlobs, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
@@ -16,7 +18,7 @@ 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> {
|
||||
pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs, format_version: u32) -> Result<Option<(HistoryOutcome, NewBlobs)>, Error> {
|
||||
if format_version >= SUPPORTED_FORMAT_VERSION {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -28,6 +30,7 @@ pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs,
|
||||
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)),
|
||||
..Default::default()
|
||||
};
|
||||
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}");
|
||||
@@ -40,7 +43,11 @@ pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs,
|
||||
records.hot_log = payloads.hot_log.into_iter().map(|payload| payload.bytes).collect();
|
||||
records.session = payloads.session.map(|payload| payload.bytes);
|
||||
|
||||
Ok(Some(outcome))
|
||||
let blobs = NewBlobs {
|
||||
bytes: payloads.blobs.into_iter().map(|(hash, bytes)| (BlobHash(hash), bytes)).collect(),
|
||||
bases: payloads.blob_bases.into_iter().map(|(hash, base)| (BlobHash(hash), BlobHash(base))).collect(),
|
||||
};
|
||||
Ok(Some((outcome, blobs)))
|
||||
}
|
||||
|
||||
/// The facts in `metadata` with their revs mapped by `remap`, which drops the facts of a rev it has no answer for.
|
||||
@@ -91,14 +98,16 @@ impl<L: Layout> Gdd<L> {
|
||||
// Hot ops join history first, so they migrate with it
|
||||
self.session.retire_all()?;
|
||||
|
||||
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host)?;
|
||||
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host) {
|
||||
let mut blobs = MigrationBlobs::new(&self.blobs.bytes);
|
||||
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host, &mut blobs)?;
|
||||
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host, &mut blobs) {
|
||||
Ok(rewritten) => rewritten,
|
||||
Err(error) => {
|
||||
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
|
||||
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
|
||||
}
|
||||
};
|
||||
self.keep_blobs_durably(blobs.into_added()).await?;
|
||||
|
||||
// Declarations the migrations introduced need their bytes next to the other resources
|
||||
let referenced = self.session.all_declaration_resources();
|
||||
@@ -156,10 +165,11 @@ impl<L: Layout> Gdd<L> {
|
||||
migrated: &Registry,
|
||||
resolver: &DocumentDeclarations,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<(Session, HistoryMetadata), RunnerError> {
|
||||
let history: Vec<Delta> = self.session.history().cloned().collect();
|
||||
let cursors = self.session.head_rev().into_iter().chain(self.session.redo_stack().iter().copied());
|
||||
let rewritten = migrate_history(migrations, history, resolver, host, cursors)?;
|
||||
let rewritten = migrate_history(migrations, history, resolver, host, cursors, blobs)?;
|
||||
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
|
||||
|
||||
let head = self.session.head_rev().and_then(remap);
|
||||
|
||||
@@ -4,52 +4,16 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::{CrdtError, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, Touched, UserId};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
use document_container::AsyncContainer;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use document_graph_storage::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, UserId};
|
||||
use peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::{Gdd, PendingPersist};
|
||||
|
||||
/// What peers changed in the working registry since it was last taken, so a runtime mirror can reconcile
|
||||
/// just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and publish it, recording what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
/// Host this document's room, and remember it is shared so a reopen reconnects.
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
@@ -86,6 +50,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Drop the connection but keep the document shared, so a reopen reconnects. A host first retires every closed
|
||||
/// interaction with no ops still on their way.
|
||||
pub fn disconnect(&mut self) {
|
||||
self.undo_requested = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
if let Err(error) = self.retire_interactions(&closed) {
|
||||
log::error!("Retiring before leaving failed: {error}");
|
||||
@@ -124,6 +89,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.network.iter().flat_map(|replica| replica.peers())
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.session.mark_runtime_current();
|
||||
}
|
||||
|
||||
pub fn poll_peers(&mut self) -> Vec<Event> {
|
||||
let Some(mut replica) = self.network.take() else { return Vec::new() };
|
||||
let events = replica.poll(self);
|
||||
@@ -365,12 +334,40 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Also includes missing blobs. They are fetched in full like resources.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.unstored_resources().into_iter().collect()
|
||||
let missing_blobs = self.session.all_blob_hashes().into_iter().filter(|hash| !self.blobs.bytes.contains_key(hash));
|
||||
self.unstored_resources().into_iter().chain(missing_blobs.map(ResourceHash::from)).collect()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
self.blobs.bytes.get(&BlobHash(hash)).cloned()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let blob = BlobHash(hash);
|
||||
if self.session.names_blob(blob) {
|
||||
let bytes = BlobBytes::from([(blob, bytes.to_vec())]);
|
||||
self.keep_blobs(NewBlobs { bytes, ..Default::default() })?;
|
||||
return Ok(());
|
||||
}
|
||||
self.hold_resource(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn blob_records(&self) -> Vec<BlobRecord> {
|
||||
self.blobs.records().into_iter().map(|(hash, record)| BlobRecord { hash, record }).collect()
|
||||
}
|
||||
|
||||
fn absorb_blob_records(&mut self, records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
let held = self.blobs.absorb(records.into_iter().map(|BlobRecord { hash, record }| (hash, record)).collect());
|
||||
for (index, (hash, record)) in held.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Forget the unwritten blobs so that they are asked for again
|
||||
held[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+246
-16
@@ -4,9 +4,12 @@
|
||||
//! surface absorbs durability.
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, Sorted, Subject, TimeStamp, Value, WallStamp};
|
||||
use document_graph_storage::from_runtime::RuntimeConversion;
|
||||
use document_graph_storage::{BlobHash, CrdtError, Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource, Registry};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -14,7 +17,7 @@ use crate::SessionState;
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, encode_facts, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, RemoteChanges, encode_facts, io};
|
||||
|
||||
/// Written after every staged payload, so its presence means the whole rewrite is ready to move into place.
|
||||
const STAGING_COMMITTED: &str = "committed";
|
||||
@@ -65,6 +68,21 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some() {
|
||||
return Err(Error::UserChangeWhileConnected);
|
||||
}
|
||||
let closing = self.session.set_user(user, peer)?;
|
||||
self.own_last_staged_ms = None;
|
||||
self.persist_staged(&closing, Vec::new())?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Edit the cached manifest and persist it. Always JSON, synchronous.
|
||||
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
|
||||
edit(&mut self.manifest);
|
||||
@@ -91,16 +109,27 @@ impl<L: Layout> Gdd<L> {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
let RuntimeConversion {
|
||||
registry,
|
||||
blob_bytes,
|
||||
declaration_bytes,
|
||||
declarations,
|
||||
..
|
||||
} = Registry::convert_from_runtime(network, metadata, resources, self.session.peer()).map_err(CommitError::from)?;
|
||||
|
||||
// The converted registry already names its large values as blobs
|
||||
let ops = self.session.runtime_diff(®istry);
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
let hot_ops = self.session.stage_runtime_diff(ops, registry)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blob_bytes, bases })?;
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in conversion.declaration_bytes.values() {
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(conversion.declarations)
|
||||
Ok(declarations)
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
@@ -122,21 +151,37 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff.
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff. Large input values become blobs.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops.into_iter().collect())?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
let mut ops: Vec<_> = ops.into_iter().collect();
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blobs, bases })?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them.
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
/// Write the records of new blobs, then persist the hot frames that name them.
|
||||
fn persist_with_blobs(&mut self, hot_ops: &[HotOp], blobs: NewBlobs) -> Result<(), Error> {
|
||||
let records = self.keep_blobs(blobs)?;
|
||||
self.persist_staged(hot_ops, records)
|
||||
}
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them together with their new blob records.
|
||||
#[cfg_attr(not(feature = "network"), expect(unused_variables, reason = "only peers receive the blob records"))]
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp], blobs: Vec<(BlobHash, Vec<u8>)>) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
let blobs = blobs.into_iter().map(|(hash, record)| peer_transport::BlobRecord { hash, record }).collect();
|
||||
replica.broadcast_hot_ops(hot_ops, blobs)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -183,7 +228,7 @@ impl<L: Layout> Gdd<L> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
replica.broadcast_hot_ops(hot_ops, Vec::new())?;
|
||||
}
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -368,17 +413,200 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many closed interactions wait before they retire. Retiring later merges more of a gesture into one delta.
|
||||
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
|
||||
/// Gives every peer time to see the whole interaction.
|
||||
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
|
||||
/// The longest anything waits, so quiet sessions and interactions with gaps still retire.
|
||||
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
|
||||
|
||||
/// Close this peer's open interaction, if any, with a marker staged like any other hot op.
|
||||
pub fn end_interaction(&mut self) -> Result<(), Error> {
|
||||
let staged = self.session.end_interaction()?;
|
||||
self.persist_staged(&staged)?;
|
||||
self.persist_staged(&staged, Vec::new())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(retraction) = self.session.retract_interaction()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.own_last_staged_ms = None;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
self.remote_changes.touched.extend(retraction.touched);
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&retraction.ids)?;
|
||||
}
|
||||
Ok(Some(retraction.ops))
|
||||
}
|
||||
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
if !self.can_change_line() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A peer promoted to host drops the step itself, so an unanswered request no longer blocks it
|
||||
let asked = (!self.retires_locally()).then_some((rev, self.session.head_rev()));
|
||||
if asked.is_some() && self.undo_requested == asked {
|
||||
return Ok(None);
|
||||
}
|
||||
self.drop_step(rev)?;
|
||||
self.undo_requested = asked;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
pub fn can_change_line(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.as_ref().is_some_and(|replica| replica.has_host()) {
|
||||
return true;
|
||||
}
|
||||
self.retires_locally()
|
||||
}
|
||||
|
||||
/// Drop a retired interaction from the line. A non-retiring peer asks the retirer.
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = moved;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_move(rev)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let deltas = self.restore_dropped_interaction(rev)?;
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = deltas;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and record what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
// Only the deltas peers will see are published, so a local redo stays silently undoable
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
fn persist_rewritten_line(&mut self) -> Result<(), Error> {
|
||||
self.rewrite_history()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Stage retracted ops as a new interaction. They count as remote changes.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
|
||||
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
|
||||
self.wall_clock_ms = Some(now_ms);
|
||||
// Close a quiet interaction only between steps, so a pause doesn't split a gesture
|
||||
if self.own_staged_since_tick {
|
||||
self.own_staged_since_tick = false;
|
||||
self.own_last_staged_ms = Some(now_ms);
|
||||
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let closed = self.session.closed_interactions();
|
||||
let mut seen = std::mem::take(&mut self.interactions_seen);
|
||||
let mut due = Vec::new();
|
||||
let mut oldest_age: f64 = 0.0;
|
||||
for interaction in &closed {
|
||||
let Some(&marker) = interaction.ops.last() else { continue };
|
||||
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
|
||||
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
|
||||
due.push(interaction.clone());
|
||||
oldest_age = oldest_age.max(age);
|
||||
}
|
||||
}
|
||||
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
|
||||
self.interactions_seen = seen;
|
||||
|
||||
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
|
||||
self.retire_interactions(&due)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one with no ops still on their way, whoever authored
|
||||
/// it. A peer that does not retire only closes its own.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
self.retire_interactions(&closed)
|
||||
}
|
||||
@@ -414,8 +642,10 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Publish and persist freshly retired deltas, then broadcast them with the hot ops they retired.
|
||||
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
|
||||
if let Some(wall_ms) = self.wall_clock_ms {
|
||||
self.session.stamp_retired_at(new_revs, wall_ms as u64);
|
||||
}
|
||||
// Deltas peers hold are published, so undo past them moves the shared head instead of rewinding.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
|
||||
@@ -7,6 +7,8 @@ use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use document_graph_storage::BlobHash;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use graphene_resource::ResourceFuture;
|
||||
use graphene_resource::{LoadResource, Resource, ResourceHash, ResourceStorage};
|
||||
|
||||
@@ -124,6 +126,45 @@ impl<L: Layout> Gdd<L> {
|
||||
pub(crate) fn unstored_resources(&self) -> Vec<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
|
||||
}
|
||||
|
||||
/// The decoded bytes of every blob the document names.
|
||||
pub fn blobs(&self) -> &BlobBytes {
|
||||
&self.blobs.bytes
|
||||
}
|
||||
|
||||
/// Hold staged blobs and queue their records before the hot frames that name them.
|
||||
/// Returns the records so peers can receive them with the ops.
|
||||
pub(crate) fn keep_blobs(&mut self, blobs: NewBlobs) -> Result<Vec<(BlobHash, Vec<u8>)>, ContainerError> {
|
||||
let records = self.blobs.insert_all(blobs);
|
||||
|
||||
for (index, (hash, record)) in records.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Forget the unwritten blobs so that staging them again writes them
|
||||
records[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
/// Like [`keep_blobs`](Self::keep_blobs), but waits until the records are written.
|
||||
/// A migration needs this before it replaces the old records.
|
||||
#[cfg(feature = "migrations")]
|
||||
pub(crate) async fn keep_blobs_durably(&mut self, blobs: NewBlobs) -> Result<(), ContainerError> {
|
||||
for (hash, record) in self.blobs.insert_all(blobs) {
|
||||
self.working.write(&self.layout.blob_path(&hash), &record).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode every blob the document names. This includes blobs of history states the cursor can move to.
|
||||
pub(crate) async fn load_blobs(&mut self) {
|
||||
for hash in self.session.all_blob_hashes() {
|
||||
if let Err(error) = self.blobs.load(hash, &self.working, &self.layout).await {
|
||||
log::error!("{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{ExportFormat, ExportOptions, GddV1, GddV1Layout};
|
||||
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, to_value};
|
||||
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, UserId, to_value};
|
||||
use graph_craft::application_io::resource::{HashMapResourceStorage, ResourceStorage};
|
||||
use graphene_resource::DataSource;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -16,7 +16,7 @@ const LATEST: TimeStamp = TimeStamp {
|
||||
};
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Networks and nodes, some of each removed again, plus link-only resources whose bytes sit in the byte store.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// History metadata has its own file, travels in exports and merges across copies.
|
||||
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{GddV1, GddV1Layout, Layout};
|
||||
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, Subject, TimeStamp, UserId, rev_attr, user_attr};
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
const ADA: Subject = Subject::User(UserId(10));
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
fn document(peer: u64, user: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Let the room settle through greetings, the sync handshake and whatever was broadcast.
|
||||
@@ -24,49 +25,76 @@ fn settle(network: &mut peer_transport::mock::MockNetwork, peers: &mut [&mut Gdd
|
||||
}
|
||||
}
|
||||
|
||||
fn document_naming_ada() -> GddV1 {
|
||||
let mut gdd = document(1);
|
||||
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
gdd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_facts_survive_a_reopen() {
|
||||
fn a_recorded_name_survives_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document_naming_ada();
|
||||
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
|
||||
let mut gdd = document(1, 10);
|
||||
assert!(gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
assert!(
|
||||
!gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
|
||||
"the same name is no change"
|
||||
);
|
||||
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
assert!(gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
|
||||
assert!(gdd.record(Subject::Rev(step), "tag:v1", true.into(), NOW_MS).expect("record"));
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
|
||||
|
||||
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
|
||||
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
fn recording_an_unchanged_value_writes_nothing() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = document_naming_ada();
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
|
||||
}
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let metadata = gdd.metadata().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
let before = working.read(&path).await.expect("read").as_slice().to_vec();
|
||||
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert!(!reopened.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"));
|
||||
assert_eq!(reopened.metadata(), &metadata);
|
||||
let (working, _) = reopened.into_storage();
|
||||
assert_eq!(working.read(&path).await.expect("read").as_slice().trim_ascii(), before.trim_ascii());
|
||||
});
|
||||
}
|
||||
|
||||
/// A line that doesn't decode is skipped, so a torn write can't block opening.
|
||||
#[test]
|
||||
fn an_unreadable_metadata_line_is_skipped() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working
|
||||
.append_non_blocking(
|
||||
&path,
|
||||
b"{\"subject\":{\"Branch\":3},\"key\":\"name\",\"value\":1,\"stamp\":{\"ms\":1,\"peer\":1}}\n{\"subject\":{\"User\":",
|
||||
)
|
||||
.expect("append");
|
||||
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
futures::executor::block_on(async {
|
||||
let (working, layout) = document_naming_ada().into_storage();
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
|
||||
|
||||
@@ -82,29 +110,75 @@ fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
#[cfg(feature = "network")]
|
||||
#[test]
|
||||
fn names_reach_the_room_with_the_sync_and_as_they_change() {
|
||||
let mut host = document(1);
|
||||
let mut guest = document(2);
|
||||
host.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
// A name given before joining travels with the joiner and reaches the host.
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
futures::executor::block_on(async {
|
||||
let mut host = document(1, 10);
|
||||
let mut guest = document(2, 20);
|
||||
host.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
|
||||
let mut network = peer_transport::mock::MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
let mut network = peer_transport::mock::MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
|
||||
// A rename while in the room goes round on its own.
|
||||
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retirement_records_when_it_happened() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.retire_due(NOW_MS, true).expect("tick");
|
||||
|
||||
gdd.stage_ops([RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}])
|
||||
.expect("stage");
|
||||
let everything = TimeStamp {
|
||||
counter: u64::MAX,
|
||||
peer: PeerId(u64::MAX),
|
||||
};
|
||||
let revs = gdd.retire(everything).expect("retire");
|
||||
assert!(!revs.is_empty());
|
||||
for rev in revs {
|
||||
let delta = gdd.session().delta(rev).expect("retired delta");
|
||||
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history carries no facts, since they'd name missing revs.
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
let expected = include_history.then_some("Ada");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), expected, "include_history: {include_history}");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry, UserId};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
@@ -91,7 +91,7 @@ fn stored(nodes: &[(u64, &'static str)]) -> AnyContainer {
|
||||
|
||||
/// A document whose declaration bytes went to `store`, as the editor sends them to its global cache.
|
||||
fn stored_with_bytes_in(nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) -> AnyContainer {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
gdd.commit_from_runtime(&network_of(nodes), &NoMetadata, &ResourceRegistry::new(), store).unwrap();
|
||||
gdd.into_storage().0
|
||||
}
|
||||
@@ -143,7 +143,7 @@ fn declarations_come_from_the_container_when_the_cache_lacks_them() {
|
||||
let nodes = [(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")];
|
||||
|
||||
// An archive carries its declarations in the container, which a device's cache hasn't seen yet
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
gdd.commit_from_runtime(&network_of(&nodes), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||
.unwrap();
|
||||
for (_, identifier) in nodes {
|
||||
|
||||
@@ -31,7 +31,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
|
||||
}
|
||||
|
||||
fn create() -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
}
|
||||
|
||||
fn commit(gdd: &mut GddV1, nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) {
|
||||
@@ -79,7 +79,7 @@ fn a_migration_on_disk_leaves_no_staging_behind() {
|
||||
block_on(async {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("document");
|
||||
let mut gdd = GddV1::create(&path, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create(&path, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
commit(&mut gdd, &[(1, FADE)], &HashMapResourceStorage::new());
|
||||
drop(gdd);
|
||||
|
||||
@@ -259,7 +259,7 @@ fn reopening_with_an_undone_implementation_swap_can_redo() {
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
let declarations = reopened.declarations(&store).await;
|
||||
reopened.redo().unwrap();
|
||||
let converted = reopened.registry().to_runtime_with_full_metadata(&declarations);
|
||||
let converted = reopened.registry().to_runtime_with_full_metadata(&declarations, reopened.blobs());
|
||||
assert!(converted.is_ok(), "{}", converted.err().unwrap());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
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 document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, UserId};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
@@ -28,7 +28,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
|
||||
}
|
||||
|
||||
fn create() -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
}
|
||||
|
||||
fn implementations(gdd: &GddV1) -> Vec<Implementation> {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
@@ -99,7 +99,7 @@ fn an_empty_registry_file_is_corrupt_rather_than_absent() {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let codec = gdd.manifest().codecs.registry;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
@@ -114,7 +114,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let codecs = gdd.manifest().codecs;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
@@ -135,7 +135,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
@@ -150,7 +150,7 @@ fn update_manifest_changes_visible_after_reopen() {
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||
// produces one network in the registry.
|
||||
@@ -177,7 +177,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||
let early = HotOp {
|
||||
@@ -225,7 +225,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Retire one op so there is a real retired rev to mark as published.
|
||||
let op = HotOp {
|
||||
@@ -256,7 +256,7 @@ fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
@@ -284,7 +284,7 @@ fn export_zip_round_trips_via_deserialize() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -309,7 +309,7 @@ fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
@@ -332,7 +332,7 @@ fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -362,7 +362,7 @@ fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -391,7 +391,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -415,7 +415,7 @@ fn export_carries_resources() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -443,7 +443,7 @@ fn embed_all_resources_materializes_link_only_resource() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||
// byte store; the working copy never holds them.
|
||||
@@ -508,7 +508,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||
let payload = b"embedded bytes in the cache";
|
||||
@@ -538,6 +538,46 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export with history carries the bytes of a resource only history still names, so undoing its removal
|
||||
/// after a reopen finds them, even when they live in the byte store rather than the working copy.
|
||||
#[test]
|
||||
fn export_with_history_carries_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"bytes of a removed resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let byte_store = empty_byte_store();
|
||||
byte_store.store(payload);
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
let id = ResourceId::new();
|
||||
resources.push_source_back(&id, DataSource::Embedded);
|
||||
resources.resolve(&id, hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
gdd.commit_from_runtime(&graph_craft::document::NodeNetwork::default(), &NoMetadata, &ResourceRegistry::new(), &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(!gdd.registry().resources.contains_key(&id), "the resource should only be named by history");
|
||||
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
|
||||
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&hash).await, "history-only bytes should travel with the export");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
@@ -549,7 +589,7 @@ fn export_round_trips_unretired_hot_ops() {
|
||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -602,7 +642,7 @@ fn open_in_rejects_future_format_version() {
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
@@ -623,7 +663,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
@@ -665,7 +705,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -718,7 +758,7 @@ fn declarations_round_trip_through_byte_store() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
@@ -729,7 +769,10 @@ fn declarations_round_trip_through_byte_store() {
|
||||
let declarations = gdd.declarations(&byte_store).await;
|
||||
assert_eq!(declarations.len(), 1, "expected one proto-node declaration resolved from the byte store");
|
||||
|
||||
let (converted, _entries) = gdd.registry().to_runtime_with_metadata(&declarations).unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
|
||||
let (converted, _entries) = gdd
|
||||
.registry()
|
||||
.to_runtime_with_metadata(&declarations, gdd.blobs())
|
||||
.unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
|
||||
|
||||
let node = converted.nodes.values().next().expect("converted network has the node");
|
||||
match &node.implementation {
|
||||
@@ -746,7 +789,7 @@ fn an_export_without_history_drops_tombstones() {
|
||||
use document_graph_storage::{Network, NetworkId, RegistryDelta};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let id = NetworkId(7);
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
attributes: Default::default(),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
@@ -80,28 +80,136 @@ fn a_reopen_continues_the_hot_op_sequence() {
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set(1)]).unwrap();
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = stage(&mut gdd, set(2));
|
||||
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let last = reopened.session().last_hot_sequence();
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_change_survives_a_reopen() {
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
let set = |key: &str| RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(24), UserId(240), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set("a")]).unwrap();
|
||||
gdd.retire_pending_interaction().unwrap();
|
||||
gdd.stage_ops([set("b")]).unwrap();
|
||||
|
||||
gdd.set_user(UserId(250), PeerId(25)).unwrap();
|
||||
let clock = gdd.session().clock_counter();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().peer(), PeerId(25));
|
||||
assert_eq!(reopened.session().user(), UserId(250));
|
||||
assert_eq!(reopened.session().clock_counter(), clock);
|
||||
|
||||
let staged = reopened.stage_ops([set("c")]).unwrap();
|
||||
assert!(staged.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(25) && hot_op.timestamp.counter > clock));
|
||||
assert_eq!(staged[0].sequence.0, 1, "the new peer's run starts over");
|
||||
reopened.retire_pending_interaction().unwrap();
|
||||
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
let session = reopened.session();
|
||||
assert!(session.hot_log().is_empty(), "the previous user's open step closed and retired");
|
||||
assert_eq!(session.user_of(PeerId(24)), Some(UserId(240)));
|
||||
assert_eq!(session.user_of(PeerId(25)), Some(UserId(250)));
|
||||
assert!(!session.is_mine(PeerId(24)));
|
||||
assert!(session.is_mine(PeerId(25)));
|
||||
let authors: Vec<PeerId> = session
|
||||
.history()
|
||||
.filter(|delta| matches!(delta.kind, RegistryDelta::ChangeDocumentAttribute { .. }))
|
||||
.map(|delta| delta.author)
|
||||
.collect();
|
||||
assert_eq!(authors, [PeerId(24), PeerId(24), PeerId(25)]);
|
||||
});
|
||||
}
|
||||
|
||||
/// Large input values are staged as blobs. An edit is stored as a delta against the previous value.
|
||||
/// Both the current state and an undone one survive a reopen and an archive round trip.
|
||||
#[test]
|
||||
fn blobs_resolve_after_a_reopen_and_an_archive_round_trip() {
|
||||
use document_container::AsyncContainer;
|
||||
use document_format::export::{ExportFormat, ExportOptions};
|
||||
use document_format::layout::Layout;
|
||||
use document_graph_storage::{NodeInput, RegistryDelta, Value, blob::BLOB_THRESHOLD};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
let original = TaggedValue::String("a".repeat(BLOB_THRESHOLD));
|
||||
let edited = TaggedValue::String(format!("b{}", "a".repeat(BLOB_THRESHOLD)));
|
||||
let mut network = network_with_one_node();
|
||||
network.nodes.get_mut(&NodeId(1)).unwrap().inputs = vec![graph_craft::document::NodeInput::value(original.clone(), false)];
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(26), UserId(26), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &store).unwrap();
|
||||
|
||||
// This op is not from a conversion, so the value stays inline until staging moves it into a blob
|
||||
let id = *gdd.registry().node_instances.keys().next().unwrap();
|
||||
let value = Value::from(serde_json::to_value(&edited).unwrap());
|
||||
let new_input = NodeInput::Value { value, exposed: false };
|
||||
gdd.stage_ops([RegistryDelta::ChangeNodeInput { id, index: 0, new_input }]).unwrap();
|
||||
gdd.retire_pending_interaction().unwrap();
|
||||
|
||||
let edited_blob = gdd.registry().node_instances[&id].inputs()[0].input.blob().expect("staging moves the value into a blob");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let record = working.read(&layout.blob_path(&edited_blob)).await.unwrap();
|
||||
assert_eq!(record.as_slice()[0], 1, "the edit is stored as a delta");
|
||||
assert!(record.as_slice().len() < 100, "the delta is small, got {} bytes", record.as_slice().len());
|
||||
|
||||
let input_value = |gdd: &GddV1, declarations: &document_graph_storage::Declarations| {
|
||||
let (converted, _) = gdd.registry().to_runtime_with_metadata(declarations, gdd.blobs()).expect("to_runtime");
|
||||
let node = converted.nodes.values().next().expect("the node converts");
|
||||
let graph_craft::document::NodeInput::Value { tagged_value, .. } = &node.inputs[0] else {
|
||||
panic!("a value input")
|
||||
};
|
||||
(**tagged_value).clone()
|
||||
};
|
||||
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
let archive = reopened.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &store, None).await.unwrap();
|
||||
let unpacked = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.unwrap();
|
||||
|
||||
let flat_options = ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
};
|
||||
let flat_archive = reopened.export_to_bytes(ExportFormat::Zip, flat_options, &store, None).await.unwrap();
|
||||
let flat = GddV1::open_from_archive(&flat_archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.unwrap();
|
||||
let declarations = flat.declarations(&store).await;
|
||||
assert_eq!(flat.blobs().len(), 1, "a copy without history leaves the undone value behind");
|
||||
assert_eq!(input_value(&flat, &declarations), edited);
|
||||
|
||||
for mut gdd in [reopened, unpacked] {
|
||||
let declarations = gdd.declarations(&store).await;
|
||||
assert_eq!(gdd.blobs().len(), 2, "both values' blobs load, the undone one included");
|
||||
assert_eq!(input_value(&gdd, &declarations), edited);
|
||||
|
||||
gdd.undo().unwrap();
|
||||
assert_eq!(input_value(&gdd, &declarations), original);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use peer_transport::mock::MockNetwork;
|
||||
use peer_transport::{Event, SyncTarget};
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
|
||||
@@ -110,3 +110,123 @@ fn an_interaction_past_a_gap_waits_to_retire() {
|
||||
assert!(!host.retire_pending_interaction().expect("retire").is_empty());
|
||||
assert!(host.session().hot_log().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_cannot_change_while_connected() {
|
||||
let mut host = document(1);
|
||||
let mut network = MockNetwork::new(1);
|
||||
host.share(network.endpoint(), UserId(1)).expect("share");
|
||||
assert!(matches!(host.set_user(UserId(2), PeerId(2)), Err(document_format::Error::UserChangeWhileConnected)));
|
||||
assert_eq!(host.session().peer(), PeerId(1));
|
||||
assert_eq!(host.session().user(), UserId(1));
|
||||
}
|
||||
|
||||
/// Edits to a large input reach a peer as deltas. A peer that joins later gets every blob with its sync.
|
||||
#[test]
|
||||
fn blobs_reach_peers_as_deltas_and_with_a_sync() {
|
||||
use document_container::AsyncContainer;
|
||||
use document_format::layout::Layout;
|
||||
use document_graph_storage::blob::BLOB_THRESHOLD;
|
||||
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, ROOT_NETWORK, Value};
|
||||
|
||||
let text = |length: usize| NodeInput::Value {
|
||||
value: Value::Str("a".repeat(length)),
|
||||
exposed: false,
|
||||
};
|
||||
let id = NodeId(1);
|
||||
|
||||
let mut host = document(1);
|
||||
let mut guest = document(2);
|
||||
let mut network = MockNetwork::new(1);
|
||||
let (host_endpoint, guest_endpoint) = (network.endpoint(), network.endpoint());
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(1)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(2)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
|
||||
node.inputs_mut()[0].input = text(BLOB_THRESHOLD);
|
||||
let root = RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
};
|
||||
guest.stage_ops([root, RegistryDelta::AddNode { id, node }]).expect("add");
|
||||
for length in BLOB_THRESHOLD + 1..BLOB_THRESHOLD + 4 {
|
||||
guest
|
||||
.stage_ops([RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: 0,
|
||||
new_input: text(length),
|
||||
}])
|
||||
.expect("edit");
|
||||
}
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
let latest = guest.registry().node_instances[&id].inputs()[0].input.blob().expect("the input is a blob");
|
||||
assert_eq!(host.registry().node_instances[&id].inputs()[0].input.blob(), Some(latest));
|
||||
assert_eq!(host.blobs().len(), 4, "every version reached the host");
|
||||
assert!(host.session().all_blob_hashes().iter().all(|hash| host.blobs().contains_key(hash)));
|
||||
|
||||
let late_endpoint = network.endpoint();
|
||||
let late_id = late_endpoint.id();
|
||||
let mut late = document(3);
|
||||
late.connect(late_endpoint, UserId(3)).expect("connect");
|
||||
network.connect(late_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest, &mut late]);
|
||||
assert!(late.is_synced());
|
||||
assert_eq!(late.blobs(), host.blobs(), "a sync carries every blob");
|
||||
|
||||
let (working, layout) = host.into_storage();
|
||||
let record = futures::executor::block_on(working.read(&layout.blob_path(&latest))).expect("the host wrote the record");
|
||||
assert_eq!(record.as_slice()[0], 1, "an edit arrives as a delta");
|
||||
assert!(record.as_slice().len() < 100, "the delta is small, got {} bytes", record.as_slice().len());
|
||||
}
|
||||
|
||||
/// A record whose base is missing is dropped. The blob is then fetched in full like a missing resource.
|
||||
#[test]
|
||||
fn a_blob_without_its_base_is_asked_for_in_full() {
|
||||
use document_graph_storage::blob::BLOB_THRESHOLD;
|
||||
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, ROOT_NETWORK, Value};
|
||||
|
||||
let text = |length: usize| NodeInput::Value {
|
||||
value: Value::Str("a".repeat(length)),
|
||||
exposed: false,
|
||||
};
|
||||
let id = NodeId(1);
|
||||
|
||||
let mut author = document(1);
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
|
||||
node.inputs_mut()[0].input = text(BLOB_THRESHOLD);
|
||||
let root = RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
};
|
||||
let mut hot_ops = author.stage_ops([root, RegistryDelta::AddNode { id, node }]).expect("add");
|
||||
hot_ops.extend(
|
||||
author
|
||||
.stage_ops([RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: 0,
|
||||
new_input: text(BLOB_THRESHOLD + 1),
|
||||
}])
|
||||
.expect("edit"),
|
||||
);
|
||||
let latest = author.registry().node_instances[&id].inputs()[0].input.blob().expect("the input is a blob");
|
||||
// Blobs are fetched through the resource path with the same hash
|
||||
let resource = ResourceHash::from(latest);
|
||||
|
||||
// Only the delta record of the edit arrives, without the full record of its base
|
||||
let mut reader = document(2);
|
||||
let records = author.blob_records().into_iter().filter(|record| record.hash == latest).collect();
|
||||
reader.apply_remote_hot_ops(hot_ops).expect("apply");
|
||||
reader.absorb_blob_records(records).expect("absorb");
|
||||
assert!(!reader.blobs().contains_key(&latest));
|
||||
assert!(reader.missing_resources().contains(&resource));
|
||||
|
||||
let bytes = author.resource_bytes(resource).expect("the author serves the blob in full");
|
||||
reader.store_resource(resource, &bytes).expect("store");
|
||||
assert_eq!(reader.blobs().get(&latest), Some(&bytes));
|
||||
assert!(!reader.missing_resources().contains(&resource));
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Large node input values are stored as blobs outside the registry, history and hot log. The input keeps a
|
||||
//! [`Value::Blob`] with the hash. Blob bytes are the postcard encoding of the value, so equal values share one blob.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt;
|
||||
|
||||
use crate::{BlobHash, NodeId, NodeInput, Registry, RegistryDelta, ResourceHash, Value};
|
||||
|
||||
/// Values whose encoding reaches this many bytes are stored as blobs.
|
||||
pub const BLOB_THRESHOLD: usize = 1024;
|
||||
|
||||
/// Blob bytes by hash.
|
||||
pub type BlobBytes = HashMap<BlobHash, Vec<u8>>;
|
||||
|
||||
/// Blobs to store, with the base blob that each one can be encoded against.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NewBlobs {
|
||||
pub bytes: BlobBytes,
|
||||
pub bases: HashMap<BlobHash, BlobHash>,
|
||||
}
|
||||
|
||||
impl BlobHash {
|
||||
/// The hash of a blob holding `bytes`.
|
||||
pub fn of(bytes: &[u8]) -> Self {
|
||||
Self(ResourceHash::from(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for BlobHash {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.0.fmt(formatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// Blobs are content addressed like resources, so a peer can fetch a blob through the resource path.
|
||||
impl From<BlobHash> for ResourceHash {
|
||||
fn from(hash: BlobHash) -> Self {
|
||||
hash.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The value a blob's bytes encode.
|
||||
pub fn decode_blob(bytes: &[u8]) -> Result<Value, postcard::Error> {
|
||||
postcard::from_bytes(bytes)
|
||||
}
|
||||
|
||||
impl NodeInput {
|
||||
/// Replace a value of at least [`BLOB_THRESHOLD`] encoded bytes with a blob. The blob bytes are added to `bytes`.
|
||||
pub fn move_into_blob(&mut self, bytes: &mut BlobBytes) {
|
||||
let NodeInput::Value { value, .. } = self else { return };
|
||||
if matches!(value, Value::Blob(_)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Encoding into memory can't fail
|
||||
let Ok(encoded) = postcard::to_stdvec(value) else { return };
|
||||
if encoded.len() < BLOB_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
let hash = BlobHash::of(&encoded);
|
||||
*value = Value::Blob(hash);
|
||||
bytes.insert(hash, encoded);
|
||||
}
|
||||
}
|
||||
|
||||
impl RegistryDelta {
|
||||
/// Move the large values this op writes into blobs. See [`NodeInput::move_into_blob`].
|
||||
pub fn move_values_into_blobs(&mut self, bytes: &mut BlobBytes) {
|
||||
let slots = match self {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => {
|
||||
new_input.move_into_blob(bytes);
|
||||
return;
|
||||
}
|
||||
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => &mut node.inputs,
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => inputs,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
for slot in slots {
|
||||
slot.input.move_into_blob(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// Move the large values of every node input into blobs. See [`NodeInput::move_into_blob`].
|
||||
pub fn move_values_into_blobs(&mut self, bytes: &mut BlobBytes) {
|
||||
for slot in self.node_instances.values_mut().flat_map(|node| &mut node.inputs) {
|
||||
slot.input.move_into_blob(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every blob that live nodes and tombstones of removed nodes name.
|
||||
pub fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let live = self.node_instances.values();
|
||||
let removed = self.removed_nodes.values().map(|tombstone| &tombstone.content);
|
||||
live.chain(removed).flat_map(|node| node.inputs()).filter_map(|slot| slot.input.blob())
|
||||
}
|
||||
|
||||
/// The base of each blob that `ops` write. The base is the blob that the same input slot held before.
|
||||
pub fn blob_bases(&self, ops: &[RegistryDelta]) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut latest: HashMap<(NodeId, usize), BlobHash> = HashMap::new();
|
||||
let mut written = HashSet::new();
|
||||
let mut bases = HashMap::new();
|
||||
|
||||
let mut write = |id: NodeId, index: usize, input: &NodeInput| {
|
||||
let Some(hash) = input.blob() else { return };
|
||||
|
||||
// Only the first write of a blob takes a base. This keeps bases acyclic
|
||||
if written.insert(hash)
|
||||
&& let Some(previous) = latest.get(&(id, index)).copied().or_else(|| self.input_blob(id, index))
|
||||
&& previous != hash
|
||||
{
|
||||
bases.insert(hash, previous);
|
||||
}
|
||||
latest.insert((id, index), hash);
|
||||
};
|
||||
|
||||
for op in ops {
|
||||
match op {
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => write(*id, *index as usize, new_input),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => inputs.iter().enumerate().for_each(|(index, slot)| write(*id, index, &slot.input)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
bases
|
||||
}
|
||||
|
||||
/// Like [`blob_bases`](Self::blob_bases), but compares the slots of `self` with the same slots in `previous`.
|
||||
pub fn blob_bases_since(&self, previous: &Registry) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut nodes: Vec<_> = self.node_instances.iter().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
|
||||
let mut written = HashSet::new();
|
||||
let mut bases = HashMap::new();
|
||||
for (id, node) in nodes {
|
||||
for (index, slot) in node.inputs().iter().enumerate() {
|
||||
if let Some(hash) = slot.input.blob()
|
||||
&& written.insert(hash)
|
||||
&& let Some(base) = previous.input_blob(*id, index)
|
||||
&& base != hash
|
||||
{
|
||||
bases.insert(hash, base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bases
|
||||
}
|
||||
|
||||
fn input_blob(&self, id: NodeId, index: usize) -> Option<BlobHash> {
|
||||
self.node_instances.get(&id)?.inputs().get(index)?.input.blob()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn value_input(value: Value) -> NodeInput {
|
||||
NodeInput::Value { value, exposed: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_large_values_become_blobs() {
|
||||
let mut bytes = BlobBytes::new();
|
||||
|
||||
let mut small = value_input(Value::Str("small".into()));
|
||||
small.move_into_blob(&mut bytes);
|
||||
assert_eq!(small, value_input(Value::Str("small".into())));
|
||||
assert!(bytes.is_empty());
|
||||
|
||||
let large_value = Value::Str("x".repeat(BLOB_THRESHOLD));
|
||||
let mut large = value_input(large_value.clone());
|
||||
large.move_into_blob(&mut bytes);
|
||||
let hash = large.blob().expect("a large value becomes a blob");
|
||||
assert_eq!(decode_blob(&bytes[&hash]).unwrap(), large_value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_twice_keeps_the_blob() {
|
||||
let mut bytes = BlobBytes::new();
|
||||
let mut input = value_input(Value::Str("x".repeat(BLOB_THRESHOLD)));
|
||||
input.move_into_blob(&mut bytes);
|
||||
let once = input.clone();
|
||||
|
||||
input.move_into_blob(&mut bytes);
|
||||
assert_eq!(input, once);
|
||||
assert_eq!(bytes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bases_stay_acyclic_when_slots_swap_blobs() {
|
||||
let [x, a] = [b"x", b"a"].map(|bytes| BlobHash::of(bytes));
|
||||
let write = |node: u64, hash: BlobHash| RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(node),
|
||||
index: 0,
|
||||
new_input: value_input(Value::Blob(hash)),
|
||||
};
|
||||
|
||||
let bases = Registry::default().blob_bases(&[write(1, x), write(1, a), write(2, a), write(2, x)]);
|
||||
assert_eq!(bases, HashMap::from([(a, x)]), "only first writes take a base");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Attributes, Delta, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Value, attr, compute_rev};
|
||||
use crate::{Attributes, BlobHash, Delta, InputSlot, NodeField, NodeInput, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Tombstone, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
impl Delta {
|
||||
@@ -78,6 +78,28 @@ impl Delta {
|
||||
pub fn has_valid_id(&self) -> bool {
|
||||
self.id == self.recomputed_id()
|
||||
}
|
||||
|
||||
/// The blobs that the op writes or that its priors restore.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let prior_slots = self.reverse.iter().flat_map(|prior| match prior {
|
||||
Prior::Node { node, .. }
|
||||
| Prior::RemovedNode {
|
||||
tombstone: Tombstone { content: node, .. },
|
||||
..
|
||||
} => node.inputs(),
|
||||
Prior::NodeField {
|
||||
field: NodeField::Input { previous, .. },
|
||||
..
|
||||
} => std::slice::from_ref(previous),
|
||||
Prior::NodeField {
|
||||
field: NodeField::Inputs { previous, .. },
|
||||
..
|
||||
} => previous.as_slice(),
|
||||
_ => &[],
|
||||
});
|
||||
|
||||
self.kind.blob_hashes().chain(prior_slots.filter_map(|slot| slot.input.blob()))
|
||||
}
|
||||
}
|
||||
|
||||
impl RegistryDelta {
|
||||
@@ -89,6 +111,18 @@ impl RegistryDelta {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs in the input values that the op writes.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let (input, slots): (Option<&NodeInput>, &[InputSlot]) = match self {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => (Some(new_input), &[]),
|
||||
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => (None, node.inputs()),
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => (None, inputs),
|
||||
_ => (None, &[]),
|
||||
};
|
||||
|
||||
input.into_iter().chain(slots.iter().map(|slot| &slot.input)).filter_map(NodeInput::blob)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -9,6 +9,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::blob::BlobBytes;
|
||||
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
|
||||
use crate::{
|
||||
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
|
||||
@@ -118,6 +119,8 @@ pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// The bytes of the blobs that the registry names. The caller stores them.
|
||||
pub blob_bytes: BlobBytes,
|
||||
/// The storage `NetworkId` of each runtime network location, to key per-network view state in `session.json`.
|
||||
pub network_ids: HashMap<NetworkLocation, NetworkId>,
|
||||
}
|
||||
@@ -165,8 +168,9 @@ pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
||||
impl Registry {
|
||||
/// Convenience wrapper returning only the registry (declaration bytes discarded). For callers
|
||||
/// that don't persist a byte store — e.g. the graph-only `TryFrom` and value-comparison tests.
|
||||
/// Large values stay inline, so the registry converts back without blob bytes.
|
||||
pub fn from_runtime_with_metadata<M: NodeMetadataSource>(node_network: &NodeNetwork, metadata: &M, resources: &graphene_resource::ResourceRegistry, peer: PeerId) -> Result<Self, ConversionError> {
|
||||
Ok(Self::convert_from_runtime(node_network, metadata, resources, peer)?.registry)
|
||||
Ok(Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?.registry)
|
||||
}
|
||||
|
||||
/// Full conversion: returns the registry and the extracted declaration bytes for the caller to
|
||||
@@ -176,6 +180,18 @@ impl Registry {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut conversion = Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?;
|
||||
conversion.registry.move_values_into_blobs(&mut conversion.blob_bytes);
|
||||
Ok(conversion)
|
||||
}
|
||||
|
||||
/// [`convert_from_runtime`](Self::convert_from_runtime) without moving large values into blobs.
|
||||
pub(crate) fn convert_from_runtime_inline<M: NodeMetadataSource>(
|
||||
node_network: &NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut registry = Registry::default();
|
||||
let mut ctx = ConversionContext {
|
||||
@@ -216,6 +232,7 @@ impl Registry {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
blob_bytes: BlobBytes::new(),
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
pub mod attributes;
|
||||
pub mod blob;
|
||||
pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::registry::attributes_value_equal;
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
|
||||
use crate::{Attributes, BlobHash, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
|
||||
|
||||
impl Node {
|
||||
pub fn implementation(&self) -> &Implementation {
|
||||
@@ -64,6 +64,16 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeInput {
|
||||
/// The blob hash of a value input that holds a [`Value::Blob`].
|
||||
pub fn blob(&self) -> Option<BlobHash> {
|
||||
match self {
|
||||
NodeInput::Value { value: Value::Blob(hash), .. } => Some(*hash),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `timestamp`.
|
||||
pub fn unset(timestamp: TimeStamp) -> Self {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::HashMap;
|
||||
use crate::{Attributes, Implementation, NetworkId, NodeId, PeerId, ROOT_NETWORK, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
@@ -25,6 +25,31 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry as `to_runtime` renders it. A removed network the root still reaches counts as present.
|
||||
pub(crate) fn as_rendered(&self) -> Registry {
|
||||
let mut nodes_by_network: HashMap<NetworkId, Vec<&crate::Node>> = HashMap::new();
|
||||
for node in self.node_instances.values() {
|
||||
nodes_by_network.entry(node.network).or_default().push(node);
|
||||
}
|
||||
|
||||
let mut rendered = self.clone();
|
||||
let mut reached = HashSet::from([ROOT_NETWORK]);
|
||||
let mut pending = vec![ROOT_NETWORK];
|
||||
while let Some(network) = pending.pop() {
|
||||
for node in nodes_by_network.get(&network).into_iter().flatten() {
|
||||
if let Implementation::Network(id) = node.implementation
|
||||
&& reached.insert(id)
|
||||
{
|
||||
pending.push(id);
|
||||
if let Some(mark) = rendered.removed_networks.remove(&id) {
|
||||
rendered.networks.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Whether both registries removed the same entities at the same times. Registries equal in value but not in their
|
||||
/// removal marks resolve later ops differently.
|
||||
pub fn removal_marks_equal(&self, other: &Self) -> bool {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Stable, document-scoped identity for a node. Minted as a truncated `blake3(peer, counter)` so it
|
||||
@@ -12,6 +13,11 @@ pub struct NodeId(pub u64);
|
||||
#[serde(transparent)]
|
||||
pub struct NetworkId(pub u64);
|
||||
|
||||
/// The content hash of a blob, which stores a large node input value.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct BlobHash(pub ResourceHash);
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct SessionState {
|
||||
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
|
||||
/// This peer's identity for the document, stable per (device, document, user). Per-peer rather than
|
||||
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::BlobHash;
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::de::{self, MapAccess, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
@@ -12,6 +14,8 @@ pub enum Value {
|
||||
Str(String),
|
||||
Array(Vec<Value>),
|
||||
Object(Vec<(String, Value)>),
|
||||
/// A large node input value that is stored as a blob. See [`crate::blob`].
|
||||
Blob(BlobHash),
|
||||
}
|
||||
|
||||
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
|
||||
@@ -29,6 +33,7 @@ impl Serialize for Value {
|
||||
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))),
|
||||
Value::Blob(hash) => serializer.collect_map(std::iter::once((Value::BLOB_KEY, hash))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +102,7 @@ impl<'de> Deserialize<'de> for Value {
|
||||
}
|
||||
dedup
|
||||
});
|
||||
Ok(Value::Object(object))
|
||||
Ok(Value::from_object(object))
|
||||
}
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a valid Value")
|
||||
@@ -106,3 +111,20 @@ impl<'de> Deserialize<'de> for Value {
|
||||
deserializer.deserialize_any(Untagged)
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// In human-readable formats a [`Value::Blob`] is written as an object with only this key. The key is reserved.
|
||||
/// Such an object with a hash string is read back as a blob.
|
||||
pub(crate) const BLOB_KEY: &str = "$blob";
|
||||
|
||||
/// An object, or a [`Value::Blob`] if the object has the form of one.
|
||||
pub(crate) fn from_object(object: Vec<(String, Value)>) -> Self {
|
||||
if let [(key, Value::Str(hex))] = object.as_slice()
|
||||
&& key == Self::BLOB_KEY
|
||||
&& let Ok(hash) = ResourceHash::try_from(hex.as_str())
|
||||
{
|
||||
return Value::Blob(BlobHash(hash));
|
||||
}
|
||||
Value::Object(object)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{
|
||||
ApplyMode, Attributes, Delta, Document, History, HotOp, HotOpId, HotSequence, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry,
|
||||
RetiredMarks, Rev, TimeStamp, Touched, UserId, Value, to_value,
|
||||
ApplyMode, Attributes, BlobHash, 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};
|
||||
@@ -19,6 +19,8 @@ pub struct Session {
|
||||
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
|
||||
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
|
||||
remote_tips: HashMap<PeerId, Rev>,
|
||||
/// The base of local diffs, so peers' edits to the working registry aren't diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
|
||||
/// hold the only copy, so they stay garbage collection roots for the life of the session.
|
||||
taken_back_resources: HashSet<ResourceHash>,
|
||||
@@ -43,6 +45,7 @@ impl Session {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -55,6 +58,19 @@ impl Session {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// Hand this device to `user` under `peer`, an unused id, so the old peer's ops keep their author.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let closing = self.end_interaction()?;
|
||||
let mut clock = LamportClock::new(peer);
|
||||
clock.counter = self.document.clock.counter;
|
||||
self.document.clock = clock;
|
||||
self.document.peer = peer;
|
||||
self.document.user = user;
|
||||
self.document.last_hot_sequence = HotSequence::NONE;
|
||||
self.document.redo_stack.clear();
|
||||
Ok(closing)
|
||||
}
|
||||
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
@@ -83,7 +99,9 @@ impl Session {
|
||||
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
|
||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||
/// to promote them into durable history.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
///
|
||||
/// Only for tests because it does not store the blob bytes. `Gdd::stage_runtime_snapshot` does.
|
||||
#[cfg(test)]
|
||||
pub fn stage_from_runtime<M: NodeMetadataSource>(
|
||||
&mut self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
@@ -91,16 +109,36 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
let ops = self.runtime_diff(&conversion.registry);
|
||||
let hot_ops = self.stage_runtime_diff(ops, conversion.registry.clone())?;
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// The ops from the last staged runtime state to `registry`, a fresh conversion of the runtime network.
|
||||
pub fn runtime_diff(&self, registry: &Registry) -> Vec<RegistryDelta> {
|
||||
match &self.runtime_base {
|
||||
Some(base) => crate::delta::compute_deltas(base, registry),
|
||||
None => crate::delta::compute_deltas(&self.document.working_registry.as_rendered(), registry),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage the [`runtime_diff`](Self::runtime_diff) ops of `registry` and keep `registry` as the last runtime state.
|
||||
pub fn stage_runtime_diff(&mut self, ops: Vec<RegistryDelta>, registry: Registry) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// Lenient since a peer's concurrent write may have reshaped what the diff names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
self.runtime_base = Some(registry);
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.as_rendered());
|
||||
}
|
||||
|
||||
/// The stable [`NetworkId`] of each runtime network location for this document's peer, to key per-network view state in `session.json`.
|
||||
/// It depends only on the network structure, not on resources or declarations.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub fn network_ids<M: NodeMetadataSource>(&self, network: &graph_craft::document::NodeNetwork, metadata: &M) -> Result<HashMap<graph_craft::document::NetworkLocation, NetworkId>, CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
let conversion = Registry::convert_from_runtime_inline(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
Ok(conversion.network_ids)
|
||||
}
|
||||
|
||||
@@ -169,10 +207,10 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
|
||||
}
|
||||
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
@@ -180,7 +218,10 @@ impl Session {
|
||||
}
|
||||
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
let carried = pending
|
||||
.iter()
|
||||
.any(|(op, _)| matches!(op, RegistryDelta::RegisterPeer { peer: named, user: naming } if *named == peer && *naming == user));
|
||||
if !carried && self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new()));
|
||||
}
|
||||
|
||||
@@ -199,7 +240,7 @@ impl Session {
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -213,9 +254,20 @@ impl Session {
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
self.advance_runtime_base(&staged);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// Keeps a later whole-document stage from restating a local batch.
|
||||
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
|
||||
let Some(base) = self.runtime_base.take() else { return };
|
||||
let working = std::mem::replace(&mut self.document.working_registry, base);
|
||||
for hot_op in staged {
|
||||
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
|
||||
}
|
||||
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
|
||||
}
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
@@ -289,6 +341,7 @@ impl Session {
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -314,6 +367,7 @@ impl Session {
|
||||
/// Drop hot ops another peer retired, without retiring them here. Until their deltas arrive, the working registry
|
||||
/// shows the snapshot plus what is still hot.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.mark_retired(retired.iter().copied())
|
||||
}
|
||||
|
||||
@@ -338,6 +392,7 @@ impl Session {
|
||||
if ids.iter().any(|&id| retired.covers(id)) || !retired.took_back_all(peer, own[own.len() - 1].sequence, self.document.last_hot_sequence) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
@@ -346,6 +401,7 @@ impl Session {
|
||||
|
||||
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
|
||||
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.retract_hot_ops(ids).0
|
||||
}
|
||||
|
||||
@@ -408,6 +464,7 @@ impl Session {
|
||||
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
@@ -435,6 +492,7 @@ impl Session {
|
||||
self.document.retired_snapshot = snapshot;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
self.publish_up_to(target);
|
||||
Ok((
|
||||
HeadMove {
|
||||
@@ -482,6 +540,7 @@ impl Session {
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = moved.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
@@ -528,6 +587,7 @@ impl Session {
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
@@ -538,7 +598,11 @@ impl Session {
|
||||
|
||||
/// 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)
|
||||
let touched = self.document.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.runtime_base = None;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -586,7 +650,7 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
@@ -680,6 +744,7 @@ impl Session {
|
||||
} else {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
@@ -754,6 +819,7 @@ impl Session {
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
@@ -829,6 +895,13 @@ impl Session {
|
||||
self.document.history.mark_interaction_end(rev, timestamp);
|
||||
}
|
||||
|
||||
/// Record the retirer's clock for these deltas. Not part of their revs and never used for ordering.
|
||||
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
|
||||
for &rev in revs {
|
||||
self.document.history.set_retired_at(rev, wall_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy the attributes and retirement time of the delta it stands for.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
@@ -884,6 +957,7 @@ impl Session {
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
@@ -904,6 +978,7 @@ impl Session {
|
||||
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
|
||||
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
let mut forward = Vec::new();
|
||||
let mut cursor = Some(checkpoint);
|
||||
@@ -999,6 +1074,22 @@ impl Session {
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every blob that the registry, its tombstones, the history or the hot log names.
|
||||
pub fn all_blob_hashes(&self) -> HashSet<BlobHash> {
|
||||
self.blob_hashes().collect()
|
||||
}
|
||||
|
||||
/// Whether the registry, its tombstones, the history or the hot log names `hash`.
|
||||
pub fn names_blob(&self, hash: BlobHash) -> bool {
|
||||
self.blob_hashes().any(|named| named == hash)
|
||||
}
|
||||
|
||||
fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let history = self.document.history.iter().flat_map(Delta::blob_hashes);
|
||||
let hot_log = self.document.hot_log.iter().flat_map(|hot_op| hot_op.op.blob_hashes());
|
||||
self.document.working_registry.blob_hashes().chain(history).chain(hot_log)
|
||||
}
|
||||
|
||||
/// Every referenced resource hash plus what the ops this peer took back named. Garbage collection must keep these.
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
let mut roots = self.all_referenced_resource_hashes();
|
||||
|
||||
@@ -281,7 +281,6 @@ fn newest_peer_registration_wins_in_any_order() {
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes, so the next batch registers again.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
@@ -296,6 +295,56 @@ fn newest_peer_registration_wins_in_any_order() {
|
||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_user_takes_a_fresh_peer_and_leaves_the_old_steps_to_their_maker() {
|
||||
fn interaction(session: &mut Session, key: &str) {
|
||||
session.stage_ops([set_attribute(key, 1)]).expect("stage");
|
||||
session.end_interaction().expect("close");
|
||||
for closed in session.closed_interactions() {
|
||||
session.retire_interaction(&closed).expect("retire");
|
||||
}
|
||||
}
|
||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
||||
for key in ["a", "b", "c"] {
|
||||
interaction(&mut device, key);
|
||||
}
|
||||
device.undo().expect("undo c");
|
||||
assert!(device.can_redo());
|
||||
device.stage_ops([set_attribute("d", 1)]).expect("stage d, left open");
|
||||
let clock_before = device.clock_counter();
|
||||
|
||||
let closing = device.set_user(UserId(20), PeerId(2)).expect("switch");
|
||||
assert!(closing.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(1)), "the old peer closes its own interaction");
|
||||
assert!(closing.last().is_some_and(crate::HotOp::ends_interaction));
|
||||
assert_eq!(device.peer(), PeerId(2));
|
||||
assert!(device.clock_counter() >= clock_before);
|
||||
assert!(!device.can_undo(), "the previous user's steps are not this person's to undo");
|
||||
assert!(!device.can_redo());
|
||||
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
|
||||
assert!(!device.is_mine(PeerId(1)));
|
||||
|
||||
device.stage_ops([set_attribute("e", 1)]).expect("stage e");
|
||||
device.end_interaction().expect("close e");
|
||||
let new_ops: Vec<_> = device.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(2)).collect();
|
||||
assert_eq!(new_ops.first().map(|hot_op| hot_op.sequence), Some(crate::HotSequence(1)), "the new peer's run starts over");
|
||||
assert!(new_ops.iter().all(|hot_op| hot_op.timestamp.counter > clock_before));
|
||||
for closed in device.closed_interactions() {
|
||||
device.retire_interaction(&closed).expect("retire");
|
||||
}
|
||||
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10), "the old registration stands");
|
||||
assert_eq!(device.user_of(PeerId(2)), Some(UserId(20)));
|
||||
assert!(device.is_mine(PeerId(2)));
|
||||
for delta in device.history().filter(|delta| !matches!(delta.kind, RegistryDelta::RegisterPeer { .. })) {
|
||||
let expected = if delta.author == PeerId(1) { UserId(10) } else { UserId(20) };
|
||||
assert_eq!(device.user_of(delta.author), Some(expected));
|
||||
}
|
||||
|
||||
assert!(device.can_undo(), "the new user's own step undoes");
|
||||
device.undo().expect("undo e");
|
||||
assert!(!device.can_undo(), "but not past it into the previous user's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
@@ -1453,7 +1453,10 @@ fn an_input_naming_a_node_not_yet_added_renders_dangling() {
|
||||
}
|
||||
assert!(document.working_registry.removed_nodes.get(&unseen).is_some_and(|mark| mark.placeholder));
|
||||
|
||||
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
|
||||
document
|
||||
.working_registry
|
||||
.to_runtime_with_metadata(&crate::Declarations::new(), &crate::blob::BlobBytes::new())
|
||||
.expect("converts with a dangling input");
|
||||
}
|
||||
|
||||
/// Remapped tips can swap order, and a merge's `parent` has to stay the lowest.
|
||||
|
||||
@@ -4,6 +4,7 @@ use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId as RuntimeNetworkId, NetworkLocation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::blob::BlobBytes;
|
||||
use crate::to_runtime::ConversionError;
|
||||
use crate::{Declarations, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
|
||||
|
||||
@@ -72,9 +73,9 @@ 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, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
let (whole, node_entries, _) = registry.to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes).expect("whole conversion");
|
||||
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
|
||||
for &id in registry.node_instances.keys() {
|
||||
let projected = projection.node(id).expect("every stored node projects");
|
||||
let (network, local_id) = projection.node_address(id).expect("every stored node has an address");
|
||||
@@ -96,8 +97,8 @@ fn a_network_entry_projects_its_dense_exports_and_location() {
|
||||
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 (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
|
||||
|
||||
let root = projection.network_entry(ROOT_NETWORK).expect("root");
|
||||
assert_eq!(root.network, NetworkLocation::default());
|
||||
@@ -120,8 +121,8 @@ fn an_unreachable_network_has_no_address() {
|
||||
node.network = NetworkId(5);
|
||||
registry.node_instances.insert(NodeId(9), node);
|
||||
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
|
||||
let projection = registry.runtime_projection(&declarations, &blobs);
|
||||
assert_eq!(projection.network_location(NetworkId(5)), None);
|
||||
assert_eq!(projection.node_address(NodeId(9)), None);
|
||||
assert!(matches!(projection.node(NodeId(9)), Err(ConversionError::NetworkNotFound(_))));
|
||||
@@ -140,8 +141,8 @@ fn a_network_several_nodes_implement_has_one_location() {
|
||||
registry.node_instances.insert(NodeId(id), node);
|
||||
}
|
||||
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
|
||||
let projection = registry.runtime_projection(&declarations, &blobs);
|
||||
assert_eq!(projection.network_location(NetworkId(5)), Some(Some(RuntimeNetworkId(5))));
|
||||
assert_eq!(projection.network_location(ROOT_NETWORK), Some(NetworkLocation::default()));
|
||||
}
|
||||
@@ -20,12 +20,12 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations and blobs alongside it.
|
||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` and blob bytes in hand for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations, crate::blob::BlobBytes) {
|
||||
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
||||
(conversion.registry, conversion.declarations)
|
||||
(conversion.registry, conversion.declarations, conversion.blob_bytes)
|
||||
}
|
||||
|
||||
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
||||
@@ -137,10 +137,10 @@ fn test_simple_round_trip() {
|
||||
let original_network = create_simple_network();
|
||||
|
||||
// Convert to Registry
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
let (registry, declarations, blobs) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back to NodeNetwork");
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
|
||||
|
||||
// Verify structure is preserved
|
||||
assert_eq!(converted_network.nodes.len(), original_network.nodes.len(), "Node count should be preserved");
|
||||
@@ -185,10 +185,10 @@ fn test_nested_network_round_trip() {
|
||||
let original_network = create_nested_network();
|
||||
|
||||
// Convert to Registry
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
let (registry, declarations, blobs) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back to NodeNetwork");
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
|
||||
|
||||
// Verify structure is preserved
|
||||
assert_eq!(converted_network.nodes.len(), original_network.nodes.len(), "Node count should be preserved");
|
||||
@@ -213,7 +213,7 @@ fn test_nested_network_round_trip() {
|
||||
fn test_registry_structure() {
|
||||
let network = create_simple_network();
|
||||
|
||||
let (registry, _declarations) = to_registry(&network);
|
||||
let (registry, _declarations, _blobs) = to_registry(&network);
|
||||
|
||||
assert!(registry.resources.len() >= 2, "Should have proto-node declaration resources");
|
||||
assert!(!registry.networks.is_empty(), "Should have at least one network");
|
||||
@@ -281,8 +281,8 @@ fn test_metadata_preservation() {
|
||||
};
|
||||
|
||||
// Convert to Registry and back
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert back to NodeNetwork");
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert back to NodeNetwork");
|
||||
|
||||
// Verify call_argument is preserved
|
||||
let orig_node_0 = network.nodes.get(&NodeId(0)).unwrap();
|
||||
@@ -327,11 +327,11 @@ fn test_demo_artwork_round_trip() {
|
||||
original_network.lift_nested_networks();
|
||||
|
||||
// Convert to Registry
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
let (registry, declarations, blobs) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry
|
||||
.to_runtime_with_metadata(&declarations)
|
||||
.to_runtime_with_metadata(&declarations, &blobs)
|
||||
.unwrap_or_else(|e| panic!("Failed to convert {} back to NodeNetwork: {:?}", artwork_name, e));
|
||||
|
||||
// Basic structural checks
|
||||
@@ -470,9 +470,10 @@ fn test_ui_metadata_round_trip() {
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
|
||||
let declarations = conversion.declarations;
|
||||
let blobs = conversion.blob_bytes;
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back with metadata");
|
||||
|
||||
// Graph structure still round-trips.
|
||||
assert_eq!(converted.nodes.len(), network.nodes.len());
|
||||
@@ -629,8 +630,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
|
||||
let input = &converted.nodes.get(&NodeId(0)).expect("node 0").inputs[0];
|
||||
let NodeInput::Value { tagged_value, .. } = input else {
|
||||
@@ -650,14 +651,14 @@ fn duplicate_runtime_node_id_is_rejected() {
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
let (mut registry, declarations) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
|
||||
// Force both root-network nodes onto the same runtime ID.
|
||||
for node in registry.node_instances.values_mut() {
|
||||
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
|
||||
}
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("duplicate runtime ID must error");
|
||||
assert!(
|
||||
matches!(error, ConversionError::DuplicateRuntimeNodeId { runtime_id: 7, .. }),
|
||||
"expected DuplicateRuntimeNodeId, got {error:?}"
|
||||
@@ -671,7 +672,7 @@ fn cross_network_reference_is_rejected() {
|
||||
use crate::to_runtime::ConversionError;
|
||||
use crate::{Network, NodeInput};
|
||||
|
||||
let (mut registry, declarations) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
|
||||
// `create_simple_network` wires one node's input to another, both in the root network. Find the
|
||||
// referenced storage ID, then move that node into a fresh second network so the reference crosses
|
||||
@@ -690,7 +691,7 @@ fn cross_network_reference_is_rejected() {
|
||||
registry.networks.insert(other_network, Network::default());
|
||||
registry.node_instances.get_mut(&referenced_storage_id).expect("referenced node exists").network = other_network;
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("cross-network reference must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("cross-network reference must error");
|
||||
assert!(matches!(error, ConversionError::CrossNetworkReference { .. }), "expected CrossNetworkReference, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -701,8 +702,8 @@ fn scope_injections_round_trip() {
|
||||
let mut network = create_simple_network();
|
||||
network.scope_injections.insert("editor-api".to_string(), (NodeId(0), concrete!(u32)));
|
||||
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
|
||||
let (node_id, ty) = converted.scope_injections.get("editor-api").expect("scope injection must survive the round trip");
|
||||
assert_eq!(*node_id, NodeId(0), "the injection's node reference must resolve back to its original runtime ID");
|
||||
@@ -716,7 +717,7 @@ fn dangling_scope_injection_is_rejected() {
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
let (mut registry, declarations) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
|
||||
// Store an injection pointing at a storage ID that no node carries, leaving the reference dangling
|
||||
// while the rest of the graph stays valid. The root network is whichever one holds the nodes.
|
||||
@@ -730,7 +731,7 @@ fn dangling_scope_injection_is_rejected() {
|
||||
.set_serialized(crate::attr::network::SCOPE_INJECTIONS, &injections, TimeStamp::ORIGIN)
|
||||
.expect("serialize injections");
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("dangling scope injection must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("dangling scope injection must error");
|
||||
assert!(matches!(error, ConversionError::DanglingScopeInjection { .. }), "expected DanglingScopeInjection, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -776,7 +777,9 @@ fn cyclic_network_reference_is_rejected() {
|
||||
},
|
||||
);
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&crate::Declarations::new()).expect_err("cyclic network reference must error");
|
||||
let error = registry
|
||||
.to_runtime_with_metadata(&crate::Declarations::new(), &crate::blob::BlobBytes::new())
|
||||
.expect_err("cyclic network reference must error");
|
||||
assert!(matches!(error, ConversionError::CyclicNetwork(_)), "expected CyclicNetwork, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -805,7 +808,7 @@ fn a_shared_table_entry_round_trips_as_one_network() {
|
||||
network.nodes.get_mut(&NodeId(1)).expect("node 1").implementation = DocumentNodeImplementation::Definition(shared);
|
||||
network.nodes.get_mut(&NodeId(1)).expect("node 1").inputs = vec![NodeInput::node(NodeId(0), 0)];
|
||||
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
|
||||
assert_eq!(registry.networks.len(), 2, "the root and the one shared entry");
|
||||
assert!(registry.networks.contains_key(&NetworkId(shared.0)), "the entry is stored under its own ID");
|
||||
@@ -815,7 +818,7 @@ fn a_shared_table_entry_round_trips_as_one_network() {
|
||||
"the shared body is stored once"
|
||||
);
|
||||
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
assert_eq!(converted, network);
|
||||
}
|
||||
|
||||
@@ -855,6 +858,39 @@ fn an_unreached_table_entry_is_not_stored() {
|
||||
let mut network = create_simple_network();
|
||||
network.definitions.insert(RuntimeNetworkId(5), create_simple_network());
|
||||
|
||||
let (registry, _) = to_registry(&network);
|
||||
let (registry, ..) = to_registry(&network);
|
||||
assert_eq!(registry.networks.keys().copied().collect::<Vec<_>>(), vec![crate::ROOT_NETWORK]);
|
||||
}
|
||||
|
||||
/// A large input value is stored as a blob and read back from the blob bytes.
|
||||
#[test]
|
||||
fn large_input_value_round_trips_through_a_blob() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
let large = TaggedValue::String("x".repeat(crate::blob::BLOB_THRESHOLD));
|
||||
let network = NodeNetwork {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(large, false), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
let inputs = registry.node_instances.values().next().expect("the node converts").inputs();
|
||||
let blob = inputs[0].input.blob().expect("the large value becomes a blob");
|
||||
assert!(inputs[1].input.blob().is_none(), "a small value stays inline");
|
||||
assert_eq!(blobs.keys().collect::<Vec<_>>(), [&blob]);
|
||||
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
assert_eq!(converted, network);
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&declarations, &crate::blob::BlobBytes::new()).expect_err("a missing blob must error");
|
||||
assert!(matches!(error, crate::to_runtime::ConversionError::BlobNotFound(hash) if hash == blob), "{error}");
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
//! Peers exchanging retired history, moving the shared head, and undoing against what other peers hold.
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput as RuntimeInput, NodeNetwork};
|
||||
|
||||
use crate::{
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry,
|
||||
ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, NoMetadata, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta,
|
||||
ResourceEntry, ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -397,6 +402,46 @@ fn rebuilt_working(session: &Session) -> Registry {
|
||||
copy.document.working_registry
|
||||
}
|
||||
|
||||
fn runtime_network(values: [u32; 2]) -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
inputs: values.iter().map(|&value| RuntimeInput::value(TaggedValue::Integer(value as i64), false)).collect(),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage past a peer's shrunken input list lands like a peer's write, so later stages don't fail.
|
||||
#[test]
|
||||
fn a_local_stage_after_a_peers_input_list_change_still_lands() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
a.stage_from_runtime(&runtime_network([1, 2]), &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
let (&id, node) = b.registry().node_instances.iter().find(|(_, node)| node.inputs().len() == 2).expect("the converted node");
|
||||
let first = node.inputs()[0].clone();
|
||||
let shrink = b.stage_ops([RegistryDelta::SetNodeInputs { id, inputs: vec![first] }]).unwrap();
|
||||
for hot_op in shrink {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
|
||||
let edit = a.stage_from_runtime(&runtime_network([1, 5]), &NoMetadata, &resources);
|
||||
let later = a.stage_from_runtime(&runtime_network([9, 5]), &NoMetadata, &resources);
|
||||
assert!(edit.is_ok() || later.is_ok(), "a later stage still lands: first {:?}, later {:?}", edit.err(), later.err());
|
||||
}
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, bound: u64) -> u64 {
|
||||
@@ -439,7 +484,11 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
key: key.into(),
|
||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(50)))),
|
||||
};
|
||||
Some(match rng.below(9) {
|
||||
let source_key = |rng: &mut Lcg| crate::SourceKey {
|
||||
priority: crate::Priority::new(rng.below(2) as f64).expect("finite"),
|
||||
peer: PeerId(1 + rng.below(2)),
|
||||
};
|
||||
Some(match rng.below(17) {
|
||||
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: {
|
||||
let key = ["x", "y"][rng.below(2) as usize];
|
||||
@@ -500,7 +549,7 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
new_input: input(rng),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
8 => {
|
||||
let id = pick(rng, seen_nodes.clone())?;
|
||||
let inputs = (0..1 + rng.below(3))
|
||||
.map(|_| InputSlot {
|
||||
@@ -511,6 +560,55 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
.collect();
|
||||
RegistryDelta::SetNodeInputs { id: NodeId(id), inputs }
|
||||
}
|
||||
9 => RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
index: rng.below(2) as u32,
|
||||
export: (rng.below(3) > 0).then(|| input(rng)),
|
||||
},
|
||||
10 => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
delta: attribute(rng, "name"),
|
||||
},
|
||||
11 => RegistryDelta::SetNodeImplementation {
|
||||
id: NodeId(pick(rng, seen_nodes.clone())?),
|
||||
implementation: Implementation::Network(NetworkId(pick(rng, seen_networks.clone())?)),
|
||||
},
|
||||
12 => {
|
||||
let mut entry = ResourceEntry {
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
..Default::default()
|
||||
};
|
||||
entry.force_set_source(
|
||||
source_key(rng),
|
||||
crate::SourceValue {
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
RegistryDelta::AddResource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
entry,
|
||||
}
|
||||
}
|
||||
13 => {
|
||||
let id = ResourceId::from(1 + rng.below(2));
|
||||
let snapshot = registry.resources.get(&id)?.clone();
|
||||
RegistryDelta::RemoveResource { id, snapshot }
|
||||
}
|
||||
14 => RegistryDelta::SetResourceHash {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
},
|
||||
15 => RegistryDelta::AddSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
},
|
||||
_ => RegistryDelta::RemoveSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -774,7 +872,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
|
||||
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
|
||||
let later = host.head_rev().expect("rev");
|
||||
host.mark_interaction_end(later);
|
||||
host.document.history.set_retired_at(later, 1_234);
|
||||
host.stamp_retired_at(&[later], 1_234);
|
||||
catch_up(&mut guest, &host);
|
||||
assert_eq!(guest.head_rev(), host.head_rev());
|
||||
assert_eq!(guest.latest_own_interaction(), Some(undone));
|
||||
@@ -1017,6 +1115,68 @@ fn discarded_hot_ops_leave_the_working_registry_at_the_snapshot() {
|
||||
assert_eq!(session.registry(), session.retired_registry());
|
||||
}
|
||||
|
||||
/// Staging a rebuilt runtime unchanged must not restore a network a peer removed while another kept writing to its owner.
|
||||
#[test]
|
||||
fn restaging_an_unchanged_runtime_does_not_revive_a_nested_network_removed_under_a_live_owner() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let outer = NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(graph_craft::document::NetworkId(9)),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
definitions: [(graph_craft::document::NetworkId(9), runtime_network([1, 2]))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
let (_, conversion) = a.stage_from_runtime(&outer, &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
|
||||
let (&owner, owner_node) = b
|
||||
.registry()
|
||||
.node_instances
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(node.implementation(), Implementation::Network(_)))
|
||||
.expect("the owner");
|
||||
let Implementation::Network(nested) = *owner_node.implementation() else { unreachable!() };
|
||||
let mut removal = vec![RegistryDelta::RemoveNode {
|
||||
id: owner,
|
||||
snapshot: owner_node.clone(),
|
||||
}];
|
||||
for (&id, node) in b.registry().node_instances.iter().filter(|(_, node)| node.network() == nested) {
|
||||
removal.push(RegistryDelta::RemoveNode { id, snapshot: node.clone() });
|
||||
}
|
||||
removal.push(RegistryDelta::RemoveNetwork {
|
||||
id: nested,
|
||||
snapshot: b.registry().networks[&nested].clone(),
|
||||
});
|
||||
let removal = b.stage_ops(removal).unwrap();
|
||||
|
||||
// A writes after the removal, so only the nested network goes.
|
||||
for _ in 0..10 {
|
||||
a.document.clock.tick();
|
||||
}
|
||||
a.stage_ops([change_node_attribute(owner, "tint", serde_json::json!(1))]).unwrap();
|
||||
for hot_op in removal {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
assert!(a.registry().node_instances.contains_key(&owner));
|
||||
assert!(!a.registry().networks.contains_key(&nested));
|
||||
|
||||
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations, &conversion.blob_bytes).expect("to runtime");
|
||||
a.mark_runtime_current();
|
||||
a.stage_from_runtime(&runtime, &NoMetadata, &resources).expect("restage");
|
||||
assert!(!a.registry().networks.contains_key(&nested), "the removed network stays removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
@@ -1047,3 +1207,45 @@ fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
assert_eq!(session.retired_registry(), &retired);
|
||||
assert_eq!(session.registry(), ®istry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_carrying_its_registration_is_not_given_another() {
|
||||
let mut session = Session::with_peer(crate::PeerId(1));
|
||||
let register = RegistryDelta::RegisterPeer {
|
||||
peer: crate::PeerId(1),
|
||||
user: session.user(),
|
||||
};
|
||||
assert_eq!(session.stage_computed_ops(vec![register]).expect("stage").len(), 1);
|
||||
}
|
||||
|
||||
/// Only what the root reaches renders, so a removal no rendered node undoes stays a removal.
|
||||
#[test]
|
||||
fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
|
||||
let (run_by_root, nested, run_by_stray, stray) = (NetworkId(1), NetworkId(2), NetworkId(3), NetworkId(4));
|
||||
let node = |network, runs| crate::Node {
|
||||
presence: TimeStamp::default(),
|
||||
network,
|
||||
network_timestamp: TimeStamp::default(),
|
||||
implementation: Implementation::Network(runs),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: Vec::new(),
|
||||
inputs_timestamp: TimeStamp::default(),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut registry = Registry::default();
|
||||
for (id, network, runs) in [(1, crate::ROOT_NETWORK, run_by_root), (2, run_by_root, nested), (3, stray, run_by_stray)] {
|
||||
registry.node_instances.insert(crate::NodeId(id), node(network, runs));
|
||||
}
|
||||
for id in [run_by_root, nested, run_by_stray] {
|
||||
let mark = crate::Tombstone {
|
||||
content: Network::default(),
|
||||
timestamp: TimeStamp::default(),
|
||||
placeholder: false,
|
||||
};
|
||||
registry.removed_networks.insert(id, mark);
|
||||
}
|
||||
|
||||
let rendered = registry.as_rendered();
|
||||
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
|
||||
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
|
||||
}
|
||||
@@ -9,8 +9,9 @@ use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::blob::{BlobBytes, decode_blob};
|
||||
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
use crate::{BlobHash, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -22,6 +23,8 @@ pub enum ConversionError {
|
||||
DeclarationNotFound(ResourceId),
|
||||
#[error("Deserialization error: {0}")]
|
||||
DeserializationError(String),
|
||||
#[error("Blob {0} not found in provided blobs")]
|
||||
BlobNotFound(BlobHash),
|
||||
#[error("Network {network} has two nodes mapping to runtime ID {runtime_id}")]
|
||||
DuplicateRuntimeNodeId { network: NetworkId, runtime_id: u64 },
|
||||
#[error("Network {network} references node {referenced}, which lives in a different network")]
|
||||
@@ -40,8 +43,8 @@ pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
||||
impl Registry {
|
||||
/// Returns the network plus one metadata entry per node, since every node carries an identity to
|
||||
/// restore even when it has no `ui::*` attribute.
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations, blobs)?;
|
||||
Ok((network, node_entries))
|
||||
}
|
||||
|
||||
@@ -50,11 +53,11 @@ impl Registry {
|
||||
///
|
||||
/// Every network the root reaches becomes an entry in the root's definitions table under its storage ID.
|
||||
/// The nodes that implement it name it by that ID.
|
||||
pub fn to_runtime_with_full_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>, Vec<NetworkMetadataEntry>), ConversionError> {
|
||||
pub fn to_runtime_with_full_metadata(&self, declarations: &Declarations, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>, Vec<NetworkMetadataEntry>), ConversionError> {
|
||||
let mut node_metadata = Vec::new();
|
||||
let mut network_metadata = Vec::new();
|
||||
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
let context = ConversionContext::new(self, declarations, blobs);
|
||||
|
||||
// Reject cycles first because the runtime cannot inline a definition that contains itself
|
||||
detect_network_cycle(&context, ROOT_NETWORK)?;
|
||||
@@ -96,11 +99,12 @@ impl Registry {
|
||||
struct ConversionContext<'a> {
|
||||
registry: &'a Registry,
|
||||
declarations: &'a Declarations,
|
||||
blobs: &'a BlobBytes,
|
||||
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
||||
}
|
||||
|
||||
impl<'a> ConversionContext<'a> {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations, blobs: &'a BlobBytes) -> Self {
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in ®istry.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
@@ -108,10 +112,17 @@ impl<'a> ConversionContext<'a> {
|
||||
Self {
|
||||
registry,
|
||||
declarations,
|
||||
blobs,
|
||||
nodes_by_network,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value stored in blob `hash`.
|
||||
fn resolve_blob(&self, hash: BlobHash) -> Result<Value, ConversionError> {
|
||||
let bytes = self.blobs.get(&hash).ok_or(ConversionError::BlobNotFound(hash))?;
|
||||
decode_blob(bytes).map_err(|error| ConversionError::DeserializationError(format!("Blob {hash}: {error}")))
|
||||
}
|
||||
|
||||
/// The networks other than the root that the root reaches through node implementations.
|
||||
fn reachable_definitions(&self) -> FxHashSet<NetworkId> {
|
||||
let mut reached = FxHashSet::default();
|
||||
@@ -175,8 +186,8 @@ pub struct RuntimeProjection<'a> {
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations, blobs: &'a BlobBytes) -> RuntimeProjection<'a> {
|
||||
let context = ConversionContext::new(self, declarations, blobs);
|
||||
RuntimeProjection {
|
||||
reachable: context.reachable_definitions(),
|
||||
context,
|
||||
@@ -190,6 +201,21 @@ impl RuntimeProjection<'_> {
|
||||
(network == ROOT_NETWORK || self.reachable.contains(&network)).then(|| runtime_location(network))
|
||||
}
|
||||
|
||||
pub fn definitions(&self) -> impl Iterator<Item = RuntimeNetworkId> + '_ {
|
||||
self.reachable.iter().map(|&id| runtime_network_id(id))
|
||||
}
|
||||
|
||||
pub fn network_nodes(&self, network: NetworkId) -> impl Iterator<Item = NodeId> + '_ {
|
||||
self.context.nodes_by_network.get(&network).into_iter().flatten().map(|&(id, _)| id)
|
||||
}
|
||||
|
||||
pub fn implemented_network(&self, id: NodeId) -> Option<NetworkId> {
|
||||
match self.context.registry.node_instances.get(&id)?.implementation {
|
||||
Implementation::Network(network) => Some(network),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The location of the node's network in the runtime, and the node's ID in that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(NetworkLocation, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
@@ -225,7 +251,7 @@ impl RuntimeProjection<'_> {
|
||||
Ok(ProjectedNetwork {
|
||||
metadata: extract_network_metadata(registry, &network.attributes, location, id),
|
||||
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
|
||||
exports: convert_exports(registry, id, network)?,
|
||||
exports: convert_exports(&self.context, id, network)?,
|
||||
network: location,
|
||||
})
|
||||
}
|
||||
@@ -233,7 +259,7 @@ impl RuntimeProjection<'_> {
|
||||
|
||||
/// Rejects a registry whose root reaches a network cycle.
|
||||
pub(crate) fn reject_network_cycles(registry: &Registry, declarations: &Declarations) -> Result<(), ConversionError> {
|
||||
detect_network_cycle(&ConversionContext::new(registry, declarations), ROOT_NETWORK)
|
||||
detect_network_cycle(&ConversionContext::new(registry, declarations, &BlobBytes::new()), ROOT_NETWORK)
|
||||
}
|
||||
|
||||
/// Rejects any cycle in the graph of `Implementation::Network` references from a network to the networks its nodes implement.
|
||||
@@ -314,7 +340,7 @@ fn convert_network(
|
||||
}
|
||||
}
|
||||
|
||||
let exports = convert_exports(context.registry, network_id, network)?;
|
||||
let exports = convert_exports(context, network_id, network)?;
|
||||
let scope_injections = read_scope_injections(context.registry, network_id, &network.attributes)?;
|
||||
|
||||
Ok(NodeNetwork {
|
||||
@@ -327,14 +353,14 @@ fn convert_network(
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
fn convert_exports(context: &ConversionContext, 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))
|
||||
.map(|input| convert_input(context, network_id, input, &empty_attrs))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -438,7 +464,7 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
|
||||
let inputs = node
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|slot| convert_input(context.registry, node.network, &slot.input, &slot.attributes))
|
||||
.map(|slot| convert_input(context, node.network, &slot.input, &slot.attributes))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// Defaults must match `DocumentNode::default()` (and the `set_if_not_default` calls in `from_runtime`).
|
||||
@@ -454,7 +480,9 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
fn convert_input(context: &ConversionContext, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
let registry = context.registry;
|
||||
|
||||
Ok(match input {
|
||||
NodeInput::Node { id: node_id, index: output_index } => {
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
|
||||
@@ -477,7 +505,12 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
|
||||
}
|
||||
}
|
||||
NodeInput::Value { value, exposed } => {
|
||||
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
||||
let value = match value {
|
||||
Value::Blob(hash) => Cow::Owned(context.resolve_blob(*hash)?),
|
||||
value => Cow::Borrowed(value),
|
||||
};
|
||||
|
||||
let tagged_value: TaggedValue = from_value(&value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
||||
GraphCraftNodeInput::Value {
|
||||
tagged_value: MemoHash::new(tagged_value),
|
||||
exposed: *exposed,
|
||||
|
||||
@@ -27,7 +27,7 @@ impl From<serde_json::Value> for Value {
|
||||
}
|
||||
Json::String(string) => Value::Str(string),
|
||||
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
|
||||
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
||||
Json::Object(object) => Value::from_object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ impl From<Value> for serde_json::Value {
|
||||
Value::Str(string) => Json::String(string),
|
||||
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
|
||||
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
||||
Value::Blob(hash) => serde_json::json!({ Value::BLOB_KEY: String::from(&hash.0) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +59,7 @@ pub struct ValueError(serde_json::Error);
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{BlobHash, ResourceHash};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[test]
|
||||
@@ -157,5 +159,26 @@ mod tests {
|
||||
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
|
||||
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
|
||||
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
|
||||
assert_eq!(encode(Value::Blob(BlobHash(ResourceHash::from([9; 32]))))[..2], [7, 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_round_trips_as_reserved_object() {
|
||||
let blob = Value::Blob(BlobHash::of(b"bytes"));
|
||||
|
||||
let text = serde_json::to_string(&blob).unwrap();
|
||||
assert!(text.starts_with(r#"{"$blob":""#), "got {text}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), blob);
|
||||
assert_eq!(Value::from(serde_json::Value::from(blob.clone())), blob);
|
||||
|
||||
let bytes = postcard::to_stdvec(&blob).unwrap();
|
||||
assert_eq!(postcard::from_bytes::<Value>(&bytes).unwrap(), blob);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_key_without_a_hash_stays_an_object() {
|
||||
for json in [r#"{"$blob": "not a hash"}"#, r#"{"$blob": 1}"#, r#"{"$blob": "", "other": 1}"#] {
|
||||
assert!(matches!(serde_json::from_str::<Value>(json).unwrap(), Value::Object(_)), "{json}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "document-live"
|
||||
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-format = { workspace = true, features = ["network"] }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,109 @@
|
||||
//! A memory-backed document in a collaborative session. The caller spawns the transport driver.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
#[error(transparent)]
|
||||
Format(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
Conversion(#[from] ConversionError),
|
||||
}
|
||||
|
||||
pub struct LiveDocument {
|
||||
gdd: GddV1,
|
||||
token: SessionToken,
|
||||
}
|
||||
|
||||
impl LiveDocument {
|
||||
/// Host an empty document under `token`. `spawn` must drive the returned future for the whole session.
|
||||
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let gdd = Self::empty_document(peer, user).await?;
|
||||
Self::host_document(gdd, signaling_server, token, user, spawn)
|
||||
}
|
||||
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
gdd.share(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let mut gdd = Self::empty_document(peer, user).await?;
|
||||
gdd.connect(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
fn connect(signaling_server: &str, token: SessionToken, spawn: impl FnOnce(MessageLoopFuture)) -> Room {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
room
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId, user: UserId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, user, peer.0, version.clone(), version)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
pub fn missing_resources(&self) -> Vec<ResourceHash> {
|
||||
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// Apply what peers sent and answer their requests. Call it regularly.
|
||||
pub async fn poll(&mut self) -> Vec<Event> {
|
||||
let events = self.gdd.poll_peers();
|
||||
for event in &events {
|
||||
let Event::ResourceRequested { from, hash } = event else { continue };
|
||||
match self.gdd.read_resource(hash).await {
|
||||
Ok(bytes) => {
|
||||
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
|
||||
log::warn!("Failed to send resource {hash}: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub fn document(&self) -> &GddV1 {
|
||||
&self.gdd
|
||||
}
|
||||
|
||||
pub fn document_mut(&mut self) -> &mut GddV1 {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ graph-craft = { workspace = true }
|
||||
graphene-std = { workspace = true }
|
||||
migration-core = { workspace = true, features = ["typed"] }
|
||||
preprocessor = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
migration-runner = { workspace = true, features = ["testing"] }
|
||||
serde = { workspace = true }
|
||||
@@ -1,3 +1,4 @@
|
||||
use document_graph_storage::blob::BlobBytes;
|
||||
use document_graph_storage::{Declarations, Implementation, NodeId, Registry, ResourceId};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::{NodeId as RuntimeNodeId, NodeNetwork};
|
||||
@@ -58,8 +59,9 @@ impl MigrationHost for CompilerHost {
|
||||
}
|
||||
}
|
||||
|
||||
// A state that doesn't convert answers nothing, so each migration asking takes its fallback
|
||||
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations).ok()?;
|
||||
// A state that doesn't convert answers nothing, so each migration asking takes its fallback.
|
||||
// Node migrations only see states with resolved blobs, so no blobs are needed.
|
||||
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations, &BlobBytes::new()).ok()?;
|
||||
inlined.inline_definitions().ok()?;
|
||||
|
||||
Some(Box::new(StateCompiler {
|
||||
|
||||
@@ -2,5 +2,6 @@
|
||||
//! Unlike `migration-nodes`, these link the node crates and depend on the build they run in, so a document's peers can't all reach the same result.
|
||||
|
||||
mod compiler;
|
||||
mod vary_nodes_from_copy_to_points;
|
||||
|
||||
pub use compiler::CompilerHost;
|
||||
@@ -0,0 +1,272 @@
|
||||
use document_graph_storage::attr::node::VISIBLE;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONTENT: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
fn number(input: &NodeInput) -> Option<f64> {
|
||||
match literal_of::<Tagged>(input) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy to Points becomes Into Group, Repeat on Points, Vary Rotations, Vary Scales, and a flatten back to the content's element type, ending at the
|
||||
/// anchor to keep its downstream wires. Grouping makes each copy one row for the vary nodes, and keeps the offsets of its content, whose translation
|
||||
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
|
||||
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
|
||||
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
|
||||
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
|
||||
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
|
||||
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
|
||||
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
|
||||
|
||||
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
|
||||
let unset = || literal(Tagged::Bool(false));
|
||||
|
||||
let visible = node.attributes().get_or(VISIBLE, true);
|
||||
if !visible {
|
||||
target.set(repeat);
|
||||
replace_inputs(inputs, vec![points, content, unset()]);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let content_type = compiler.and_then(|compiler| compiler.input_type(node, CONTENT));
|
||||
|
||||
let fallback = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
|
||||
let flatten = match &content_type {
|
||||
Some(content) if content.element_is::<Vector>() => decl!("graphic_nodes::graphic::FlattenVectorNode"@1),
|
||||
Some(content) if content.element_is::<Raster<CPU>>() => decl!("graphic_nodes::graphic::FlattenRasterNode"@1),
|
||||
Some(content) if content.element_is::<Color>() => decl!("graphic_nodes::graphic::FlattenColorNode"@1),
|
||||
Some(content) if content.element_is::<Gradient>() => decl!("graphic_nodes::graphic::FlattenGradientNode"@1),
|
||||
_ => fallback,
|
||||
};
|
||||
|
||||
// Text has no group to go in, so its rows are repeated as they are
|
||||
let groups = !content_type.as_ref().is_some_and(|content| content.element_is::<String>());
|
||||
let group = groups.then(|| {
|
||||
upstream.add_node(NewNode {
|
||||
declaration: decl!("graphic_nodes::graphic::IntoGroupNode"@1),
|
||||
inputs: vec![content.clone()],
|
||||
})
|
||||
});
|
||||
let repeated_content = group.map_or(content, |group| NodeInput::Node { id: group, index: 0 });
|
||||
|
||||
let mut stages = vec![(repeat, vec![points, repeated_content, unset()])];
|
||||
|
||||
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
|
||||
if number(&rotation) != Some(0.) {
|
||||
let mut half = |factor: f64, key: &str| match number(&rotation) {
|
||||
Some(rotation) => literal(Tagged::Number(rotation * factor)),
|
||||
None => {
|
||||
let multiply = upstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: decl!("math_nodes::MultiplyNode"@1),
|
||||
inputs: vec![rotation.clone(), literal(Tagged::Number(factor))],
|
||||
},
|
||||
key,
|
||||
);
|
||||
NodeInput::Node { id: multiply, index: 0 }
|
||||
}
|
||||
};
|
||||
let (min, max) = (half(-0.5, "min"), half(0.5, "max"));
|
||||
stages.push((
|
||||
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
|
||||
vec![
|
||||
unset(),
|
||||
min,
|
||||
max,
|
||||
literal(Tagged::Number(0.5)),
|
||||
unset(),
|
||||
literal(Tagged::Bool(true)),
|
||||
rotation_seed,
|
||||
literal(Tagged::Integer(0)),
|
||||
],
|
||||
));
|
||||
}
|
||||
|
||||
// A wired bias can't be converted, so it is left at the default
|
||||
if number(&scale_min) != Some(1.) || number(&scale_max) != Some(1.) {
|
||||
let bias = number(&scale_bias).map_or(0.5, bias_keeping_average_scale);
|
||||
stages.push((
|
||||
decl!("transform_nodes::transform_nodes::VaryScalesNode"@1),
|
||||
vec![
|
||||
unset(),
|
||||
scale_min,
|
||||
scale_max,
|
||||
literal(Tagged::Number(bias)),
|
||||
unset(),
|
||||
literal(Tagged::Bool(true)),
|
||||
scale_seed,
|
||||
literal(Tagged::Integer(0)),
|
||||
],
|
||||
));
|
||||
}
|
||||
|
||||
if groups {
|
||||
let fully_flatten = (flatten == fallback).then(unset);
|
||||
stages.push((flatten, std::iter::once(unset()).chain(fully_flatten).collect()));
|
||||
}
|
||||
|
||||
// Each stage reads the one before it, up to the last, which is the anchor
|
||||
let Some((last_declaration, mut last_inputs)) = stages.pop() else { return Ok(()) };
|
||||
let mut previous = None;
|
||||
for (declaration, mut stage_inputs) in stages {
|
||||
if let Some(id) = previous {
|
||||
stage_inputs[0] = NodeInput::Node { id, index: 0 };
|
||||
}
|
||||
previous = Some(upstream.add_node(NewNode { declaration, inputs: stage_inputs }));
|
||||
}
|
||||
if let Some(id) = previous {
|
||||
last_inputs[0] = NodeInput::Node { id, index: 0 };
|
||||
}
|
||||
|
||||
target.set(last_declaration);
|
||||
replace_inputs(inputs, last_inputs);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace_inputs(inputs: &mut Inputs, replacement: Vec<NodeInput>) {
|
||||
inputs.truncate(0);
|
||||
for input in replacement {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that Copy to Points' random scale distribution had for its bias.
|
||||
fn bias_keeping_average_scale(bias: f64) -> f64 {
|
||||
if bias.abs() < 1e-6 {
|
||||
return 0.5;
|
||||
}
|
||||
|
||||
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
|
||||
let x = bias * std::f64::consts::LN_2;
|
||||
let average = -1. / (-x).exp_m1() - 1. / x;
|
||||
|
||||
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
|
||||
if average < 0.5 {
|
||||
let k = average / (1. - average);
|
||||
1. - (-k).exp2()
|
||||
} else {
|
||||
let p = 1. / average - 1.;
|
||||
(-p).exp2()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::CompilerHost;
|
||||
use migration_core::Declaration;
|
||||
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
|
||||
|
||||
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
|
||||
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
|
||||
const FLATTEN_VECTOR: Declaration = decl!("graphic_nodes::graphic::FlattenVectorNode"@1);
|
||||
const FLATTEN_GRAPHIC: Declaration = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
|
||||
const VARY_ROTATIONS: Declaration = decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2);
|
||||
|
||||
fn host() -> CompilerHost {
|
||||
CompilerHost::default()
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random: &mut Random, slot| match slot {
|
||||
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
|
||||
_ => literal(Tagged::Integer(random.below(3) as i64)),
|
||||
})
|
||||
}
|
||||
|
||||
fn star_inputs() -> Vec<NodeInput> {
|
||||
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
|
||||
}
|
||||
|
||||
fn inputs(content: NodeInput, scale: f64, rotation: f64) -> Vec<NodeInput> {
|
||||
let number = |number| literal(Tagged::Number(number));
|
||||
let integer = |integer| literal(Tagged::Integer(integer));
|
||||
vec![literal(Tagged::Integer(0)), content, number(scale), number(scale), number(0.), integer(1), number(rotation), integer(2)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let host = host();
|
||||
check_commutation_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
|
||||
check_undo_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_content_ends_in_the_flatten_of_its_element() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let star = fixture.add(STAR, star_inputs());
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 0.));
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_VECTOR));
|
||||
assert_eq!(fixture.inputs(&migrated, copies).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_that_does_not_compile_keeps_flatten_graphic() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let unknown = fixture.add(decl!("migration_testing::unknown"@1), vec![]);
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: unknown, index: 0 }, 2., 0.));
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_GRAPHIC));
|
||||
assert_eq!(fixture.inputs(&migrated, copies).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_repeated_without_a_group() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let text = fixture.add(decl!("text_nodes::AsStringNode"@1), vec![literal(Tagged::Number(1.))]);
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: text, index: 0 }, 1., 90.));
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
assert_eq!(fixture.declaration_of(&migrated, copies), Some(VARY_ROTATIONS));
|
||||
|
||||
let NodeInput::Node { id: repeat, .. } = fixture.inputs(&migrated, copies)[0] else {
|
||||
panic!("the rotations read the repeat")
|
||||
};
|
||||
assert_eq!(fixture.inputs(&migrated, repeat)[1], NodeInput::Node { id: text, index: 0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_range_is_centered() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let star = fixture.add(STAR, star_inputs());
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 90.));
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
let NodeInput::Node { id: rotations, .. } = fixture.inputs(&migrated, copies)[0] else {
|
||||
panic!("the flatten reads the last stage")
|
||||
};
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, rotations), Some(VARY_ROTATIONS));
|
||||
assert_eq!(number(&fixture.inputs(&migrated, rotations)[1]), Some(-45.));
|
||||
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_keeps_its_average() {
|
||||
assert_eq!(bias_keeping_average_scale(0.), 0.5);
|
||||
assert!(bias_keeping_average_scale(-10.) < 0.5);
|
||||
assert!(bias_keeping_average_scale(10.) > 0.5);
|
||||
assert!(bias_keeping_average_scale(100.).is_finite());
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ typed = ["dep:document-graph-storage", "dep:blake3"]
|
||||
[dependencies]
|
||||
document-graph-storage = { workspace = true, optional = true }
|
||||
migration-macros = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
|
||||
blake3 = { workspace = true, optional = true }
|
||||
ctor = { workspace = true }
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
use crate::{MigrationError, Payload};
|
||||
|
||||
/// How stored history survives a format step.
|
||||
@@ -15,6 +19,22 @@ pub enum HistoryPolicy {
|
||||
Truncate,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DocumentPayloads {
|
||||
pub format_version: u32,
|
||||
pub registry: Option<Payload>,
|
||||
pub history: Vec<Payload>,
|
||||
pub hot_log: Vec<Payload>,
|
||||
pub session: Option<Payload>,
|
||||
/// Blobs that steps moved values into. The load path stores them.
|
||||
pub blobs: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// The base blob of each blob in `blobs`.
|
||||
pub blob_bases: HashMap<ResourceHash, ResourceHash>,
|
||||
}
|
||||
|
||||
/// 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`. Steps only transform payload
|
||||
@@ -42,6 +62,10 @@ pub trait FormatMigration: Send + Sync {
|
||||
fn migrate_session(&self, session: &Payload) -> Result<Payload, MigrationError> {
|
||||
Ok(session.clone())
|
||||
}
|
||||
/// Transform the whole document after its records are converted. Use this when a change needs state across records.
|
||||
fn migrate_document(&self, _document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a frozen stored type to its counterpart in the next format version. `cargo run migration snapshot`
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use declaration::{Declaration, DeclarationResolver};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use document_graph_storage::NodeInput;
|
||||
pub use error::MigrationError;
|
||||
pub use format::{FormatMigration, HistoryPolicy, Upgrade};
|
||||
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use migration::{NodeMigration, Rename};
|
||||
pub use migration_macros::format_migration;
|
||||
|
||||
@@ -11,11 +11,11 @@ publish.workspace = true
|
||||
migration-core = { workspace = true }
|
||||
graphene-resource = { workspace = true, features = ["serde"] }
|
||||
|
||||
postcard = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
document-graph-storage = { workspace = true }
|
||||
|
||||
postcard = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod v1;
|
||||
pub mod v2;
|
||||
pub mod v3;
|
||||
pub use v3 as latest;
|
||||
pub mod v4;
|
||||
pub use v4 as latest;
|
||||
|
||||
mod steps;
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
mod v1_to_v2;
|
||||
mod v2_to_v3;
|
||||
mod v3_to_v4;
|
||||
@@ -0,0 +1,667 @@
|
||||
//! Format step 3 to 4, generated by `cargo run migration snapshot`.
|
||||
|
||||
use crate::{v3, v4};
|
||||
use graphene_resource::ResourceHash;
|
||||
use migration_core::{DocumentPayloads, MigrationError, Upgrade, format_migration};
|
||||
use std::collections::HashMap;
|
||||
|
||||
format_migration! {
|
||||
3 => 4,
|
||||
registry: v3::Registry,
|
||||
delta: v3::Delta,
|
||||
hot_op: v3::HotOp,
|
||||
session: v3::SessionState,
|
||||
document: move_values_into_blobs,
|
||||
}
|
||||
|
||||
impl Upgrade for v3::AttributeValue {
|
||||
type Next = v4::AttributeValue;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::AttributeValue { value, timestamp, deleted } = self;
|
||||
Ok(v4::AttributeValue {
|
||||
value: Upgrade::upgrade(value)?,
|
||||
timestamp,
|
||||
deleted,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Attributes {
|
||||
type Next = v4::Attributes;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::Attributes { entries, floor } = self;
|
||||
Ok(v4::Attributes {
|
||||
entries: entries
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
floor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Delta {
|
||||
type Next = v4::Delta;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::Delta {
|
||||
id,
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
kind,
|
||||
reverse,
|
||||
attributes,
|
||||
retired_at_ms,
|
||||
} = self;
|
||||
Ok(v4::Delta {
|
||||
id,
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
kind: Upgrade::upgrade(kind)?,
|
||||
reverse: reverse.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
retired_at_ms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::RegistryDelta {
|
||||
type Next = v4::RegistryDelta;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::RegistryDelta::AddNode { id, node } => v4::RegistryDelta::AddNode { id, node: Upgrade::upgrade(node)? },
|
||||
v3::RegistryDelta::RemoveNode { id, snapshot } => v4::RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: Upgrade::upgrade(snapshot)?,
|
||||
},
|
||||
v3::RegistryDelta::ChangeNodeInput { id, index, new_input } => v4::RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index,
|
||||
new_input: Upgrade::upgrade(new_input)?,
|
||||
},
|
||||
v3::RegistryDelta::SetNodeInputs { id, inputs } => v4::RegistryDelta::SetNodeInputs {
|
||||
id,
|
||||
inputs: inputs.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
},
|
||||
v3::RegistryDelta::SetNodeImplementation { id, implementation } => v4::RegistryDelta::SetNodeImplementation { id, implementation },
|
||||
v3::RegistryDelta::ChangeNodeAttribute { id, delta } => v4::RegistryDelta::ChangeNodeAttribute { id, delta: Upgrade::upgrade(delta)? },
|
||||
v3::RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => v4::RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: Upgrade::upgrade(delta)?,
|
||||
},
|
||||
v3::RegistryDelta::SetNetworkExport { id, index, export } => v4::RegistryDelta::SetNetworkExport {
|
||||
id,
|
||||
index,
|
||||
export: export.map(Upgrade::upgrade).transpose()?,
|
||||
},
|
||||
v3::RegistryDelta::ChangeNetworkAttribute { id, delta } => v4::RegistryDelta::ChangeNetworkAttribute { id, delta: Upgrade::upgrade(delta)? },
|
||||
v3::RegistryDelta::AddNetwork { id, network } => v4::RegistryDelta::AddNetwork {
|
||||
id,
|
||||
network: Upgrade::upgrade(network)?,
|
||||
},
|
||||
v3::RegistryDelta::RemoveNetwork { id, snapshot } => v4::RegistryDelta::RemoveNetwork {
|
||||
id,
|
||||
snapshot: Upgrade::upgrade(snapshot)?,
|
||||
},
|
||||
v3::RegistryDelta::AddResource { id, entry } => v4::RegistryDelta::AddResource { id, entry: Upgrade::upgrade(entry)? },
|
||||
v3::RegistryDelta::SetResourceHash { id, hash } => v4::RegistryDelta::SetResourceHash { id, hash },
|
||||
v3::RegistryDelta::RemoveResource { id, snapshot } => v4::RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: Upgrade::upgrade(snapshot)?,
|
||||
},
|
||||
v3::RegistryDelta::AddSource { id, key, source } => v4::RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Upgrade::upgrade(source)?,
|
||||
},
|
||||
v3::RegistryDelta::RemoveSource { id, key } => v4::RegistryDelta::RemoveSource { id, key },
|
||||
v3::RegistryDelta::RegisterPeer { peer, user } => v4::RegistryDelta::RegisterPeer { peer, user },
|
||||
v3::RegistryDelta::ChangeDocumentAttribute { delta } => v4::RegistryDelta::ChangeDocumentAttribute { delta: Upgrade::upgrade(delta)? },
|
||||
v3::RegistryDelta::Merge { extra_parents } => v4::RegistryDelta::Merge { extra_parents },
|
||||
v3::RegistryDelta::Meta => v4::RegistryDelta::Meta,
|
||||
v3::RegistryDelta::Other(field_0) => v4::RegistryDelta::Other(Upgrade::upgrade(field_0)?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::AttributeDelta {
|
||||
type Next = v4::AttributeDelta;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::AttributeDelta { key, value } = self;
|
||||
Ok(v4::AttributeDelta {
|
||||
key,
|
||||
value: value.map(Upgrade::upgrade).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Node {
|
||||
type Next = v4::Node;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::Node {
|
||||
presence,
|
||||
network,
|
||||
network_timestamp,
|
||||
implementation,
|
||||
implementation_timestamp,
|
||||
inputs,
|
||||
inputs_timestamp,
|
||||
attributes,
|
||||
} = self;
|
||||
Ok(v4::Node {
|
||||
presence,
|
||||
network,
|
||||
network_timestamp,
|
||||
implementation,
|
||||
implementation_timestamp,
|
||||
inputs: inputs.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
inputs_timestamp,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::InputSlot {
|
||||
type Next = v4::InputSlot;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::InputSlot { input, timestamp, attributes } = self;
|
||||
Ok(v4::InputSlot {
|
||||
input: Upgrade::upgrade(input)?,
|
||||
timestamp,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::NodeInput {
|
||||
type Next = v4::NodeInput;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::NodeInput::Node { id, index } => v4::NodeInput::Node { id, index },
|
||||
v3::NodeInput::Value { value, exposed } => v4::NodeInput::Value {
|
||||
value: Upgrade::upgrade(value)?,
|
||||
exposed,
|
||||
},
|
||||
v3::NodeInput::Scope(field_0) => v4::NodeInput::Scope(field_0),
|
||||
v3::NodeInput::Import { index } => v4::NodeInput::Import { index },
|
||||
v3::NodeInput::Reflection => v4::NodeInput::Reflection,
|
||||
v3::NodeInput::Other => v4::NodeInput::Other,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Network {
|
||||
type Next = v4::Network;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::Network {
|
||||
presence,
|
||||
exports,
|
||||
exports_timestamp,
|
||||
attributes,
|
||||
} = self;
|
||||
Ok(v4::Network {
|
||||
presence,
|
||||
exports: exports.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
exports_timestamp,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::ExportSlot {
|
||||
type Next = v4::ExportSlot;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::ExportSlot { target, timestamp } = self;
|
||||
Ok(v4::ExportSlot {
|
||||
target: target.map(Upgrade::upgrade).transpose()?,
|
||||
timestamp,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::ProtoNode {
|
||||
type Next = v4::ProtoNode;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::ProtoNode { identifier, version, attributes } = self;
|
||||
Ok(v4::ProtoNode {
|
||||
identifier,
|
||||
version,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Prior {
|
||||
type Next = v4::Prior;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::Prior::Node { id, node } => v4::Prior::Node { id, node: Upgrade::upgrade(node)? },
|
||||
v3::Prior::RemovedNode { id, tombstone } => v4::Prior::RemovedNode {
|
||||
id,
|
||||
tombstone: {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
},
|
||||
},
|
||||
v3::Prior::AbsentNode { id } => v4::Prior::AbsentNode { id },
|
||||
v3::Prior::Network { id, network } => v4::Prior::Network {
|
||||
id,
|
||||
network: Upgrade::upgrade(network)?,
|
||||
},
|
||||
v3::Prior::RemovedNetwork { id, tombstone } => v4::Prior::RemovedNetwork {
|
||||
id,
|
||||
tombstone: {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
},
|
||||
},
|
||||
v3::Prior::AbsentNetwork { id } => v4::Prior::AbsentNetwork { id },
|
||||
v3::Prior::Resource { id, resource } => v4::Prior::Resource {
|
||||
id,
|
||||
resource: Upgrade::upgrade(resource)?,
|
||||
},
|
||||
v3::Prior::RemovedResource { id, tombstone } => v4::Prior::RemovedResource {
|
||||
id,
|
||||
tombstone: {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
},
|
||||
},
|
||||
v3::Prior::AbsentResource { id } => v4::Prior::AbsentResource { id },
|
||||
v3::Prior::NodeField { id, presence, field } => v4::Prior::NodeField {
|
||||
id,
|
||||
presence,
|
||||
field: Upgrade::upgrade(field)?,
|
||||
},
|
||||
v3::Prior::NetworkField { id, presence, field } => v4::Prior::NetworkField {
|
||||
id,
|
||||
presence,
|
||||
field: Upgrade::upgrade(field)?,
|
||||
},
|
||||
v3::Prior::DocumentAttribute { key, previous } => v4::Prior::DocumentAttribute {
|
||||
key,
|
||||
previous: previous.map(Upgrade::upgrade).transpose()?,
|
||||
},
|
||||
v3::Prior::PeerUser { peer, previous } => v4::Prior::PeerUser { peer, previous },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::NodeField {
|
||||
type Next = v4::NodeField;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::NodeField::Presence => v4::NodeField::Presence,
|
||||
v3::NodeField::Attribute { key, previous } => v4::NodeField::Attribute {
|
||||
key,
|
||||
previous: previous.map(Upgrade::upgrade).transpose()?,
|
||||
},
|
||||
v3::NodeField::Input { index, previous } => v4::NodeField::Input {
|
||||
index,
|
||||
previous: Upgrade::upgrade(previous)?,
|
||||
},
|
||||
v3::NodeField::InputAttribute { index, key, previous } => v4::NodeField::InputAttribute {
|
||||
index,
|
||||
key,
|
||||
previous: previous.map(Upgrade::upgrade).transpose()?,
|
||||
},
|
||||
v3::NodeField::Inputs { previous, inputs_timestamp } => v4::NodeField::Inputs {
|
||||
previous: previous.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
inputs_timestamp,
|
||||
},
|
||||
v3::NodeField::Implementation { previous, implementation_timestamp } => v4::NodeField::Implementation { previous, implementation_timestamp },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::NetworkField {
|
||||
type Next = v4::NetworkField;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::NetworkField::Presence => v4::NetworkField::Presence,
|
||||
v3::NetworkField::Attribute { key, previous } => v4::NetworkField::Attribute {
|
||||
key,
|
||||
previous: previous.map(Upgrade::upgrade).transpose()?,
|
||||
},
|
||||
v3::NetworkField::Exports { previous } => v4::NetworkField::Exports {
|
||||
previous: previous.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Registry {
|
||||
type Next = v4::Registry;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::Registry {
|
||||
node_instances,
|
||||
networks,
|
||||
resources,
|
||||
peer_users,
|
||||
attributes,
|
||||
removed_nodes,
|
||||
removed_networks,
|
||||
removed_resources,
|
||||
} = self;
|
||||
Ok(v4::Registry {
|
||||
node_instances: node_instances
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
networks: networks
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
resources: resources
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
peer_users,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
removed_nodes: removed_nodes
|
||||
.into_iter()
|
||||
.map(|(key, entry)| {
|
||||
Ok::<_, MigrationError>((key, {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = entry;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
removed_networks: removed_networks
|
||||
.into_iter()
|
||||
.map(|(key, entry)| {
|
||||
Ok::<_, MigrationError>((key, {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = entry;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
removed_resources: removed_resources
|
||||
.into_iter()
|
||||
.map(|(key, entry)| {
|
||||
Ok::<_, MigrationError>((key, {
|
||||
let v3::Tombstone { content, timestamp, placeholder } = entry;
|
||||
v4::Tombstone {
|
||||
content: Upgrade::upgrade(content)?,
|
||||
timestamp,
|
||||
placeholder,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::SourceValue {
|
||||
type Next = v4::SourceValue;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::SourceValue { source, timestamp, deleted } = self;
|
||||
Ok(v4::SourceValue {
|
||||
source: Upgrade::upgrade(source)?,
|
||||
timestamp,
|
||||
deleted,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::ResourceEntry {
|
||||
type Next = v4::ResourceEntry;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::ResourceEntry {
|
||||
presence,
|
||||
sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
} = self;
|
||||
Ok(v4::ResourceEntry {
|
||||
presence,
|
||||
sources: sources
|
||||
.into_iter()
|
||||
.map(|element| {
|
||||
Ok::<_, MigrationError>({
|
||||
let (element_0, element_1) = element;
|
||||
(element_0, Upgrade::upgrade(element_1)?)
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::HotOp {
|
||||
type Next = v4::HotOp;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::HotOp { op, timestamp, sequence, attributes } = self;
|
||||
Ok(v4::HotOp {
|
||||
op: Upgrade::upgrade(op)?,
|
||||
timestamp,
|
||||
sequence,
|
||||
attributes: Upgrade::upgrade(attributes)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::SessionState {
|
||||
type Next = v4::SessionState;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
let v3::SessionState {
|
||||
peer_id,
|
||||
user_id,
|
||||
head_rev,
|
||||
last_broadcast_rev,
|
||||
redo_stack,
|
||||
next_node_counter,
|
||||
last_hot_sequence,
|
||||
view_settings,
|
||||
network_view_settings,
|
||||
retired_marks,
|
||||
clock_counter,
|
||||
shared,
|
||||
} = self;
|
||||
Ok(v4::SessionState {
|
||||
peer_id,
|
||||
user_id,
|
||||
head_rev,
|
||||
last_broadcast_rev,
|
||||
redo_stack,
|
||||
next_node_counter,
|
||||
last_hot_sequence,
|
||||
view_settings: view_settings
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
network_view_settings: network_view_settings
|
||||
.into_iter()
|
||||
.map(|(key, entry)| {
|
||||
Ok::<_, MigrationError>((
|
||||
key,
|
||||
entry
|
||||
.into_iter()
|
||||
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
retired_marks,
|
||||
clock_counter,
|
||||
shared,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Upgrade for v3::Value {
|
||||
type Next = v4::Value;
|
||||
fn upgrade(self) -> Result<Self::Next, MigrationError> {
|
||||
Ok(match self {
|
||||
v3::Value::None => v4::Value::None,
|
||||
v3::Value::Bool(field_0) => v4::Value::Bool(field_0),
|
||||
v3::Value::Int(field_0) => v4::Value::Int(field_0),
|
||||
v3::Value::Float(field_0) => v4::Value::Float(field_0),
|
||||
v3::Value::Str(field_0) => v4::Value::Str(field_0),
|
||||
v3::Value::Array(field_0) => v4::Value::Array(field_0.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?),
|
||||
v3::Value::Object(field_0) => v4::Value::Object(
|
||||
field_0
|
||||
.into_iter()
|
||||
.map(|element| {
|
||||
Ok::<_, MigrationError>({
|
||||
let (element_0, element_1) = element;
|
||||
(element_0, Upgrade::upgrade(element_1)?)
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, MigrationError>>()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Values whose postcard encoding reaches this many bytes move into blobs. This is the live threshold at version 4.
|
||||
const BLOB_THRESHOLD: usize = 1024;
|
||||
|
||||
/// Move large node input values into blobs. Records are visited in stored order, so the base of a blob is the previous blob of its slot.
|
||||
fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
let mut blobs = Blobs::default();
|
||||
|
||||
for record in &mut document.history {
|
||||
let mut delta: v4::Delta = record.decode()?;
|
||||
blobs.op(&mut delta.kind);
|
||||
delta.reverse.iter_mut().for_each(|prior| blobs.prior(prior));
|
||||
*record = record.encode_as(&delta)?;
|
||||
}
|
||||
for record in &mut document.hot_log {
|
||||
let mut hot_op: v4::HotOp = record.decode()?;
|
||||
blobs.op(&mut hot_op.op);
|
||||
*record = record.encode_as(&hot_op)?;
|
||||
}
|
||||
if let Some(record) = &mut document.registry {
|
||||
let mut registry: v4::Registry = record.decode()?;
|
||||
// Sort by ID so the base choice does not depend on hash map order
|
||||
let mut nodes: Vec<_> = registry.node_instances.iter_mut().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
for (id, node) in nodes {
|
||||
blobs.node(*id, node);
|
||||
}
|
||||
registry.removed_nodes.values_mut().for_each(|tombstone| blobs.loose_node(&mut tombstone.content));
|
||||
*record = record.encode_as(®istry)?;
|
||||
}
|
||||
|
||||
document.blobs.extend(blobs.bytes);
|
||||
document.blob_bases.extend(blobs.bases);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Blobs {
|
||||
bytes: HashMap<ResourceHash, Vec<u8>>,
|
||||
bases: HashMap<ResourceHash, ResourceHash>,
|
||||
/// The last blob of each input slot, by node and input index.
|
||||
latest: HashMap<(v4::NodeId, u32), ResourceHash>,
|
||||
}
|
||||
|
||||
impl Blobs {
|
||||
fn op(&mut self, op: &mut v4::RegistryDelta) {
|
||||
match op {
|
||||
v4::RegistryDelta::AddNode { id, node } => self.node(*id, node),
|
||||
v4::RegistryDelta::RemoveNode { snapshot, .. } => self.loose_node(snapshot),
|
||||
v4::RegistryDelta::ChangeNodeInput { id, index, new_input } => self.write(*id, *index, new_input),
|
||||
v4::RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
for (index, slot) in (0..).zip(inputs) {
|
||||
self.write(*id, index, &mut slot.input);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Priors only restore earlier values, so they never change the latest blob of a slot.
|
||||
fn prior(&mut self, prior: &mut v4::Prior) {
|
||||
match prior {
|
||||
v4::Prior::Node { node, .. } => self.loose_node(node),
|
||||
v4::Prior::RemovedNode { tombstone, .. } => self.loose_node(&mut tombstone.content),
|
||||
v4::Prior::NodeField {
|
||||
field: v4::NodeField::Input { previous, .. },
|
||||
..
|
||||
} => {
|
||||
self.move_into_blob(&mut previous.input);
|
||||
}
|
||||
v4::Prior::NodeField {
|
||||
field: v4::NodeField::Inputs { previous, .. },
|
||||
..
|
||||
} => {
|
||||
for slot in previous {
|
||||
self.move_into_blob(&mut slot.input);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn node(&mut self, id: v4::NodeId, node: &mut v4::Node) {
|
||||
for (index, slot) in (0..).zip(&mut node.inputs) {
|
||||
self.write(id, index, &mut slot.input);
|
||||
}
|
||||
}
|
||||
|
||||
fn loose_node(&mut self, node: &mut v4::Node) {
|
||||
for slot in &mut node.inputs {
|
||||
self.move_into_blob(&mut slot.input);
|
||||
}
|
||||
}
|
||||
|
||||
/// A write into an input slot. Its blob is based on the previous blob of the slot.
|
||||
fn write(&mut self, id: v4::NodeId, index: u32, input: &mut v4::NodeInput) {
|
||||
let Some((hash, created)) = self.move_into_blob(input) else { return };
|
||||
|
||||
// Only a newly created blob takes a base. This keeps bases acyclic
|
||||
if let Some(previous) = self.latest.insert((id, index), hash)
|
||||
&& created
|
||||
&& previous != hash
|
||||
{
|
||||
self.bases.insert(hash, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// The blob that `input` now names, and whether this call created it.
|
||||
fn move_into_blob(&mut self, input: &mut v4::NodeInput) -> Option<(ResourceHash, bool)> {
|
||||
let v4::NodeInput::Value { value, .. } = input else { return None };
|
||||
if let v4::Value::Blob(hash) = value {
|
||||
return Some((hash.0, false));
|
||||
}
|
||||
|
||||
let encoded = postcard::to_stdvec(value).ok()?;
|
||||
if encoded.len() < BLOB_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
|
||||
let hash = ResourceHash::from(encoded.as_slice());
|
||||
*value = v4::Value::Blob(v4::BlobHash(hash));
|
||||
let created = self.bytes.insert(hash, encoded).is_none();
|
||||
Some((hash, created))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! Format version 4, frozen by `cargo run migration snapshot`. Never edit it: old documents decode through these definitions.
|
||||
|
||||
pub use super::v3::{HotOpId, HotSequence, Implementation, NetworkId, NodeId, NonFinitePriority, PeerId, PeerRegistration, Priority, RetiredMarks, Rev, SourceKey, TimeStamp, Tombstone, UserId};
|
||||
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(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, 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,
|
||||
#[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
|
||||
}
|
||||
}
|
||||
|
||||
#[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, 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(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HotOp {
|
||||
pub op: RegistryDelta,
|
||||
pub timestamp: TimeStamp,
|
||||
pub sequence: HotSequence,
|
||||
#[serde(default)]
|
||||
pub attributes: Attributes,
|
||||
}
|
||||
|
||||
#[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,
|
||||
#[serde(default)]
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct BlobHash(pub ResourceHash);
|
||||
|
||||
#[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)>),
|
||||
Blob(BlobHash),
|
||||
}
|
||||
|
||||
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))),
|
||||
Value::Blob(hash) => serializer.collect_map(std::iter::once((Value::BLOB_KEY, hash))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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::from_object(object))
|
||||
}
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a valid Value")
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_any(Untagged)
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub const BLOB_KEY: &str = "$blob";
|
||||
pub fn from_object(object: Vec<(String, Value)>) -> Self {
|
||||
if let [(key, Value::Str(hex))] = object.as_slice()
|
||||
&& key == Self::BLOB_KEY
|
||||
&& let Ok(hash) = ResourceHash::try_from(hex.as_str())
|
||||
{
|
||||
return Value::Blob(BlobHash(hash));
|
||||
}
|
||||
Value::Object(object)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! The step to version 4 moves large node input values into the same blobs that live staging makes.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes, decode_blob};
|
||||
use document_graph_storage::{Delta, HotOp, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, ResourceId, Session, UserId, Value};
|
||||
use migration_core::{DocumentPayloads, Payload, PayloadCodec};
|
||||
|
||||
// Format steps register when linked
|
||||
use migration_formats as _;
|
||||
|
||||
fn large_input(prefix: &str) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::Str(format!("{prefix}{}", "a".repeat(BLOB_THRESHOLD))),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn postcard_payload(value: &impl serde::Serialize) -> Payload {
|
||||
Payload::encode(value, PayloadCodec::Postcard).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_four_moves_large_values_into_blobs_based_on_their_slot() {
|
||||
// `Value::Blob` is the only change in version 4, so a version 3 document is a live one without blobs
|
||||
let id = NodeId(1);
|
||||
let mut session = Session::with_identity(PeerId(1), UserId(1));
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
|
||||
node.inputs_mut()[0].input = large_input("");
|
||||
let network = RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
};
|
||||
session.stage_computed_ops(vec![network, RegistryDelta::AddNode { id, node }]).unwrap();
|
||||
session
|
||||
.stage_computed_ops(vec![RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: 0,
|
||||
new_input: large_input("b"),
|
||||
}])
|
||||
.unwrap();
|
||||
session.retire_all().unwrap();
|
||||
session
|
||||
.stage_computed_ops(vec![RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: 0,
|
||||
new_input: large_input("c"),
|
||||
}])
|
||||
.unwrap();
|
||||
|
||||
let mut document = DocumentPayloads {
|
||||
format_version: 3,
|
||||
registry: Some(postcard_payload(session.retired_registry())),
|
||||
history: session.history().map(postcard_payload).collect(),
|
||||
hot_log: session.hot_log().iter().map(postcard_payload).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let steps = migration_core::registered_format_migrations();
|
||||
let step = steps.iter().find(|step| step.migrates_from() == 3).expect("the step into version 4");
|
||||
document.registry = Some(step.migrate_registry(document.registry.as_ref().unwrap()).unwrap());
|
||||
document.history = document.history.iter().map(|record| step.migrate_delta(record).unwrap()).collect();
|
||||
document.hot_log = document.hot_log.iter().map(|record| step.migrate_hot_op(record).unwrap()).collect();
|
||||
step.migrate_document(&mut document).unwrap();
|
||||
|
||||
// Both paths hash the same bytes, so the migrated blob equals the staged one
|
||||
let staged_blob = |input: NodeInput| {
|
||||
let mut input = input;
|
||||
input.move_into_blob(&mut BlobBytes::new());
|
||||
input.blob().unwrap()
|
||||
};
|
||||
let [first, second, third] = [large_input(""), large_input("b"), large_input("c")].map(staged_blob);
|
||||
|
||||
let history: Vec<Delta> = document.history.iter().map(|record| record.decode().unwrap()).collect();
|
||||
let hot_log: Vec<HotOp> = document.hot_log.iter().map(|record| record.decode().unwrap()).collect();
|
||||
let registry: Registry = document.registry.as_ref().unwrap().decode().unwrap();
|
||||
let written = |op: &RegistryDelta| match op {
|
||||
RegistryDelta::AddNode { node, .. } => node.inputs()[0].input.blob(),
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => new_input.blob(),
|
||||
_ => None,
|
||||
};
|
||||
let retired: Vec<_> = history.iter().filter_map(|delta| written(&delta.kind)).collect();
|
||||
let hot: Vec<_> = hot_log.iter().filter_map(|hot_op| written(&hot_op.op)).collect();
|
||||
assert_eq!(retired, [first, second]);
|
||||
assert_eq!(hot, [third]);
|
||||
assert_eq!(registry.node_instances[&id].inputs()[0].input.blob(), Some(second));
|
||||
|
||||
assert_eq!(document.blobs.len(), 3);
|
||||
let [first, second, third] = [first, second, third].map(|hash| hash.0);
|
||||
assert_eq!(decode_blob(&document.blobs[&third]).unwrap(), Value::Str(format!("c{}", "a".repeat(BLOB_THRESHOLD))));
|
||||
assert_eq!(document.blob_bases.get(&first), None, "the first value of a slot has nothing to be based on");
|
||||
assert_eq!(document.blob_bases.get(&second), Some(&first));
|
||||
assert_eq!(document.blob_bases.get(&third), Some(&second));
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::{Error, Ident, LitInt, Token, Type};
|
||||
use syn::{Error, Ident, LitInt, Path, Token, Type};
|
||||
|
||||
/// The stored roots a format step can convert, by the `FormatMigration` method converting each.
|
||||
const ROOTS: &[(&str, &str)] = &[
|
||||
@@ -16,6 +16,7 @@ pub(crate) struct FormatStep {
|
||||
pub from: u32,
|
||||
pub to: u32,
|
||||
roots: Vec<(Ident, Type)>,
|
||||
document: Option<Path>,
|
||||
}
|
||||
|
||||
impl Parse for FormatStep {
|
||||
@@ -34,8 +35,18 @@ impl Parse for FormatStep {
|
||||
}
|
||||
|
||||
let mut roots: Vec<(Ident, Type)> = Vec::new();
|
||||
let mut document = None;
|
||||
while input.parse::<Option<Token![,]>>()?.is_some() && !input.is_empty() {
|
||||
let root: Ident = input.parse()?;
|
||||
if root == "document" {
|
||||
if document.is_some() {
|
||||
return Err(Error::new(root.span(), "the document function is already named"));
|
||||
}
|
||||
input.parse::<Token![:]>()?;
|
||||
document = Some(input.parse()?);
|
||||
continue;
|
||||
}
|
||||
|
||||
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(", "))));
|
||||
@@ -48,7 +59,7 @@ impl Parse for FormatStep {
|
||||
roots.push((root, input.parse()?));
|
||||
}
|
||||
|
||||
Ok(Self { from, to, roots })
|
||||
Ok(Self { from, to, roots, document })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +86,14 @@ pub(crate) fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
|
||||
}
|
||||
});
|
||||
|
||||
let document = step.document.as_ref().map(|function| {
|
||||
quote! {
|
||||
fn migrate_document(&self, document: &mut #core::DocumentPayloads) -> ::core::result::Result<(), #core::MigrationError> {
|
||||
#function(document)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
quote! {
|
||||
struct FormatStep;
|
||||
|
||||
@@ -84,6 +103,7 @@ pub(crate) fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
|
||||
}
|
||||
#history_policy
|
||||
#(#methods)*
|
||||
#document
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ pub fn rename(input: TokenStream) -> TokenStream {
|
||||
|
||||
/// 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.
|
||||
/// `document: function` adds a pass over the whole converted document. Use it when a change needs state across records.
|
||||
#[proc_macro]
|
||||
pub fn format_migration(input: TokenStream) -> TokenStream {
|
||||
let step = parse_macro_input!(input as format::FormatStep);
|
||||
@@ -244,7 +245,7 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr
|
||||
quote! {
|
||||
use #core::ctor::ctor;
|
||||
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor)]
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = #core::ctor))]
|
||||
fn register() {
|
||||
#core::#register(#migration);
|
||||
}
|
||||
|
||||
@@ -12,8 +12,5 @@ migration-core = { workspace = true, features = ["typed"] }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
document-graph-storage = { workspace = true, default-features = false }
|
||||
migration-runner = { workspace = true, features = ["testing"] }
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
# Frozen mirrors of stored values, once a node migration needs one
|
||||
ignored = ["serde"]
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
@@ -0,0 +1,131 @@
|
||||
use migration_core::{Declaration, Downstream, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Target, decl, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const FILL: u32 = 1;
|
||||
const STROKE: u32 = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// Assign Colors splits by its Fill and Stroke toggles into Vary Fill Colors, Vary Stroke Colors, or both in a row, with the same parameters.
|
||||
/// A wired toggle counts as enabled, and with both off it only ever passed its content through, which a Passthrough still does. With both on,
|
||||
/// the stroke goes downstream of the anchor so toggling never rewires the content, since a wire written to a removed node would revive it.
|
||||
#[migration("graphene_core::vector::AssignColorsNode"@1 => "graphene_core::vector::VaryFillColorsNode"@2)]
|
||||
pub fn vary_colors_from_assign_colors(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, target: &mut Target) -> Result<(), MigrationError> {
|
||||
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
|
||||
if slots.len() != 8 {
|
||||
return Err(MigrationError::invariant("Assign Colors has eight inputs"));
|
||||
}
|
||||
|
||||
let enabled = |slot: u32| !matches!(literal_of::<Tagged>(&slots[slot as usize]), Some(Tagged::Bool(false)));
|
||||
let (fill, stroke) = (enabled(FILL), enabled(STROKE));
|
||||
|
||||
let vary_fill: Declaration = decl!("graphene_core::vector::VaryFillColorsNode"@2);
|
||||
let vary_stroke: Declaration = decl!("graphene_core::vector::VaryStrokeColorsNode"@1);
|
||||
|
||||
if !fill && !stroke {
|
||||
target.set(decl!("graphene_core::ops::PassthroughNode"@2));
|
||||
inputs.truncate(1);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
inputs.remove(STROKE);
|
||||
inputs.remove(FILL);
|
||||
|
||||
if !fill {
|
||||
target.set(vary_stroke);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
target.set(vary_fill);
|
||||
if stroke {
|
||||
let consumers = downstream.consumers(0);
|
||||
let mut stroke_inputs = vec![NodeInput::Node { id: node.id(), index: 0 }];
|
||||
stroke_inputs.extend(slots[3..].iter().cloned());
|
||||
|
||||
let strokes = downstream.add_node(NewNode {
|
||||
declaration: vary_stroke,
|
||||
inputs: stroke_inputs,
|
||||
});
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: strokes, output: 0 }, consumer);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const ASSIGN_COLORS: Declaration = decl!("graphene_core::vector::AssignColorsNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
// Only the content can read another Assign Colors, since the other inputs don't take its output type
|
||||
SourceContract {
|
||||
reads_own_output: |slot| slot == 0,
|
||||
..SourceContract::new(8, |random, slot| match slot {
|
||||
1 | 2 => literal(Tagged::Bool(random.below(2) == 0)),
|
||||
_ => literal(random.below(4) as f64),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn node(fill: bool, stroke: bool) -> Vec<NodeInput> {
|
||||
let parameter = |number: u32| literal(f64::from(number));
|
||||
vec![
|
||||
parameter(0),
|
||||
literal(Tagged::Bool(fill)),
|
||||
literal(Tagged::Bool(stroke)),
|
||||
parameter(3),
|
||||
parameter(4),
|
||||
parameter(5),
|
||||
parameter(6),
|
||||
parameter(7),
|
||||
]
|
||||
}
|
||||
|
||||
fn migrated_declaration(fill: bool, stroke: bool) -> (Option<Declaration>, usize) {
|
||||
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
|
||||
let anchor = fixture.add(ASSIGN_COLORS, node(fill, stroke));
|
||||
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
|
||||
(fixture.declaration_of(&migrated, anchor), fixture.inputs(&migrated, anchor).len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&VaryColorsFromAssignColors, &contract());
|
||||
check_undo(&VaryColorsFromAssignColors, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_toggle_chooses_its_node() {
|
||||
assert_eq!(migrated_declaration(true, false), (Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)), 6));
|
||||
assert_eq!(migrated_declaration(false, true), (Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)), 6));
|
||||
assert_eq!(migrated_declaration(false, false), (Some(decl!("graphene_core::ops::PassthroughNode"@2)), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_toggles_chain_fill_into_stroke() {
|
||||
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
|
||||
let anchor = fixture.add(ASSIGN_COLORS, node(true, true));
|
||||
fixture.export(NodeInput::Node { id: anchor, index: 0 });
|
||||
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, anchor)[0], literal(0.));
|
||||
|
||||
let export = migrated.networks[&document_graph_storage::ROOT_NETWORK].exports[0].target.clone();
|
||||
let Some(NodeInput::Node { id: strokes, .. }) = export else {
|
||||
panic!("the export reads the stroke")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, strokes), Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, strokes)[0], NodeInput::Node { id: anchor, index: 0 });
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,5 @@
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
@@ -0,0 +1,107 @@
|
||||
use migration_core::{Node, Target, decl, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const EXPRESSION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
String(String),
|
||||
}
|
||||
|
||||
/// The lone operators 'Math f(…)' applied across its items, in every spelling its classifier read when the node was split.
|
||||
const OPERATORS: &[&str] = &["+", "-", "*", "/", "^", "&&", "∧", "||", "∨", "<", "<=", "≤", ">", ">=", "≥", "==", "!=", "≠"];
|
||||
|
||||
/// The variadic functions 'Math f(…)' called with all its items when given a lone name, also spelled with a leading `\`.
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"hypot",
|
||||
"min",
|
||||
"max",
|
||||
"mean",
|
||||
"median",
|
||||
"variance",
|
||||
"variancepop",
|
||||
"stdev",
|
||||
"stdevpop",
|
||||
"geomean",
|
||||
"harmmean",
|
||||
"rms",
|
||||
"mode",
|
||||
"count",
|
||||
"xor",
|
||||
"gcd",
|
||||
"lcm",
|
||||
];
|
||||
|
||||
/// 'Math f(…)' split by the kind of string it held: a lone operator or function name, which it applied across its items, moves to
|
||||
/// 'Math Aggregate', and an expression stays as 'Math Formula'. A wired string can't be read before it runs, so it stays an expression.
|
||||
#[migration("math_nodes::MathFNode"@1 => "math_nodes::MathFormulaNode"@2)]
|
||||
pub fn math_formula_from_math_f(node: &Node, target: &mut Target) {
|
||||
let Some(slot) = node.inputs().get(EXPRESSION) else { return };
|
||||
let Some(Tagged::String(expression)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
let token = expression.trim();
|
||||
let function = token.strip_prefix('\\').unwrap_or(token);
|
||||
if OPERATORS.contains(&token) || FUNCTIONS.contains(&function) {
|
||||
target.set(decl!("math_nodes::MathAggregateNode"@1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const MATH_F: Declaration = decl!("math_nodes::MathFNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
// Only the items can read another 'Math f(…)', since the expression and output type don't take its number
|
||||
SourceContract {
|
||||
reads_own_output: |slot| slot == 0,
|
||||
..SourceContract::new(3, |random, slot| match slot {
|
||||
EXPRESSION => literal(Tagged::String(["+", "a * b", "\\max", " ≤ ", "min(a, b)"][random.below(5)].to_string())),
|
||||
_ => literal(random.below(4) as f64),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn migrated_declaration(expression: NodeInput) -> Option<Declaration> {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), expression, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
fixture.declaration_of(&migrated, anchor)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFormulaFromMathF, &contract());
|
||||
check_undo(&MathFormulaFromMathF, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_operators_and_functions_become_aggregates() {
|
||||
let aggregate = Some(decl!("math_nodes::MathAggregateNode"@1));
|
||||
let formula = Some(decl!("math_nodes::MathFormulaNode"@2));
|
||||
let expression = |text: &str| literal(Tagged::String(text.to_string()));
|
||||
|
||||
assert_eq!(migrated_declaration(expression("+")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression(" ≠ ")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("max")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("\\mean")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("a + b")), formula);
|
||||
assert_eq!(migrated_declaration(expression("max(a, b)")), formula);
|
||||
assert_eq!(migrated_declaration(expression("")), formula);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_expression_becomes_a_formula() {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let source = fixture.add(MATH_F, vec![literal(1.), literal(Tagged::String("+".to_string())), literal(0.)]);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), NodeInput::Node { id: source, index: 0 }, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("math_nodes::MathFormulaNode"@2)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, source), Some(decl!("math_nodes::MathAggregateNode"@1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Node migrations work on values, not blobs. Each run sees its blobs decoded, and its output moves large values back into blobs.
|
||||
//! An unchanged value encodes to the same blob, so it does not show up in the diff.
|
||||
|
||||
use crate::RunnerError;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs, decode_blob};
|
||||
use document_graph_storage::{BlobHash, NodeId, NodeInput, Registry, Value};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// The blobs of a document, plus the new blobs that migrations create.
|
||||
pub struct MigrationBlobs<'a> {
|
||||
stored: &'a BlobBytes,
|
||||
/// New blobs that are not stored yet.
|
||||
added: BlobBytes,
|
||||
/// The base of each added blob. The base is the blob its input slot held before the migration.
|
||||
bases: HashMap<BlobHash, BlobHash>,
|
||||
}
|
||||
|
||||
/// For a document without blobs.
|
||||
impl Default for MigrationBlobs<'static> {
|
||||
fn default() -> Self {
|
||||
static NONE: LazyLock<BlobBytes> = LazyLock::new(BlobBytes::new);
|
||||
Self::new(&NONE)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MigrationBlobs<'a> {
|
||||
/// Resolve values from the `stored` blobs of a document.
|
||||
pub fn new(stored: &'a BlobBytes) -> Self {
|
||||
Self {
|
||||
stored,
|
||||
added: BlobBytes::new(),
|
||||
bases: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs that migrations added.
|
||||
pub fn into_added(self) -> NewBlobs {
|
||||
NewBlobs { bytes: self.added, bases: self.bases }
|
||||
}
|
||||
|
||||
/// `registry` with the blobs in the inputs of `nodes` decoded back into values. `None` decodes every node.
|
||||
pub(crate) fn resolve<'r>(&self, registry: &'r Registry, nodes: Option<&[NodeId]>) -> Result<Cow<'r, Registry>, RunnerError> {
|
||||
let ids: Cow<[NodeId]> = match nodes {
|
||||
Some(nodes) => Cow::Borrowed(nodes),
|
||||
None => Cow::Owned(registry.node_instances.keys().copied().collect()),
|
||||
};
|
||||
let holds_blob = |id: &NodeId| registry.node_instances.get(id).is_some_and(|node| node.inputs().iter().any(|slot| slot.input.blob().is_some()));
|
||||
if !ids.iter().any(holds_blob) {
|
||||
return Ok(Cow::Borrowed(registry));
|
||||
}
|
||||
|
||||
let mut resolved = registry.clone();
|
||||
for id in ids.iter() {
|
||||
let Some(node) = resolved.node_instances.get_mut(id) else { continue };
|
||||
for slot in node.inputs_mut() {
|
||||
let NodeInput::Value { value, .. } = &mut slot.input else { continue };
|
||||
let Value::Blob(hash) = *value else { continue };
|
||||
|
||||
let bytes = self.stored.get(&hash).or_else(|| self.added.get(&hash)).ok_or(RunnerError::MissingBlob(hash))?;
|
||||
*value = decode_blob(bytes).map_err(|_| RunnerError::MissingBlob(hash))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Cow::Owned(resolved))
|
||||
}
|
||||
|
||||
/// Move the large values of `migrated` back into blobs. A new blob is based on the blob its slot held in `source`.
|
||||
pub(crate) fn store(&mut self, migrated: &mut Registry, source: &Registry) {
|
||||
let mut bytes = BlobBytes::new();
|
||||
migrated.move_values_into_blobs(&mut bytes);
|
||||
bytes.retain(|hash, _| !self.stored.contains_key(hash) && !self.added.contains_key(hash));
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.bases.extend(migrated.blob_bases_since(source).into_iter().filter(|(hash, _)| bytes.contains_key(hash)));
|
||||
self.added.extend(bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,7 @@
|
||||
//! 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>,
|
||||
}
|
||||
use migration_core::{DocumentPayloads, FormatMigration, HistoryPolicy};
|
||||
|
||||
/// 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
|
||||
@@ -69,6 +58,7 @@ pub fn run_format_migrations(migrations: &[&'static dyn FormatMigration], payloa
|
||||
if let Some(session) = &payloads.session {
|
||||
payloads.session = Some(step.migrate_session(session).map_err(fail)?);
|
||||
}
|
||||
step.migrate_document(payloads).map_err(fail)?;
|
||||
|
||||
payloads.format_version += 1;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 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 blobs;
|
||||
mod format;
|
||||
mod node;
|
||||
mod order;
|
||||
@@ -10,8 +11,10 @@ pub mod testing;
|
||||
use document_graph_storage::{CrdtError, NodeId, Rev};
|
||||
use migration_core::{Declaration, InputConnector, MigrationError};
|
||||
|
||||
pub use blobs::MigrationBlobs;
|
||||
pub use document_graph_storage::rehash_deltas;
|
||||
pub use format::{DocumentPayloads, HistoryOutcome, run_format_migrations};
|
||||
pub use format::{HistoryOutcome, run_format_migrations};
|
||||
pub use migration_core::DocumentPayloads;
|
||||
pub use node::{DeclarationTable, RewrittenHistory, holds, registry_at};
|
||||
pub use order::{migrate_history, migrate_registry, order_migrations, references};
|
||||
|
||||
@@ -49,6 +52,8 @@ pub enum RunnerError {
|
||||
InvalidStep { from: Declaration, to: Declaration },
|
||||
#[error("migrations from {0:?} depend on each other in a cycle")]
|
||||
OrderCycle(Vec<Declaration>),
|
||||
#[error("blob {0} is missing or fails to decode, so a migration can't read its value")]
|
||||
MissingBlob(document_graph_storage::BlobHash),
|
||||
#[error("failed to apply a delta: {0}")]
|
||||
Crdt(#[from] CrdtError),
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The node tier: `M` as a function on registry states, and the history rewrite derived from it.
|
||||
|
||||
use crate::RunnerError;
|
||||
use crate::{MigrationBlobs, RunnerError};
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
|
||||
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector};
|
||||
@@ -61,12 +61,29 @@ impl DeclarationResolver for DeclarationTable {
|
||||
}
|
||||
|
||||
/// `M`: run `migration` on every anchor in `source` and apply the edits. Every run reads `source`, so no run observes another's edits.
|
||||
/// A migration asking the compiler runs upstream anchors first instead, in rounds, since the compiler can't describe what's still in the old shape.
|
||||
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
|
||||
pub(crate) fn apply_migration(
|
||||
migration: &dyn NodeMigration,
|
||||
source: &Registry,
|
||||
resolver: &dyn DeclarationResolver,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<Registry, RunnerError> {
|
||||
let anchors = anchors(migration.source(), source, resolver);
|
||||
if anchors.is_empty() {
|
||||
return Ok(source.clone());
|
||||
}
|
||||
|
||||
// A migration that reads beyond its anchors needs every value decoded
|
||||
let reads_beyond_anchors = migration.footprint().reads_network() || migration.asks_compiler();
|
||||
let resolved = blobs.resolve(source, (!reads_beyond_anchors).then_some(anchors.as_slice()))?;
|
||||
|
||||
let mut migrated = apply_to_values(migration, &resolved, anchors, resolver, host)?;
|
||||
blobs.store(&mut migrated, source);
|
||||
Ok(migrated)
|
||||
}
|
||||
|
||||
/// A migration asking the compiler runs upstream anchors first, in rounds, since the compiler can't describe what's still in the old shape.
|
||||
fn apply_to_values(migration: &dyn NodeMigration, source: &Registry, anchors: Vec<NodeId>, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
|
||||
let Some(host) = host.filter(|_| migration.asks_compiler()) else {
|
||||
return apply_runs(migration, source, &anchors, resolver, None);
|
||||
};
|
||||
@@ -299,6 +316,7 @@ pub(crate) fn rewrite_history(
|
||||
resolver: &dyn DeclarationResolver,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
kept: &HashSet<Rev>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<RewrittenHistory, RunnerError> {
|
||||
let mut children: HashMap<Option<Rev>, usize> = HashMap::new();
|
||||
let mut child_authors: HashMap<Rev, HashSet<_>> = HashMap::new();
|
||||
@@ -348,7 +366,7 @@ pub(crate) fn rewrite_history(
|
||||
let passes = passes_through(&delta.kind);
|
||||
let mut chain = if passes { vec![delta.kind.clone()] } else { Vec::new() };
|
||||
if if whole_states_only { is_boundary(delta) } else { !passes } {
|
||||
let migrated = apply_migration(migration, &branch.original, resolver, host)?;
|
||||
let migrated = apply_migration(migration, &branch.original, resolver, host, blobs)?;
|
||||
chain.extend(compute_deltas(&branch.rewritten, &migrated));
|
||||
}
|
||||
check_single_writes(&chain)?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Orders registered node migrations by the declarations they read and write, and runs every pending one over a history.
|
||||
|
||||
use crate::node::{apply_migration, rewrite_history};
|
||||
use crate::{RewrittenHistory, RunnerError};
|
||||
use crate::{MigrationBlobs, RewrittenHistory, RunnerError};
|
||||
use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev};
|
||||
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
@@ -76,13 +76,15 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
|
||||
|
||||
/// 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. `kept` names the
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep.
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep. `blobs` resolves
|
||||
/// the blobs that migrations read and collects the blobs they add.
|
||||
pub fn migrate_history(
|
||||
migrations: &[&'static dyn NodeMigration],
|
||||
history: Vec<Delta>,
|
||||
resolver: &dyn DeclarationResolver,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
kept: impl IntoIterator<Item = Rev>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<RewrittenHistory, RunnerError> {
|
||||
let mut kept: HashSet<Rev> = kept.into_iter().collect();
|
||||
let mut revs: HashMap<Rev, Option<Rev>> = history.iter().map(|delta| (delta.id, Some(delta.id))).collect();
|
||||
@@ -93,7 +95,7 @@ pub fn migrate_history(
|
||||
continue;
|
||||
}
|
||||
|
||||
let step = rewrite_history(migration, &deltas, resolver, host, &kept)?;
|
||||
let step = rewrite_history(migration, &deltas, resolver, host, &kept, blobs)?;
|
||||
kept = kept.iter().filter_map(|rev| step.revs.get(rev).copied().flatten()).collect();
|
||||
for rev in revs.values_mut() {
|
||||
*rev = rev.and_then(|rev| step.revs.get(&rev).copied().flatten());
|
||||
@@ -104,11 +106,17 @@ pub fn migrate_history(
|
||||
Ok(RewrittenHistory { deltas, revs })
|
||||
}
|
||||
|
||||
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result.
|
||||
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
|
||||
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result. See [`migrate_history`] for `blobs`.
|
||||
pub fn migrate_registry(
|
||||
migrations: &[&'static dyn NodeMigration],
|
||||
registry: &Registry,
|
||||
resolver: &dyn DeclarationResolver,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<Registry, RunnerError> {
|
||||
let mut migrated = registry.clone();
|
||||
for migration in order_migrations(migrations)? {
|
||||
migrated = apply_migration(migration, &migrated, resolver, host)?;
|
||||
migrated = apply_migration(migration, &migrated, resolver, host, blobs)?;
|
||||
}
|
||||
Ok(migrated)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! Panics on failure, since it only runs in tests.
|
||||
|
||||
use crate::node::{apply_migration, rewrite_history};
|
||||
use crate::{DeclarationTable, RunnerError, references, registry_at};
|
||||
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
|
||||
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, MigrationHost, NodeMigration, decl, literal, registered_migrations};
|
||||
use std::collections::HashSet;
|
||||
@@ -52,7 +52,12 @@ impl Fixture {
|
||||
}
|
||||
|
||||
pub fn migrate_with(&self, migration: &dyn NodeMigration, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
|
||||
apply_migration(migration, &self.registry, &self.table, host)
|
||||
apply_migration(migration, &self.registry, &self.table, host, &mut MigrationBlobs::default())
|
||||
}
|
||||
|
||||
/// Migrate a registry whose inputs name blobs from `blobs`.
|
||||
pub fn migrate_blobs(&self, migration: &dyn NodeMigration, blobs: &mut MigrationBlobs) -> Result<Registry, RunnerError> {
|
||||
apply_migration(migration, &self.registry, &self.table, None, blobs)
|
||||
}
|
||||
|
||||
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
|
||||
@@ -276,11 +281,11 @@ pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceCo
|
||||
let (session, table) = generate(migration, contract, seed, 40);
|
||||
let history: Vec<Delta> = session.history().cloned().collect();
|
||||
|
||||
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
|
||||
for delta in &history {
|
||||
let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
|
||||
let expected = apply_migration(migration, &original, &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
let expected = apply_migration(migration, &original, &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
|
||||
assert!(
|
||||
replayed.value_equal(&expected),
|
||||
@@ -310,7 +315,7 @@ pub fn check_undo_with(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, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
|
||||
let head = session.head_rev();
|
||||
let migrated_head = head.and_then(|head| rewritten.revs[&head]);
|
||||
@@ -320,13 +325,13 @@ pub fn check_undo_with(migration: &dyn NodeMigration, contract: &SourceContract,
|
||||
let mut original = Session::load(PeerId(1), UserId(1), original_registry, history, head, Vec::new(), 0);
|
||||
let mut migrated = Session::load(PeerId(1), UserId(1), migrated_registry, rewritten.deltas, migrated_head, Vec::new(), 0);
|
||||
|
||||
let mut previous = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
let mut previous = apply_migration(migration, original.registry(), &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
for undo in 0..5 {
|
||||
// An interaction that only touched what `M` drops left no delta in the rewrite, so undo there passes over it
|
||||
let mut expected = previous.clone();
|
||||
while expected.value_equal(&previous) && original.can_undo() {
|
||||
original.undo().expect("can_undo said so");
|
||||
expected = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
|
||||
expected = apply_migration(migration, original.registry(), &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
|
||||
}
|
||||
if expected.value_equal(&previous) {
|
||||
break;
|
||||
|
||||
@@ -31,6 +31,7 @@ fn format_tier_chains_and_bumps_version() {
|
||||
history: vec![Payload::new(vec![1, 2, 3], PayloadCodec::Postcard)],
|
||||
hot_log: Vec::new(),
|
||||
session: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let outcome = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap();
|
||||
@@ -50,6 +51,7 @@ fn format_tier_errors_on_missing_step() {
|
||||
history: Vec::new(),
|
||||
hot_log: Vec::new(),
|
||||
session: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let error = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap_err();
|
||||
@@ -64,6 +66,7 @@ fn truncating_a_document_without_a_registry_fails() {
|
||||
history: vec![Payload::new(vec![1, 2, 3], PayloadCodec::Postcard)],
|
||||
hot_log: Vec::new(),
|
||||
session: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let error = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap_err();
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Migrations read values that are stored in blobs. The large values they write go back into blobs.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
|
||||
use document_graph_storage::{BlobHash, NodeInput, Value};
|
||||
use migration_core::{Inputs, Node, decl, literal, literal_of, migration};
|
||||
use migration_runner::MigrationBlobs;
|
||||
use migration_runner::testing::Fixture;
|
||||
|
||||
/// Appends a suffix to the text in the first input.
|
||||
#[migration("blob_nodes::text"@1 => @2)]
|
||||
pub fn append_to_text(node: &Node, inputs: &mut Inputs) {
|
||||
let text: String = literal_of(&node.inputs()[0].input).unwrap_or_default();
|
||||
inputs.set(0, literal(format!("{text}!")));
|
||||
}
|
||||
|
||||
/// A large literal stored as a blob, together with its blob bytes.
|
||||
fn blob_literal(text: &str, blobs: &mut BlobBytes) -> (NodeInput, BlobHash) {
|
||||
let mut input = literal(text.to_string());
|
||||
input.move_into_blob(blobs);
|
||||
let hash = input.blob().expect("the literal is large enough to be a blob");
|
||||
(input, hash)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrations_read_blob_values_and_write_large_ones_back_into_blobs() {
|
||||
let text = "a".repeat(BLOB_THRESHOLD);
|
||||
let mut stored = BlobBytes::new();
|
||||
let (input, original) = blob_literal(&text, &mut stored);
|
||||
|
||||
let mut fixture = Fixture::new(&AppendToText);
|
||||
let node = fixture.add(decl!("blob_nodes::text"@1), vec![input]);
|
||||
let mut blobs = MigrationBlobs::new(&stored);
|
||||
let migrated = fixture.migrate_blobs(&AppendToText, &mut blobs).unwrap();
|
||||
|
||||
let (_, appended) = blob_literal(&format!("{text}!"), &mut BlobBytes::new());
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, node),
|
||||
[NodeInput::Value {
|
||||
value: Value::Blob(appended),
|
||||
exposed: false
|
||||
}]
|
||||
);
|
||||
let added = blobs.into_added();
|
||||
assert!(added.bytes.contains_key(&appended), "the new value's bytes are handed back");
|
||||
assert_eq!(added.bases.get(&appended), Some(&original), "it is based on the blob its slot held");
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId};
|
||||
use migration_core::{Compiler, DeclarationResolver, Graph, MigrationError, MigrationHost, NodeMigration, Target, ValueType, decl, literal, literal_of, migration};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_commutation_with, check_undo, check_undo_with};
|
||||
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
|
||||
use migration_runner::{DeclarationTable, MigrationBlobs, RunnerError, migrate_history, order_migrations};
|
||||
use std::any::type_name;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
@@ -219,7 +219,7 @@ fn the_compiler_is_only_asked_at_interaction_boundaries() {
|
||||
let history: Vec<_> = session.history().cloned().collect();
|
||||
let host = AnswerHost::default();
|
||||
|
||||
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev()).unwrap();
|
||||
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev(), &mut MigrationBlobs::default()).unwrap();
|
||||
|
||||
// The root network's interaction has no anchors yet, so it never asks, and each of the other two asks once for its one round of unrelated anchors
|
||||
assert_eq!(host.asked.load(Ordering::Relaxed), 2);
|
||||
@@ -242,7 +242,7 @@ fn a_cursor_inside_an_interaction_keeps_its_state() {
|
||||
let inside = history[history.len() - 2].id;
|
||||
let host = AnswerHost::default();
|
||||
|
||||
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside]).unwrap();
|
||||
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside], &mut MigrationBlobs::default()).unwrap();
|
||||
assert_eq!(host.asked.load(Ordering::Relaxed), 2, "the cursor and the interaction's end");
|
||||
assert!(rewritten.revs[&inside].is_some());
|
||||
}
|
||||
@@ -254,7 +254,7 @@ fn reading_the_graph_also_only_sees_whole_states() {
|
||||
let history: Vec<_> = session.history().cloned().collect();
|
||||
|
||||
let before = GRAPH_READS.load(Ordering::Relaxed);
|
||||
migrate_history(&[&GraphReader], history, &table, None, session.head_rev()).unwrap();
|
||||
migrate_history(&[&GraphReader], history, &table, None, session.head_rev(), &mut MigrationBlobs::default()).unwrap();
|
||||
|
||||
// All five anchors exist at the one boundary, and the anchorless root network's boundary reads nothing
|
||||
assert_eq!(GRAPH_READS.load(Ordering::Relaxed) - before, 5);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod blobs;
|
||||
mod compiler;
|
||||
mod examples;
|
||||
mod registration;
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::examples::{ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, Transf
|
||||
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};
|
||||
use migration_runner::{DeclarationTable, MigrationBlobs, RunnerError, migrate_history, order_migrations};
|
||||
|
||||
#[test]
|
||||
fn every_migration_registers_once() {
|
||||
@@ -14,6 +14,7 @@ fn every_migration_registers_once() {
|
||||
|
||||
let mut expected = vec![
|
||||
decl!("blending_nodes::opacity"@1),
|
||||
decl!("blob_nodes::text"@1),
|
||||
decl!("compiler::anchor"@1),
|
||||
decl!("compiler::graph_reader"@1),
|
||||
decl!("choice::toggle"@1),
|
||||
@@ -207,7 +208,15 @@ fn migrate_history_chains_every_pending_migration() {
|
||||
});
|
||||
|
||||
let history: Vec<Delta> = session.history().cloned().collect();
|
||||
let migrated = migrate_history(®istered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).unwrap();
|
||||
let migrated = migrate_history(
|
||||
®istered_migrations(),
|
||||
history.clone(),
|
||||
&table,
|
||||
Some(&compiler::AnswerHost::default()),
|
||||
None,
|
||||
&mut MigrationBlobs::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let registry = replay(&migrated.deltas);
|
||||
|
||||
let declaration_of = |id: NodeId| match registry.node_instances[&id].implementation() {
|
||||
|
||||
@@ -13,7 +13,7 @@ publish.workspace = true
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
matchbox_socket = "0.14.0"
|
||||
matchbox_socket = "0.15.0"
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -6,7 +6,7 @@ mod target;
|
||||
mod token;
|
||||
mod transport;
|
||||
|
||||
pub use packet::{CursorPosition, CursorSpace, MAX_PACKET_BYTES, PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use packet::{BlobRecord, CursorPosition, CursorSpace, MAX_PACKET_BYTES, PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
|
||||
pub use room::{Incoming, Room};
|
||||
pub use target::{SyncTarget, TargetError};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use document_graph_storage::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The host is the single peer that retires hot ops.
|
||||
@@ -82,6 +82,9 @@ pub struct SyncPayload {
|
||||
pub document_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub metadata: HistoryMetadata,
|
||||
/// Every blob that the synced state names. A base comes before the blobs that use it.
|
||||
#[serde(default)]
|
||||
pub blobs: Vec<BlobRecord>,
|
||||
}
|
||||
|
||||
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`. `seen` is the sender's
|
||||
@@ -96,7 +99,11 @@ pub struct Broadcast {
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
HotOps(Vec<HotOp>),
|
||||
/// The records of new blobs that the ops name.
|
||||
HotOps {
|
||||
ops: Vec<HotOp>,
|
||||
blobs: Vec<BlobRecord>,
|
||||
},
|
||||
/// `deltas` are in causal order. `retires` names the hot ops they replace, empty for a plain history transfer.
|
||||
Deltas {
|
||||
deltas: Vec<Delta>,
|
||||
@@ -110,6 +117,14 @@ pub enum BroadcastBody {
|
||||
HeadMove(HeadMove),
|
||||
}
|
||||
|
||||
/// The stored record of a blob. It holds the value in full or as a delta against a base. The transport does not read it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlobRecord {
|
||||
pub hash: BlobHash,
|
||||
#[serde(with = "serde_bytes")]
|
||||
pub record: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Largest encoded packet a peer sends or accepts. Generous, since a `Resource` carries a whole embedded file.
|
||||
pub const MAX_PACKET_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::packet::{Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::packet::{BlobRecord, Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::target::{SyncTarget, TargetError};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId};
|
||||
@@ -124,6 +124,10 @@ impl Replica {
|
||||
Some(Role::Host)
|
||||
}
|
||||
|
||||
pub fn has_host(&self) -> bool {
|
||||
self.current_host().is_some()
|
||||
}
|
||||
|
||||
/// The link and id of the peer greeting as host. While two coexist this is the one with the lower id, which keeps
|
||||
/// the role once they meet.
|
||||
fn current_host(&self) -> Option<(TransportPeerId, PeerId)> {
|
||||
@@ -322,12 +326,13 @@ impl Replica {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
|
||||
/// Broadcast staged `ops` together with the records of their new blobs.
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp], blobs: Vec<BlobRecord>) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
|
||||
self.broadcast(BroadcastBody::HotOps { ops: ops.to_vec(), blobs })
|
||||
}
|
||||
|
||||
/// Ask the host to undo (`restore == false`) or redo (`restore == true`) this peer's retired interaction.
|
||||
@@ -401,6 +406,12 @@ impl Replica {
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
if let Some(recipients) = self.owed_resources.get_mut(&hash) {
|
||||
recipients.remove(&to);
|
||||
if recipients.is_empty() {
|
||||
self.owed_resources.remove(&hash);
|
||||
}
|
||||
}
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
@@ -488,7 +499,7 @@ impl Replica {
|
||||
let retired = target.retired_marks();
|
||||
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
|
||||
|
||||
self.broadcast_hot_ops(&unretired)?;
|
||||
self.broadcast_hot_ops(&unretired, Vec::new())?;
|
||||
if retired.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -682,6 +693,7 @@ impl Replica {
|
||||
retired: target.retired_marks(),
|
||||
document_id: target.document_id(),
|
||||
metadata: target.metadata(),
|
||||
blobs: target.blob_records(),
|
||||
};
|
||||
log::debug!("Join handshake: sync answered with {} deltas and {} hot ops", sync.deltas.len(), sync.hot_log.len());
|
||||
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
|
||||
@@ -696,6 +708,7 @@ impl Replica {
|
||||
// unretired ops, possibly the only copy of what never reached the host, are replayed on top.
|
||||
let registry = sync.registry.filter(|_| target.known_revs().is_empty());
|
||||
let replayed = if registry.is_some() { target.hot_log() } else { Vec::new() };
|
||||
target.absorb_blob_records(sync.blobs)?;
|
||||
match registry {
|
||||
Some(registry) => target.load(registry, sync.deltas, sync.head)?,
|
||||
None => target.merge_remote(sync.deltas, &[], sync.head)?,
|
||||
@@ -742,7 +755,7 @@ impl Replica {
|
||||
self.follow_current_host(&*target)?;
|
||||
|
||||
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
|
||||
self.broadcast_hot_ops(&own_hot_ops)?;
|
||||
self.broadcast_hot_ops(&own_hot_ops, Vec::new())?;
|
||||
|
||||
events.push(Event::Synced);
|
||||
}
|
||||
@@ -866,7 +879,14 @@ impl Replica {
|
||||
|
||||
// A failure is logged rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
|
||||
BroadcastBody::HotOps { ops, blobs } => {
|
||||
// A blob with a missing base is fetched like a missing resource
|
||||
self.resources_stale = true;
|
||||
target
|
||||
.absorb_blob_records(blobs)
|
||||
.and_then(|()| target.apply_remote_hot_ops(ops))
|
||||
.map(|deferred| self.deferred.extend(deferred))
|
||||
}
|
||||
// A host lets a step with a missing parent go, since its author's whole line arrives when the author syncs.
|
||||
BroadcastBody::Deltas { deltas, .. } if has_missing_parent(&deltas, &*target) => {
|
||||
if self.role == Role::Host {
|
||||
@@ -991,7 +1011,7 @@ mod tests {
|
||||
epoch: 1,
|
||||
seq,
|
||||
seen,
|
||||
body: BroadcastBody::HotOps(Vec::new()),
|
||||
body: BroadcastBody::HotOps { ops: Vec::new(), blobs: Vec::new() },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1122,4 +1142,18 @@ mod tests {
|
||||
host.poll(&mut session);
|
||||
assert!(host.owed_resources.is_empty(), "nothing is owed to a link that closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answered_request_is_owed_no_more() {
|
||||
let (mut network, mut host, host_link, mut session) = hosted_room();
|
||||
let mut bare = connect_bare_peer(&mut network, &mut host, &mut session);
|
||||
let hash = ResourceHash::from(b"bytes".as_slice());
|
||||
|
||||
bare.send(host_link, &hello(0)).unwrap();
|
||||
bare.send(host_link, &SyncPacket::ResourceRequest(vec![hash])).unwrap();
|
||||
network.deliver_all();
|
||||
host.poll(&mut session);
|
||||
host.send_resource(bare.id(), hash, b"bytes".to_vec()).unwrap();
|
||||
assert!(host.owed_resources.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ const FRAME_FINAL: u8 = 1;
|
||||
const FRAME_MORE: u8 = 0;
|
||||
|
||||
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
|
||||
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
|
||||
fn frames(bytes: &[u8]) -> Vec<Packet> {
|
||||
// Chunking an empty packet would yield no frame at all.
|
||||
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
|
||||
|
||||
@@ -200,7 +200,8 @@ impl Transport for Room {
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
// Errs only once the socket loop ended, which its future reports, after handing over the changes before that.
|
||||
for (peer, state) in self.socket.try_update_peers().unwrap_or_default() {
|
||||
match state {
|
||||
PeerState::Connected => events.push(TransportEvent::PeerConnected(peer)),
|
||||
PeerState::Disconnected => {
|
||||
@@ -258,7 +259,7 @@ mod tests {
|
||||
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
|
||||
|
||||
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
|
||||
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[FRAME_FINAL, 7])));
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::BlobRecord;
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, MergeOutcome, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -68,6 +69,14 @@ pub trait SyncTarget {
|
||||
fn store_resource(&mut self, _hash: ResourceHash, _bytes: &[u8]) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
/// The record of every held blob, for a peer that syncs from this one. A base comes before the blobs that use it.
|
||||
fn blob_records(&self) -> Vec<BlobRecord> {
|
||||
Vec::new()
|
||||
}
|
||||
/// Hold the blobs of records from a peer. A record with a missing base is dropped and later fetched as a missing resource.
|
||||
fn absorb_blob_records(&mut self, _records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for Session {
|
||||
|
||||
@@ -1,29 +1,44 @@
|
||||
//! Deterministic simulation over the mock transport with random edits, delivery order and host retirement.
|
||||
//! After quiescence every peer must hold the same retired state.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
|
||||
//! Inspect one run with `SEED=<n> GUESTS=<n> [STROKES=1] cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
|
||||
use document_graph_storage::{
|
||||
AttributeDelta, Delta, HeadMove, HotOp, HotOpId, HotSequence, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId,
|
||||
RetiredMarks, Rev, Session, SourceKey, UserId, Value,
|
||||
AttributeDelta, BlobHash, Delta, HeadMove, HotOp, HotOpId, HotSequence, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash,
|
||||
ResourceId, RetiredMarks, Rev, Session, SourceKey, UserId, Value,
|
||||
};
|
||||
use peer_transport::mock::{MockEndpoint, MockNetwork};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::thread::LocalKey;
|
||||
|
||||
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_COLLECTED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_REDONE_RETRACTIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
// Per thread, since each test runs its corpus on its own thread
|
||||
thread_local! {
|
||||
static TOTAL_NODES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_WIRED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_EXPORTS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_INPUT_ATTRIBUTES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_SOURCES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_COLLECTED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_REDONE_RETRACTIONS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOBS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_DELTAS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_FETCHES: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn count(counter: &'static LocalKey<Cell<usize>>, amount: usize) {
|
||||
counter.set(counter.get() + amount);
|
||||
}
|
||||
|
||||
/// A peer's document plus a byte store, since bare `Session` has no-op resource defaults.
|
||||
struct SimTarget {
|
||||
session: Session,
|
||||
resources: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// Blob bytes and the record of each blob. See [`SimTarget::blob_record`].
|
||||
blobs: BlobBytes,
|
||||
blob_records: HashMap<BlobHash, Vec<u8>>,
|
||||
/// History as of the last `flush`.
|
||||
durable_history: Vec<Rev>,
|
||||
flushes: usize,
|
||||
@@ -40,6 +55,8 @@ impl SimTarget {
|
||||
Self {
|
||||
session: Session::with_peer(peer),
|
||||
resources: HashMap::new(),
|
||||
blobs: BlobBytes::new(),
|
||||
blob_records: HashMap::new(),
|
||||
durable_history: Vec::new(),
|
||||
flushes: 0,
|
||||
seen_revs: HashSet::new(),
|
||||
@@ -51,6 +68,37 @@ impl SimTarget {
|
||||
fn history_revs(&self) -> Vec<Rev> {
|
||||
self.session.history().map(|delta| delta.id).collect()
|
||||
}
|
||||
|
||||
/// A stand-in for a blob record. It holds the base hash if the base is held, then the bytes. Like a real delta,
|
||||
/// a receiver can only take it when it holds the base. `document-format` tests real deltas.
|
||||
fn blob_record(&self, bytes: &[u8], base: Option<BlobHash>) -> Vec<u8> {
|
||||
let mut record = Vec::new();
|
||||
match base.filter(|base| self.blobs.contains_key(base)) {
|
||||
Some(base) => {
|
||||
record.push(1);
|
||||
record.extend_from_slice(&<[u8; 32]>::from(&base.0));
|
||||
}
|
||||
None => record.push(0),
|
||||
}
|
||||
record.extend_from_slice(bytes);
|
||||
record
|
||||
}
|
||||
|
||||
/// Hold staged blobs and return the records that peers receive with the ops.
|
||||
fn hold_blobs(&mut self, blobs: BlobBytes, bases: &HashMap<BlobHash, BlobHash>) -> Vec<BlobRecord> {
|
||||
let mut blobs: Vec<_> = blobs.into_iter().filter(|(hash, _)| !self.blobs.contains_key(hash)).collect();
|
||||
blobs.sort_unstable_by_key(|(hash, _)| *hash);
|
||||
|
||||
let mut records = Vec::new();
|
||||
for (hash, bytes) in blobs {
|
||||
let record = self.blob_record(&bytes, bases.get(&hash).copied());
|
||||
self.blobs.insert(hash, bytes);
|
||||
self.blob_records.insert(hash, record.clone());
|
||||
records.push(BlobRecord { hash, record });
|
||||
}
|
||||
count(&TOTAL_BLOBS, records.len());
|
||||
records
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for SimTarget {
|
||||
@@ -168,17 +216,67 @@ impl SyncTarget for SimTarget {
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
|
||||
let resources = self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash));
|
||||
let blobs = self.session.all_blob_hashes().into_iter().filter(|hash| !self.blobs.contains_key(hash));
|
||||
resources.chain(blobs.map(ResourceHash::from)).collect()
|
||||
}
|
||||
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
self.resources.get(&hash).cloned()
|
||||
self.resources.get(&hash).or_else(|| self.blobs.get(&BlobHash(hash))).cloned()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let blob = BlobHash(hash);
|
||||
if self.session.names_blob(blob) {
|
||||
count(&TOTAL_BLOB_FETCHES, 1);
|
||||
let record = self.blob_record(bytes, None);
|
||||
self.blobs.insert(blob, bytes.to_vec());
|
||||
self.blob_records.insert(blob, record);
|
||||
return Ok(());
|
||||
}
|
||||
self.resources.insert(hash, bytes.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn blob_records(&self) -> Vec<BlobRecord> {
|
||||
let mut records: Vec<_> = self.blob_records.iter().map(|(&hash, record)| BlobRecord { hash, record: record.clone() }).collect();
|
||||
records.sort_unstable_by_key(|record| record.hash);
|
||||
records
|
||||
}
|
||||
|
||||
fn absorb_blob_records(&mut self, records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
let mut pending = records;
|
||||
loop {
|
||||
let waiting = pending.len();
|
||||
pending.retain(|BlobRecord { hash, record }| {
|
||||
if self.blobs.contains_key(hash) {
|
||||
return false;
|
||||
}
|
||||
let bytes = match record.split_first() {
|
||||
Some((1, rest)) => {
|
||||
let base = <[u8; 32]>::try_from(&rest[..32])
|
||||
.map(|bytes| BlobHash(ResourceHash::from(bytes)))
|
||||
.expect("a delta record names its base");
|
||||
if !self.blobs.contains_key(&base) {
|
||||
return true;
|
||||
}
|
||||
count(&TOTAL_BLOB_DELTAS, 1);
|
||||
&rest[32..]
|
||||
}
|
||||
Some((_, rest)) => rest,
|
||||
None => panic!("seed {}: an empty blob record arrived", self.seed),
|
||||
};
|
||||
assert_eq!(BlobHash::of(bytes), *hash, "seed {}: a blob record decodes to bytes of another hash", self.seed);
|
||||
self.blobs.insert(*hash, bytes.to_vec());
|
||||
self.blob_records.insert(*hash, record.clone());
|
||||
false
|
||||
});
|
||||
// The remaining records need a base this peer lacks. They are fetched in full as missing resources
|
||||
if pending.is_empty() || pending.len() == waiting {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Peer {
|
||||
@@ -241,9 +339,19 @@ impl Peer {
|
||||
|
||||
fn stage(&mut self, op: RegistryDelta) {
|
||||
self.retracted.clear();
|
||||
let hot_ops = self.target.session.stage_computed_ops(vec![op]).expect("stage");
|
||||
self.stage_ops(vec![op]).expect("stage");
|
||||
}
|
||||
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
/// Stage `ops`, move their large values into blobs and broadcast the blob records with them.
|
||||
fn stage_ops(&mut self, mut ops: Vec<RegistryDelta>) -> Result<(), document_graph_storage::CrdtError> {
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
let bases = self.target.session.registry().blob_bases(&ops);
|
||||
|
||||
let hot_ops = self.target.session.stage_computed_ops(ops)?;
|
||||
let records = self.target.hold_blobs(blobs, &bases);
|
||||
self.replica.broadcast_hot_ops(&hot_ops, records).expect("broadcast");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
|
||||
@@ -255,7 +363,7 @@ impl Peer {
|
||||
// Per-peer, since a content-derived id would collide across peers.
|
||||
let id = ResourceId::from(u64::from(ResourceId::from_hash(&hash)) ^ self.peer.0);
|
||||
let hot_ops = self.target.session.stage_embedded_resource(id, hash).expect("stage resource");
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
self.replica.broadcast_hot_ops(&hot_ops, Vec::new()).expect("broadcast");
|
||||
}
|
||||
|
||||
fn retire(&mut self) {
|
||||
@@ -275,10 +383,26 @@ impl Peer {
|
||||
let staged = self.target.session.end_interaction().expect("end interaction");
|
||||
if let Some(marker) = staged.last() {
|
||||
self.last_closed = marker.sequence;
|
||||
self.replica.broadcast_hot_ops(&staged).expect("broadcast");
|
||||
self.replica.broadcast_hot_ops(&staged, Vec::new()).expect("broadcast");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit one input of a live node a few times in a row, like drawing does. Each new blob is based on the one before.
|
||||
fn stroke(&mut self, network: &mut MockNetwork) {
|
||||
let live_nodes: Vec<NodeId> = sorted(self.session().registry().node_instances.keys().copied());
|
||||
let Some(&id) = pick(network, &live_nodes) else { return };
|
||||
let index = network.random_below(2) as u32;
|
||||
|
||||
for _ in 0..2 + network.random_below(4) {
|
||||
let new_input = NodeInput::Value {
|
||||
value: large_value(network),
|
||||
exposed: false,
|
||||
};
|
||||
self.stage(RegistryDelta::ChangeNodeInput { id, index, new_input });
|
||||
}
|
||||
self.end_interaction();
|
||||
}
|
||||
|
||||
/// Undo this peer's latest interaction while hot. The ops leave every hot log and never become history.
|
||||
fn retract(&mut self) {
|
||||
if let Some(retraction) = self.target.session.retract_interaction().expect("retract") {
|
||||
@@ -293,10 +417,11 @@ impl Peer {
|
||||
/// Redo the hot step this peer took back last, staging its ops afresh. A redo that no longer fits is given up.
|
||||
fn redo_retracted(&mut self) {
|
||||
let Some(ops) = self.retracted.pop() else { return };
|
||||
let Ok(hot_ops) = self.target.session.stage_computed_ops(ops) else { return };
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
if self.stage_ops(ops).is_err() {
|
||||
return;
|
||||
}
|
||||
self.end_interaction();
|
||||
TOTAL_REDONE_RETRACTIONS.fetch_add(1, Ordering::Relaxed);
|
||||
count(&TOTAL_REDONE_RETRACTIONS, 1);
|
||||
}
|
||||
|
||||
/// Drop every held byte outside the GC root set. `needed` is what present peers name and lack.
|
||||
@@ -307,7 +432,7 @@ impl Peer {
|
||||
self.target.collected_while_needed.extend(dropped);
|
||||
let before = self.target.resources.len();
|
||||
self.target.resources.retain(|hash, _| roots.contains(hash));
|
||||
TOTAL_COLLECTED.fetch_add(before - self.target.resources.len(), Ordering::Relaxed);
|
||||
count(&TOTAL_COLLECTED, before - self.target.resources.len());
|
||||
}
|
||||
|
||||
/// Every hash this peer's registry, history, hot log or retracted steps name, gathered independently of the GC
|
||||
@@ -394,6 +519,19 @@ fn random_value(network: &mut MockNetwork) -> Value {
|
||||
Value::from(serde_json::json!(network.random_below(100)))
|
||||
}
|
||||
|
||||
/// A value large enough to become a blob. The pool is small, so peers sometimes stage the same value at once.
|
||||
fn large_value(network: &mut MockNetwork) -> Value {
|
||||
Value::Str(format!("{}{}", "x".repeat(BLOB_THRESHOLD), network.random_below(64)))
|
||||
}
|
||||
|
||||
/// A literal input value. One in three is a [`large_value`].
|
||||
fn random_input_value(network: &mut MockNetwork) -> Value {
|
||||
match network.random_below(3) {
|
||||
0 => large_value(network),
|
||||
_ => random_value(network),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
@@ -431,6 +569,16 @@ fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<Regist
|
||||
})
|
||||
}
|
||||
2 => registry.node_instances.get(&node_id).map(|node| RegistryDelta::RemoveNode { id: node_id, snapshot: node.clone() }),
|
||||
// Repeated edits to one slot chain its blobs, so most of them arrive as deltas
|
||||
5 => {
|
||||
let id = *pick(network, &live_nodes)?;
|
||||
let index = network.random_below(2) as u32;
|
||||
let new_input = NodeInput::Value {
|
||||
value: large_value(network),
|
||||
exposed: false,
|
||||
};
|
||||
Some(RegistryDelta::ChangeNodeInput { id, index, new_input })
|
||||
}
|
||||
3 | 4 => {
|
||||
let node = registry.node_instances.get(&node_id)?;
|
||||
let index = network.random_below(node.inputs().len().max(1)) as u32;
|
||||
@@ -440,7 +588,7 @@ fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<Regist
|
||||
let new_input = match wire_to {
|
||||
Some(target) if network.random_below(3) > 0 => NodeInput::Node { id: target, index: 0 },
|
||||
_ => NodeInput::Value {
|
||||
value: random_value(network),
|
||||
value: random_input_value(network),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
@@ -614,7 +762,15 @@ fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) -> usize {
|
||||
panic!("the room never went idle");
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
|
||||
/// The main kind of step in a run.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Workload {
|
||||
Mixed,
|
||||
/// Half the steps are strokes, like live drawing.
|
||||
Strokes,
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, guest_count: usize, steps: usize, workload: Workload) -> (MockNetwork, Vec<Peer>) {
|
||||
let mut network = MockNetwork::new(seed);
|
||||
let mut peers = open_room(&mut network, guest_count, seed);
|
||||
|
||||
@@ -624,7 +780,11 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Pe
|
||||
continue;
|
||||
}
|
||||
|
||||
match network.random_below(18) {
|
||||
let action = match workload {
|
||||
Workload::Strokes if network.random_below(2) == 0 => 14,
|
||||
_ => network.random_below(18),
|
||||
};
|
||||
match action {
|
||||
// Anything staged before syncing would be invisible to the room.
|
||||
0..=2 if peers[index].replica.is_synced() => {
|
||||
let op = random_op(&mut network, &peers[index].target);
|
||||
@@ -642,6 +802,7 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Pe
|
||||
peers[index].collect_garbage(&needed);
|
||||
}
|
||||
17 if peers[index].replica.is_synced() => peers[index].redo_retracted(),
|
||||
14 if peers[index].replica.is_synced() => peers[index].stroke(&mut network),
|
||||
// Bytes nothing names, as an abandoned import leaves behind.
|
||||
8 if network.random_below(4) == 0 => {
|
||||
let bytes = format!("stray-{}-{}", peers[index].peer.0, network.random_below(1 << 20)).into_bytes();
|
||||
@@ -863,7 +1024,14 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
|
||||
// Bytes that left with a departed peer are gone, so only those a present peer holds, or collected while needed,
|
||||
// must be served.
|
||||
let servable: HashSet<ResourceHash> = present()
|
||||
.flat_map(|(_, peer)| peer.target.resources.keys().chain(&peer.target.collected_while_needed).copied())
|
||||
.flat_map(|(_, peer)| {
|
||||
peer.target
|
||||
.resources
|
||||
.keys()
|
||||
.chain(&peer.target.collected_while_needed)
|
||||
.copied()
|
||||
.chain(peer.target.blobs.keys().map(|hash| hash.0))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (index, peer) in present() {
|
||||
@@ -886,14 +1054,36 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
|
||||
|
||||
#[test]
|
||||
fn peers_converge_under_random_interleavings() {
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(5000);
|
||||
run_corpus(Workload::Mixed, 5000);
|
||||
// The generator's ops are guarded on registry state, so a change can quietly stop producing them.
|
||||
assert!(TOTAL_NODES.get() > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.get() > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.get() > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.get() > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.get() > 0, "the corpus never stacked a second source on a resource");
|
||||
assert!(TOTAL_COLLECTED.get() > 0, "garbage collection never dropped a resource");
|
||||
assert!(TOTAL_REDONE_RETRACTIONS.get() > 0, "the corpus never redid a step taken back");
|
||||
assert!(TOTAL_BLOBS.get() > 0, "the corpus staged no blobs");
|
||||
}
|
||||
|
||||
// Runs every seed and lists the failures, to tell one bug from several.
|
||||
/// Mostly strokes. Blobs chain, reach peers as deltas and are fetched in full by peers that lack a base.
|
||||
#[test]
|
||||
fn blobs_reach_every_peer_under_strokes() {
|
||||
run_corpus(Workload::Strokes, 10_000);
|
||||
assert!(TOTAL_BLOB_DELTAS.get() > 0, "no blob arrived as a delta against one already held");
|
||||
assert!(TOTAL_BLOB_FETCHES.get() > 0, "no blob was fetched in full for a missing base");
|
||||
}
|
||||
|
||||
/// Run `SIM_SEEDS` seeds (or `default_seeds`) and check that each one converges.
|
||||
/// `SIM_KEEP_GOING` runs every seed and lists all failures. This tells one bug from several.
|
||||
fn run_corpus(workload: Workload, default_seeds: u64) {
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(default_seeds);
|
||||
let keep_going = std::env::var_os("SIM_KEEP_GOING").is_some();
|
||||
|
||||
let mut failed = Vec::new();
|
||||
for seed in 0..seeds {
|
||||
let run = || {
|
||||
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
|
||||
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200, workload);
|
||||
count_coverage(peers[expect_host(seed, &peers)].session().retired_registry());
|
||||
assert_converged(seed, &peers);
|
||||
};
|
||||
@@ -904,25 +1094,17 @@ fn peers_converge_under_random_interleavings() {
|
||||
}
|
||||
}
|
||||
assert!(failed.is_empty(), "{} seeds failed: {failed:?}", failed.len());
|
||||
// The generator's ops are guarded on registry state, so a change can quietly stop producing them.
|
||||
assert!(TOTAL_NODES.load(Ordering::Relaxed) > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.load(Ordering::Relaxed) > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.load(Ordering::Relaxed) > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.load(Ordering::Relaxed) > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.load(Ordering::Relaxed) > 0, "the corpus never stacked a second source on a resource");
|
||||
assert!(TOTAL_COLLECTED.load(Ordering::Relaxed) > 0, "garbage collection never dropped a resource");
|
||||
assert!(TOTAL_REDONE_RETRACTIONS.load(Ordering::Relaxed) > 0, "the corpus never redid a step taken back");
|
||||
}
|
||||
|
||||
fn count_coverage(registry: &Registry) {
|
||||
let inputs = || registry.node_instances.values().flat_map(|node| node.inputs());
|
||||
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
|
||||
TOTAL_WIRED.fetch_add(inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count(), Ordering::Relaxed);
|
||||
TOTAL_INPUT_ATTRIBUTES.fetch_add(inputs().filter(|slot| !slot.attributes.is_empty()).count(), Ordering::Relaxed);
|
||||
count(&TOTAL_NODES, registry.node_instances.len());
|
||||
count(&TOTAL_WIRED, inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count());
|
||||
count(&TOTAL_INPUT_ATTRIBUTES, inputs().filter(|slot| !slot.attributes.is_empty()).count());
|
||||
let exports = registry.networks.values().flat_map(|network| &network.exports).filter(|slot| slot.target.is_some()).count();
|
||||
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
|
||||
count(&TOTAL_EXPORTS, exports);
|
||||
// A second source can only come from `AddSource`.
|
||||
TOTAL_SOURCES.fetch_add(registry.resources.values().filter(|entry| entry.sources.len() > 1).count(), Ordering::Relaxed);
|
||||
count(&TOTAL_SOURCES, registry.resources.values().filter(|entry| entry.sources.len() > 1).count());
|
||||
}
|
||||
|
||||
/// A rejoining guest keeps its `PeerId` but restarts its broadcast sequence, which the room must follow
|
||||
@@ -954,7 +1136,8 @@ fn inspect_seed() {
|
||||
let seed = std::env::var("SEED").ok().and_then(|value| value.parse().ok()).unwrap_or(0);
|
||||
let guests = std::env::var("GUESTS").ok().and_then(|value| value.parse().ok()).unwrap_or(1);
|
||||
|
||||
let (_, peers) = simulate(seed, guests, 200);
|
||||
let workload = if std::env::var_os("STROKES").is_some() { Workload::Strokes } else { Workload::Mixed };
|
||||
let (_, peers) = simulate(seed, guests, 200, workload);
|
||||
for (index, peer) in peers.iter().enumerate() {
|
||||
eprintln!("=== peer {index} head {:?}", peer.session().head_rev());
|
||||
eprintln!("registry {}", serde_json::to_string(peer.session().retired_registry()).unwrap());
|
||||
@@ -1031,7 +1214,7 @@ fn a_witness_closes_an_authors_run_before_a_gap_forms() {
|
||||
/// an edit or the wire.
|
||||
#[test]
|
||||
fn a_seed_fixes_the_run() {
|
||||
let run = |seeds: u64| (0..seeds).map(|seed| simulate(seed, 1 + (seed % 3) as usize, 200).1).collect::<Vec<_>>();
|
||||
let run = |seeds: u64| (0..seeds).map(|seed| simulate(seed, 1 + (seed % 3) as usize, 200, Workload::Mixed).1).collect::<Vec<_>>();
|
||||
|
||||
let (first, second) = (run(100), run(100));
|
||||
|
||||
|
||||
+2
-1
@@ -22,12 +22,13 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
document-format = { workspace = true, features = ["migrations"] }
|
||||
document-format = { workspace = true, features = ["migrations", "network"] }
|
||||
migration-formats = { workspace = true }
|
||||
migration-compiled = { workspace = true }
|
||||
migration-nodes = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
blake3 = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
|
||||
+11
-28
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Clock, Scheduling, Spawn, Spawner};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
clock: Arc<dyn Clock>,
|
||||
scheduling: Scheduling,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new(clock: Arc<dyn Clock>) -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
application_io: (),
|
||||
clock,
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
pub fn new() -> Self {
|
||||
Self { wake: (), application_io: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A> RuntimeBuilder<W, A> {
|
||||
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
|
||||
Self { scheduling, ..self }
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,7 @@ impl Dispatcher {
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
tools: &self.message_handlers.tool_message_handler,
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -305,6 +306,8 @@ impl Dispatcher {
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
|
||||
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user