Compare commits

..
Author SHA1 Message Date
Timon 6a463712a4 Make every registry op a timestamped, commuting write with presence stamps and tombstones, undo by restoring each step's exact prior state, record the user behind each peer, and persist settled hot op marks and the clock 2026-10-01 22:30:53 +00:00
James Lindsay 39158dec4b Improve time complexity of identity node removal (#4625)
* Improve time complexity of identity node removal

* Code review

* Ensure all passthrough nodes are removed

* Fix double test with invalid passthrough node
2026-09-30 21:35:40 +00:00
Timon 28ed22824f Update rust-gpu (#4629) 2026-09-30 12:55:10 +00:00
Dennis Kobert d10ccbedac Update Rust to version 1.98 (#4628)
* Update rust version 1.98

* Use consts::GOLDEN_RATIO
2026-09-30 13:17:46 +02:00
Shubh Pingale 55c4e6689b Fix overflow in unsaved document list in Close All dialog (#4617)
* Fix #4601: Limit unsaved document list in Close All dialog to prevent overflow

* Truncate individual long document names in Close All dialog

* Address review comments: move dialog constants to consts.rs and use write! macro

* Use Cow and iterator chaining in Close All dialog layout
2026-09-30 01:05:59 -07:00
Keavon Chambers 0c983566f6 Keep the outward wire cache exact through node input and output replacement/insertion/deletion and validate it after every test message (#4593)
Keep the outward wire cache exact through node input and output replacement, insertion, and deletion, and validate it after every test message
2026-09-30 01:05:59 -07:00
Keavon Chambers 68c3c759d5 Add a smoothstep function to the math expression language (#4623)
* Add `smoothstep(x, R)` to the math expression language

* Evaluate a smoothstep's continuity after its range, and document the trailing argument
2026-09-28 18:00:13 -07:00
Keavon Chambers ac5be43448 Add where-keyword bindings to the math expression language (#4622)
Add where bindings to the math expression language
2026-09-28 16:13:34 -07:00
James Lindsay d24919c2c3 Improve support for importing SVGs with a viewbox (#4606)
* Improve support for importing SVGs with a viewbox

* Swap fill and stroke for SVG imports
2026-09-28 18:53:36 +00:00
James Lindsay 34a9aa9a48 Update glam and enforce unchecked preconditions (#4603)
* Update glam

* More work to avoid panics

* Clean up with new FallibleVec2Operations extension trait

* Fix compile error

* Fix typo

* Fix Nix compiling rust-gpu (#4621)
2026-09-28 18:53:36 +00:00
Keavon Chambers ae321b3409 Add a warning icon to Math node expressions with errors as tooltips (#4614)
* Add a warning icon to Math node expressions with errors as tooltips

* Point at a parse error with carets under a repeat of the expression, as a compiler does

* Render fenced code blocks in tooltips and put the parse error snippet in one

* Quote tokens as code in chumsky's parse messages and in custom parser errors

* Report the parse error past an operator rather than the operator itself
2026-09-27 02:13:28 -07:00
Timon c2fb97cc81 Switch binary document format to postcard (#4608)
* Load preferences before persisted state

* Custom Value enum

* Add to_value and from_value over serde_json::Value

* Review
2026-09-27 01:09:11 +00:00
Keavon Chambers aa27f55ab5 Add matrices, with swizzle and range literals, to the math expression parser (#4611)
* Add matrices to the math expression parser as a second sort beside values

* Add Transform input and output to the Math f(x) node

* Add ranges and boxes to the math expression parser with inside, clamp, and remap over them

* Add Transform lists to the Math f(…) node with reducers composing, averaging, and counting them

* Lex a number's trailing e as Euler's number unless an exponent's digits follow it

* Fix matrix inversion scaling, exact matrix powers, infinite shears, matrix means, kept axes, and the Transform default

* Make shared box parts flat, give composed regions their inner map's axes, and fix lone logic items, spaced ranges, and the Math f(…) tooltip

* Transpose across spaces, name fractional matrix powers, check matrix builtin arities when parsing, read range literals by their corners, and let host functions shadow matrix builtins

* Make inside and clamp hold a region's uncovered parts at zero, so a box contains only the points between its corners

* Require hosts to declare the functions they provide, name the region functions' syntax node after its builtin, and remap onto ranges with equal infinite corners

* Apply a matrix to the whole product after it, so M 2 v is M (2 v)

* Pin prefix NOT's precedence above products, comparisons, and AND with tests

* Rename inside to within, since a range's ends count and the geometry predicates with a point first use that name

* Keep a range's corners as written, so clamp orders an integer past the reals' limit exactly

* Give within a tolerance of a billionth of the region's scale, so a point a float error off an edge or a flat side counts

* Write a unit part as its basis alone, so the identity displays as [1;i;j;k]

* Add tests for product folds, mixed chains, remap, and rejected inputs

* Evaluate matrix operands, builder arguments, regions, and comparison chains on the stack instead of the heap

* Build the expression parsers once per thread, since building the combinator tree cost as much as parsing a short expression

* Compare a chain reducer's items by their order directly, and reject an item with no order rather than reading it as false

* Send a host-built list of builder arguments or regions past the stack buffers to the heap instead of rejecting it
2026-09-26 15:11:16 -07:00
Kulcode 8f5d500459 Fix Alt-drag node duplication not removing the new one on right-click abort (#3782)
Fix
2026-09-26 12:16:14 -07:00
James Lindsay f7562b6fd7 Use workspace for repository, readme, homepage, and lints (#4598)
* Use workspace for repository, readme, homepage, and lints

* Use proper README for graphite-wasm-wrapper
2026-09-26 14:31:34 +00:00
James Lindsay fdcbdd1646 Avoid unused dependency warnings (#4599)
* Avoid unused dependency warnings

* Update comment
2026-09-26 14:30:39 +00:00
Keavon Chambers 2ef9c11cd3 Add piecewise expressions to the math parser (#4610)
* Fix the math expression parser giving a valid direction between multiple infinite vector parts

* Replace the math expression parser's if() with piecewise cases like {a if x > 0, b otherwise}

* Fix the math expression parser's error spans starting before whitespace and infinities displaying as inf
2026-09-25 17:33:46 -07:00
Keavon Chambers 46c84c21fe Add Vec2 input/output in the Math nodes with quaternion support in the math expression parser (#4609)
* Extend the math expression parser's value ladder past complex numbers to quaternions

* Add a vector function family (dot, cross, rotate, slerp, and more) to the math expression parser

* Let hosts read a math expression result as a 1D to 3D vector or weighted particle

* Let the 'Math f(x)' and 'Math f(…)' nodes take and output Vec2 values

* Remove unfulfillable dead_code expectations from methods reached only through replay
2026-09-25 16:06:23 -07:00
Timon b1b372f1d6 Move all documents into platform-provided document store (#4573)
* Migrate autosaves to document store

* Review
2026-09-25 01:40:03 +00:00
Keavon Chambers 907b7d5ce3 Make the math expression parser use ints instead of floats for exact whole-number math (#4596)
Make the math expression parser store whole numbers exactly as integers and classify each value by its minimal rung
2026-09-24 17:44:25 -07:00
Keavon Chambers ddafaaa757 Add an "Output Type" parameter to the 'Math f(x)' and 'Math f(…)' nodes (#4591)
Add an 'Output Type' choice to the 'Math f(x)' and 'Math f(…)' nodes
2026-09-23 20:26:51 -07:00
Keavon Chambers 2c1cca7e99 Rename the TaggedValue I64/F64/F64Array variants to Integer/Number/Numbers (#4590)
Rename the TaggedValue F64/I64/F64Array variants to Number/Integer/Numbers
2026-09-23 18:02:06 -07:00
Keavon Chambers c91d0cd5a3 Update all node parameters with appropriate attributes of #[unit(...)], bounds, etc., deprecating the type alias units pattern (#4589)
Replace the node parameter typedefs with unit and widget attributes
2026-09-23 17:08:05 -07:00
Dennis Kobert 84ed60a404 Route every network interface write through a single-writer store (#4586)
* Route every network interface write through a single-writer store

* Keep the existing previewing behaviour and fix the review findings that remain

* Record what each store write changed and stage it into the working copy

* Fix the delta path's resource staging, batch liveness, and stale comparisons

* Keep batch resource liveness and load-time repairs consistent with what reaches storage

* Correct the delta documentation and stop persisting pinned nodes the network lost

* Swap a node's implementation in place instead of rebuilding the node

* Resolve network attributes through the same source as the IDs they name

* Resolve an implementation swap by timestamp and let an edit report whether it changed the value
2026-09-23 21:52:02 +00:00
Keavon Chambers 942d138fc1 Add #[multiline] and #[progression] node parameter attributes for choosing a type's preferred widget variant (#4587)
Add #[multiline] and #[progression] node parameter attributes for choosing a widget
2026-09-23 13:44:49 -07:00
246 changed files with 14565 additions and 4973 deletions

No files matched your search

+6 -5
View File
@@ -1,7 +1,7 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
extensions = [
"rust-src"
"rust-analyzer"
@@ -32,11 +32,12 @@ let
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
src = pkgs.fetchgit {
url = "https://github.com/Rust-GPU/rust-gpu";
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
};
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
Generated
+163 -154
View File
File diff suppressed because it is too large. Load diff
+11 -6
View File
@@ -53,7 +53,7 @@ default-members = [
resolver = "2"
[workspace.package]
rust-version = "1.88"
rust-version = "1.98"
edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
@@ -114,7 +114,7 @@ rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
rmp-serde = "1.3"
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -172,7 +172,6 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
@@ -182,10 +181,12 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.32.1", default-features = false, features = [
glam = { version = "0.33", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
blake3 = "1.5"
@@ -239,8 +240,12 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
+3
View File
@@ -7,6 +7,9 @@ mod mac;
#[cfg(target_os = "windows")]
mod win;
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
use cef_dll_sys as _;
fn main() {
#[cfg(target_os = "linux")]
linux::main().unwrap();
+3
View File
@@ -5,6 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+8 -15
View File
@@ -25,7 +25,7 @@ use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -99,7 +99,13 @@ impl App {
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let desktop_wrapper = DesktopWrapper::new(
rand::rng().random(),
Arc::new(resource_storage),
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
wgpu_context.clone(),
wake,
);
Self {
render_state: None,
@@ -307,19 +313,6 @@ impl App {
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
}
+50 -52
View File
@@ -1,6 +1,9 @@
use crate::wrapper::messages::{DocumentId, PersistedState};
use crate::wrapper::messages::PersistedState;
pub(crate) fn read_state() -> PersistedState {
if let Err(error) = migrate_documents() {
tracing::error!("Autosave migration failed: {error}");
}
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
@@ -13,16 +16,13 @@ pub(crate) fn read_state() -> PersistedState {
return PersistedState::default();
}
};
let loaded = match ron::from_str(&data) {
match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return PersistedState::default();
PersistedState::default()
}
};
garbage_collect_document_files(&loaded);
loaded
}
}
pub(crate) fn write_state(state: PersistedState) {
@@ -37,47 +37,6 @@ pub(crate) fn write_state(state: PersistedState) {
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(state);
}
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
fn state_file_path() -> std::path::PathBuf {
@@ -86,8 +45,47 @@ fn state_file_path() -> std::path::PathBuf {
path
}
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
// TODO: Remove this migration code
fn migrate_documents() -> std::io::Result<()> {
let root = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
tracing::error!("Skipping an unreadable autosave entry: {error}");
continue;
}
};
if let Err(error) = migrate_document(&root, &entry) {
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
}
}
Ok(())
}
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
let path = entry.path();
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
return Ok(());
}
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
return Ok(());
};
let destination = root.join(format!("{id:016x}"));
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
std::fs::create_dir_all(&destination)?;
let staging = destination.join("legacy.graphite.migrating");
std::fs::copy(&path, &staging)?;
std::fs::rename(staging, destination.join("legacy.graphite"))?;
}
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
if backup.exists() {
return Ok(());
}
std::fs::rename(path, backup)
}
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -44,10 +44,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
@@ -69,18 +69,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
}
+3 -2
View File
@@ -10,6 +10,7 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
@@ -32,7 +33,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -43,7 +44,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error poling node graph: {}", e);
tracing::error!("Error polling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
-11
View File
@@ -44,13 +44,6 @@ pub enum DesktopFrontendMessage {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceWritePreferences {
preferences: Preferences,
},
@@ -59,9 +52,6 @@ pub enum DesktopFrontendMessage {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -92,7 +82,6 @@ pub enum DesktopWrapperMessage {
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
+7
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
zip = ["dep:zip"]
@@ -34,6 +40,7 @@ web-sys = { workspace = true, features = [
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemRemoveOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
@@ -6,6 +6,7 @@ use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Clone)]
pub struct FolderBackend {
root: PathBuf,
}
+3 -3
View File
@@ -2,11 +2,11 @@
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
#[derive(Default)]
#[derive(Clone, Default)]
pub struct MemoryBackend {
files: Mutex<HashMap<String, Vec<u8>>>,
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
}
impl MemoryBackend {
+67 -11
View File
@@ -3,6 +3,7 @@
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::cell::Cell;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
@@ -40,6 +41,33 @@ struct Inner {
worker_active: bool,
}
thread_local! {
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
}
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
if is_not_found(error) {
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
return;
}
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
let now = js_sys::Date::now();
// Debounce alerts to avoid spamming the user
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
return;
}
LAST_WRITE_FAILURE_ALERT.set(Some(now));
if let Some(window) = web_sys::window() {
let message = format!(
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
{operation} {path}: {error:?}"
);
let _ = window.alert_with_message(&message);
}
}
#[derive(Clone)]
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
@@ -77,8 +105,6 @@ impl OpfsBackend {
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
@@ -239,12 +265,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
log::error!("OPFS background write for {path} failed: {error:?}");
report_write_error("write", &path, &error);
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
log::error!("OPFS background append for {path} failed: {error:?}");
report_write_error("append", &path, &error);
}
}
Mutation::Delete { path } => {
@@ -252,7 +278,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
log::error!("OPFS background delete for {path} failed: {error:?}");
report_write_error("delete", &path, &error);
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
@@ -263,16 +289,11 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
let mut current = opfs_root().await?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
@@ -283,6 +304,37 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
Ok(current)
}
/// List the subdirectories directly under `directory_path`.
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
crate::validate_prefix(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
}
/// Remove `directory_path` recursively.
pub async fn remove_directory(directory_path: &str) -> Result<()> {
validate_path(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
let removed = async {
let (parent, name) = descend(&root, directory_path, false).await?;
let options = web_sys::FileSystemRemoveOptions::new();
options.set_recursive(true);
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
}
.await;
match removed {
Ok(_) => Ok(()),
Err(error) if is_not_found(&error) => Ok(()),
Err(error) => Err(js_err(error)),
}
}
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
JsFuture::from(storage.get_directory()).await?.dyn_into()
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
@@ -473,3 +525,7 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
js_err(error)
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
+2
View File
@@ -12,6 +12,7 @@
pub mod archive;
pub mod backends;
pub mod store;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
@@ -350,6 +351,7 @@ impl<C: Container + ?Sized> AsyncContainer for C {
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
#[derive(Clone)]
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
+145
View File
@@ -0,0 +1,145 @@
use crate::backends::memory::MemoryBackend;
use crate::{AnyContainer, Result};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DocumentKey(pub u64);
#[cfg(not(target_family = "wasm"))]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
pub trait DocumentStore: Send + Sync {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>>;
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer>;
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()>;
}
fn directory_name(key: DocumentKey) -> String {
format!("{:016x}", key.0)
}
fn parse_directory_name(name: &str) -> Option<DocumentKey> {
(name.len() == 16 && name.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then(|| u64::from_str_radix(name, 16).ok().map(DocumentKey))
.flatten()
}
#[derive(Default)]
pub struct MemoryStore {
documents: Mutex<HashMap<DocumentKey, MemoryBackend>>,
}
impl DocumentStore for MemoryStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
let mut keys: Vec<_> = self.documents.lock().unwrap().keys().copied().collect();
keys.sort();
Box::pin(async move { Ok(keys) })
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
let backend = self.documents.lock().unwrap().entry(key).or_default().clone();
Box::pin(async move { Ok(AnyContainer::Memory(backend)) })
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
self.documents.lock().unwrap().remove(&key);
Box::pin(async { Ok(()) })
}
}
#[cfg(not(target_family = "wasm"))]
pub struct FolderStore {
root: std::path::PathBuf,
}
#[cfg(not(target_family = "wasm"))]
impl FolderStore {
pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
Self { root: root.into() }
}
}
#[cfg(not(target_family = "wasm"))]
impl DocumentStore for FolderStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let entries = match std::fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut keys: Vec<_> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.filter_map(|entry| parse_directory_name(&entry.file_name().to_string_lossy()))
.collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::folder::FolderBackend::create(self.root.join(directory_name(key)))?;
Ok(AnyContainer::Folder(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move {
match std::fs::remove_dir_all(self.root.join(directory_name(key))) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
})
}
}
#[cfg(target_family = "wasm")]
pub struct OpfsStore {
root: String,
}
#[cfg(target_family = "wasm")]
impl OpfsStore {
pub fn new(root: impl Into<String>) -> Self {
Self {
root: root.into().trim_matches('/').to_string(),
}
}
fn document_path(&self, key: DocumentKey) -> String {
let name = directory_name(key);
if self.root.is_empty() { name } else { format!("{}/{name}", self.root) }
}
}
#[cfg(target_family = "wasm")]
impl DocumentStore for OpfsStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let paths = crate::backends::opfs::list_directories(&self.root).await?;
let mut keys: Vec<_> = paths.iter().filter_map(|path| parse_directory_name(path.rsplit('/').next()?)).collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::opfs::OpfsBackend::open(&self.document_path(key)).await?;
Ok(AnyContainer::Opfs(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move { crate::backends::opfs::remove_directory(&self.document_path(key)).await })
}
}
+12
View File
@@ -176,3 +176,15 @@ fn folder_backend_write_sized_fills_via_mmap() {
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
#[test]
fn memory_backend_clones_share_the_store() {
let backend = MemoryBackend::new();
let clone = backend.clone();
backend.write("file", b"through the original").unwrap();
assert_eq!(clone.read("file").unwrap().as_slice(), b"through the original");
clone.remove("file").unwrap();
assert!(!backend.exists("file"));
}
+7 -1
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
@@ -27,7 +33,7 @@ graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
rmp-serde = { workspace = true }
postcard = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
+33 -51
View File
@@ -8,18 +8,16 @@ pub enum Codec {
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// A single MessagePack blob. `append` to a non-empty buffer errors.
MessagePack,
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
MessagePackFrames,
/// A single postcard blob. `append` to a non-empty buffer errors.
Postcard,
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
PostcardFrames,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
@@ -41,8 +39,8 @@ impl Codec {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
Codec::Postcard => "bin",
Codec::PostcardFrames => "frames",
}
}
@@ -62,15 +60,15 @@ impl Codec {
output.push(b'\n');
Ok(())
}
Codec::MessagePack => {
Codec::Postcard => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
rmp_serde::encode::write(output, value)?;
postcard::to_io(value, &mut *output)?;
Ok(())
}
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(value)?;
Codec::PostcardFrames => {
let payload = postcard::to_stdvec(value)?;
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
output.extend_from_slice(&length.to_be_bytes());
output.extend_from_slice(&payload);
@@ -91,11 +89,11 @@ impl Codec {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Codec::Postcard => {
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
Codec::PostcardFrames => Box::new(PostcardFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
@@ -153,12 +151,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
}
}
struct MessagePackFrameIter<'a, T> {
struct PostcardFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
@@ -183,7 +181,7 @@ impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
Some(postcard::from_bytes(frame).map_err(CodecError::from))
}
}
@@ -224,31 +222,20 @@ mod tests {
}
#[test]
fn message_pack_round_trip_single() {
fn postcard_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
let bytes = Codec::Postcard.write_single(&frame).unwrap();
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn message_pack_append_to_non_empty_errors() {
fn postcard_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
#[test]
fn message_pack_round_trips_serde_json_value() {
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
let bytes = Codec::MessagePack.write_single(&value).unwrap();
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, value);
}
#[test]
fn json_lines_round_trip_and_skip_blanks() {
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
@@ -263,13 +250,13 @@ mod tests {
}
#[test]
fn message_pack_frames_round_trip() {
fn postcard_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
@@ -277,27 +264,27 @@ mod tests {
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
/// than decoding a partial value into a plausible-but-wrong one.
#[test]
fn message_pack_frames_detect_truncation() {
fn postcard_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
}
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
#[test]
fn message_pack_frames_detect_truncated_length_prefix() {
fn postcard_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
}
#[test]
fn write_single_then_read_with_iter_yields_one() {
let frame = Frame { id: 5, label: "one".into() };
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
let bytes = codec.write_single(&frame).unwrap();
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
@@ -315,12 +302,7 @@ mod tests {
#[test]
fn extensions_are_distinct() {
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
+3
View File
@@ -35,6 +35,9 @@ pub enum Error {
#[cfg(feature = "conversion")]
#[error("commit error: {0}")]
Commit(#[from] CommitError),
/// The container has no manifest, cannot be opened.
#[error("container has no manifest")]
MissingManifest,
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
WrongFormat { found: String, expected: &'static str },
+4
View File
@@ -146,10 +146,14 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
+42 -44
View File
@@ -6,7 +6,6 @@
//!
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
use std::sync::Arc;
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
// gated off wasm to avoid unused-import warnings.
#[cfg(not(target_family = "wasm"))]
@@ -14,10 +13,10 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -49,30 +48,28 @@ pub type GddV1 = Gdd<GddV1Layout>;
pub const MANIFEST_CODEC: Codec = Codec::Json;
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for users who
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
///
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// through the container's sync write surface. Only `open` / `export` are async, since they
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
pub(crate) working: AnyContainer,
pub(crate) layout: L,
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
@@ -80,10 +77,10 @@ pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) manifest: Manifest,
/// 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, serde_json::Value>,
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -101,10 +98,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 async 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, 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).await
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
}
}
@@ -124,10 +121,14 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
Ok(manifest) => manifest,
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
Err(error) => return Err(error.into()),
};
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
@@ -140,18 +141,19 @@ impl<L: Layout> Gdd<L> {
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let user = session_state.user_id;
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -159,11 +161,15 @@ impl<L: Layout> Gdd<L> {
session.publish_up_to(rev);
}
session.restore_hot_sequence(session_state.last_hot_sequence);
session.restore_clock(session_state.clock);
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
session.absorb_settled_marks(&session_state.settled);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
Ok(Self {
session,
working: Arc::new(working),
working,
layout,
manifest,
view_settings: session_state.view_settings,
@@ -173,11 +179,15 @@ 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 async 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, 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, ..Default::default() };
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
@@ -185,7 +195,7 @@ impl<L: Layout> Gdd<L> {
Ok(Self {
session,
working: Arc::new(working),
working,
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
@@ -256,13 +266,13 @@ impl<L: Layout> Gdd<L> {
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::Value> {
&self.view_settings
}
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
&self.network_view_settings
}
@@ -285,11 +295,8 @@ impl<L: Layout> Gdd<L> {
}
/// Drop the session and return the working-copy container + layout.
/// Intended for test code that needs to reopen against the same container; panics if the container
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
pub fn into_storage(self) -> (AnyContainer, L) {
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
(working, self.layout)
(self.working, self.layout)
}
/// Resolve every proto-node declaration referenced by the registry or its history into a
@@ -320,16 +327,7 @@ impl<L: Layout> Gdd<L> {
declarations
}
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
// TODO: Add feature gate for legacy embedding
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
}
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
/// Read the embedded legacy `.graphite` document, if present.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
+11 -9
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp};
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -173,7 +173,7 @@ impl<L: Layout> Gdd<L> {
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
@@ -194,10 +194,14 @@ impl<L: Layout> Gdd<L> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -205,18 +209,16 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
Ok(())
}
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
@@ -232,7 +234,7 @@ impl<L: Layout> Gdd<L> {
/// enters the registry, history, or CRDT.
pub fn set_network_view_settings(
&mut self,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
self.persist_session_state()
+2 -3
View File
@@ -4,7 +4,6 @@
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
@@ -39,7 +38,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(not(target_family = "wasm"))]
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
let dest_path = self.layout.resource_path(&hash);
if let AnyContainer::Folder(folder) = self.working.as_ref() {
if let AnyContainer::Folder(folder) = &self.working {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
@@ -102,7 +101,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
}
}
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
+22 -6
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,13 +15,17 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, which the peer registers as, so authorship and undo follow the person
/// across the peer ids they accumulate.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
pub head_rev: Option<Rev>,
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub last_broadcast_rev: Option<Rev>,
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
@@ -31,12 +35,24 @@ pub struct SessionState {
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: u64,
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
/// reopen never reuses a spent sequence.
#[serde(default)]
pub last_hot_sequence: HotSequence,
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_settings: BTreeMap<String, serde_json::Value>,
#[serde(default)]
pub view_settings: BTreeMap<String, Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
#[serde(default)]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
/// time. About one sequence per author; runs only for ops in flight when saved.
#[serde(default)]
pub settled: SettledHotOps,
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
/// carries any more.
#[serde(default)]
pub clock: u64,
}
+45 -70
View File
@@ -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, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
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()).await {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,9 +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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -99,9 +97,7 @@ fn manifest_returns_what_create_in_wrote() {
#[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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
@@ -116,9 +112,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
@@ -128,6 +122,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -143,9 +138,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
@@ -154,6 +147,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -161,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -189,9 +184,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
@@ -200,6 +193,7 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -220,9 +214,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -231,7 +223,7 @@ fn export_folder_round_trips_through_open() {
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
@@ -250,9 +242,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -277,9 +267,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -302,9 +290,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -334,9 +320,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -365,9 +349,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(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";
@@ -391,9 +373,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -416,14 +396,12 @@ fn export_carries_resources() {
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::NoMetadata;
use document_graph_storage::{NoMetadata, to_value};
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(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// 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.
@@ -470,8 +448,8 @@ fn embed_all_resources_materializes_link_only_resource() {
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
assert_eq!(entry.hash, Some(hash));
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let embedded = to_value(&DataSource::Embedded).unwrap();
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
});
@@ -488,9 +466,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
@@ -531,9 +507,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -586,14 +560,12 @@ 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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.registry, Codec::Postcard);
assert_eq!(codecs.history, Codec::PostcardFrames);
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
@@ -609,9 +581,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -630,11 +600,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
});
}
@@ -645,9 +623,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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 hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -655,12 +631,13 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
let (working, layout) = gdd.into_storage();
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
@@ -698,9 +675,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())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
+108
View File
@@ -0,0 +1,108 @@
// Staging a whole document after a recorded batch, and what a reopen must carry over.
#![cfg(feature = "conversion")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
fn network_with_one_node() -> NodeNetwork {
let node = DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: [(NodeId(1), node)].into_iter().collect(),
..Default::default()
}
}
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
.expect("first whole-document stage");
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
let hot_before = gdd.session().hot_log().len();
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
.expect("the runtime already matches what was staged");
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
}
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
#[test]
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
let set = |value: u32, counter: u64| HotOp {
op: RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
},
timestamp: TimeStamp { counter, peer: PeerId(22) },
sequence: HotSequence(counter),
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(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();
let retired = gdd.session().retired_registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
/// since a reused sequence would let a peer's settled marks drop the new op.
#[test]
fn a_reopen_continues_the_hot_op_sequence() {
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
};
// Stages one op and returns the sequence it got.
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 up_to = gdd.session().hot_log().last().unwrap().timestamp;
gdd.retire(up_to).unwrap();
let last = stage(&mut gdd, set(2));
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);
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
reopened.retire(up_to).unwrap();
let last = reopened.session().last_hot_sequence().0;
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);
});
}
+7 -1
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
@@ -22,7 +28,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
rmp-serde = { workspace = true }
postcard = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
+37 -16
View File
@@ -1,4 +1,4 @@
use crate::TimeStamp;
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -8,33 +8,54 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
timestamp,
deleted: true,
}
}
}
pub type Attributes = BTreeMap<String, Value>;
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
/// write is dropped and an older tombstone is redundant.
pub type Attributes = BTreeMap<String, AttributeValue>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
/// Inserts `value` under `key`.
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
/// Serializes `value` and inserts it under `key`.
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
self.set(key, serde_json::to_value(value)?, timestamp);
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
@@ -43,8 +64,8 @@ pub trait AttributesWrite {
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
}
}
@@ -66,6 +87,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
}
}
@@ -31,6 +31,7 @@ pub mod node {
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
+78 -47
View File
@@ -1,13 +1,15 @@
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use crate::{
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
Value, attr, compute_rev,
};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
/// different local states would otherwise compute different Revs for the same logical op.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -16,16 +18,22 @@ pub struct Delta {
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
#[serde(default)]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
@@ -35,6 +43,7 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -52,9 +61,10 @@ impl Delta {
parent,
author,
timestamp,
reverse: kind.clone(),
reverse: Vec::new(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -69,11 +79,16 @@ impl Delta {
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
@@ -98,8 +113,7 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -119,6 +133,15 @@ pub enum RegistryDelta {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
@@ -143,13 +166,12 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` lets the reverse delta rebuild without re-walking history.
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -171,16 +193,15 @@ pub enum RegistryDelta {
AddSource {
id: ResourceId,
key: SourceKey,
source: serde_json::Value,
source: Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
/// registers again and the newest registration wins wherever it lands.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -195,42 +216,52 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
EndTransaction,
// Allow for future delta types without a model change
Other(serde_json::Value),
Other(Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
pub value: Option<Value>,
}
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
/// leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if timestamp <= decided {
return;
}
let entry = match value {
Some(value) => AttributeValue::new(value, timestamp),
None => AttributeValue::deleted(timestamp),
};
attributes.insert(key, entry);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
let mut stamped = base.clone();
stamped.retired_at_ms = 1_790_000_000_000;
let bare_base = postcard::to_allocvec(&base).expect("encode");
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
assert_eq!(decoded.retired_at(), None);
}
}
+18 -18
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
for (key, _) in from.live_sources() {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
for (key, to_source) in to.live_sources() {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
for (key, _) in crate::attributes::live(from) {
if to.get(key).is_none_or(|value| value.deleted) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
for (key, to_value) in crate::attributes::live(to) {
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -218,7 +218,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
#[cfg(test)]
mod tests {
use super::*;
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
#[test]
fn test_compute_deltas_empty() {
@@ -287,6 +287,7 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -304,11 +305,7 @@ mod tests {
from.networks.insert(NetworkId(0), Network::default());
let mut to = from.clone();
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
@@ -341,9 +338,10 @@ mod tests {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("old"),
crate::AttributeValue {
value: Value::Str("old".into()),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -351,9 +349,10 @@ mod tests {
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("new"),
crate::AttributeValue {
value: Value::Str("new".into()),
timestamp: stamp(1),
deleted: false,
},
);
@@ -376,9 +375,10 @@ mod tests {
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::Value {
value: serde_json::json!("value"),
crate::AttributeValue {
value: Value::Str("value".into()),
timestamp: stamp(1),
deleted: false,
},
);
+534 -306
View File
@@ -1,23 +1,29 @@
use std::collections::btree_map::Entry;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use crate::{
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
apply_attribute_delta, reverse_attribute_delta,
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
};
#[derive(Clone, Debug)]
pub struct Document {
/// Working registry: retired state with the current hot ops applied on top. This is what live
/// reads and `registry()` observe, and what undo/redo force-apply against.
/// reads and `registry()` observe.
pub(crate) working_registry: Registry,
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
pub(crate) hot_log: Vec<HotOp>,
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
pub(crate) hot_timestamps: HashSet<TimeStamp>,
/// Which hot ops are retired into history, so a late copy is dropped;
/// retired deltas keep no link back to their hot ops.
pub(crate) settled: SettledHotOps,
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
/// new edits win
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
/// empty.
pub(crate) retired_snapshot: Registry,
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
pub(crate) head: Option<Rev>,
@@ -28,97 +34,129 @@ pub struct Document {
pub(crate) redo_stack: Vec<Rev>,
pub(crate) clock: LamportClock,
pub(crate) peer: PeerId,
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
/// Commits after this can be rewritten silently; commits at or before this are published
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
/// The person behind this peer; what `RegisterPeer` records for it.
pub(crate) user: UserId,
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
/// to it are published and stay. `None` means nothing published yet.
pub(crate) last_broadcast_rev: Option<Rev>,
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
/// reading the same counter still produce distinct IDs.
pub(crate) next_node_counter: u64,
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
pub(crate) last_hot_sequence: HotSequence,
}
impl Document {
/// An empty document for `peer`, at the origin of its clock.
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
Self {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
hot_timestamps: HashSet::new(),
settled: SettledHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
user,
last_broadcast_rev: None,
next_node_counter: 0,
last_hot_sequence: HotSequence::NONE,
}
}
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
/// truncated; the counter is shared across peers and persisted with the document.
pub fn next_node_id(&mut self) -> NodeId {
self.next_node_counter += 1;
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
let digest = blake3::hash(&bytes);
let mut hasher = blake3::Hasher::new();
postcard::to_io(&(self.peer, self.next_node_counter), &mut hasher).expect("(PeerId, counter) must serialize");
let digest = hasher.finalize();
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
self.revert_delta(target, delta)
}
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
// which is what we want to re-apply.
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
self.revert_delta(target, delta)
}
/// Search every delta reachable from `head` (following all parents, including a merge's
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
/// ancestry reachability, so a node added only on a merged-in branch is still found.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
while let Some(rev) = queue.pop_front() {
let Some(delta) = self.history.get(rev) else { continue };
if predicate(delta) {
return Some(delta.clone());
}
for parent in delta.all_parents() {
if seen.insert(parent) {
queue.push_back(parent);
}
}
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
if self.hot_log.is_empty() {
crate::prior::restore(&mut self.working_registry, &delta.reverse);
}
None
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
std::mem::swap(&mut delta.kind, &mut delta.reverse);
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
}
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
/// Doesn't touch history or `head` — hot ops are transient.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
self.hot_timestamps.insert(hot_op.timestamp);
self.hot_log.push(hot_op);
Ok(())
}
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
/// than an error.
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
/// reflected in the registry changes nothing.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
if self.settled.covers(hot_op.id()) {
return Ok(());
}
// A re-announcement of a held op must not become a second copy.
if self.hot_timestamps.contains(&hot_op.timestamp) {
return Ok(());
}
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
if hot_op.timestamp.peer == self.peer {
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
}
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_timestamps.insert(hot_op.timestamp);
self.hot_log.push(hot_op);
Ok(())
}
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
/// targets, Remove on missing ones) since hot ops already produced the structural state.
/// The point is to bump field timestamps to T_retire via the LWW arms.
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
self.settled.absorb(remote);
self.drop_settled_hot_ops()
}
/// Bring the stamp index back in line after the hot log was filtered as a whole.
pub(crate) fn resync_hot_timestamps(&mut self) {
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
}
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
/// be applied in place. O(N + L), for rare paths only.
pub(crate) fn rebuild_working(&mut self) {
self.working_registry = self.retired_snapshot.clone();
for hot_op in std::mem::take(&mut self.hot_log) {
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
self.hot_log.push(hot_op);
}
}
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
fn drop_settled_hot_ops(&mut self) -> bool {
let before = self.hot_log.len();
let settled = &self.settled;
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
let dropped = self.hot_log.len() != before;
if dropped {
self.resync_hot_timestamps();
self.rebuild_working();
}
dropped
}
/// Apply a retired commit and record it in history.
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
@@ -138,312 +176,503 @@ impl Document {
}
}
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
match target {
RegistryTarget::Working => &self.working_registry,
RegistryTarget::Snapshot => &self.retired_snapshot,
}
}
/// New local/remote op against the working registry: add ops error on duplicate targets and
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
#[cfg(test)]
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
}
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
/// An op from a peer or from persisted state, against the working registry.
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
}
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
/// exists included, so the registry folds to the same values whatever order the ops land in:
///
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
/// and the removal's snapshot folds in like any other write.
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
// Advance the local clock past every observed op, including ones that subsequently no-op or
// error. Observation is about causality knowledge, not about whether the op took effect.
self.clock.observe(timestamp);
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
// LWW arms assign unconditionally only under `Force`.
let idempotent = mode != ApplyMode::Live;
let force = mode == ApplyMode::Force;
// Resurrect any concurrently-removed targets the op references before binding the registry
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
self.ensure_referenced_exist(target, &op)?;
let live = mode == ApplyMode::Live;
let registry = self.registry_mut(target);
match op {
RegistryDelta::AddNode { id, node } => {
if registry.node_instances.contains_key(&id) {
if idempotent {
// Hot ops already created this node; skip rather than error.
return Ok(());
}
if live && registry.node_instances.contains_key(&id) {
return Err(CrdtError::NodeAlreadyExists(id));
}
registry.node_instances.insert(id, node);
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
}
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
RegistryDelta::RemoveNode { id, snapshot } => {
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
node.inputs = inputs;
RegistryDelta::SetNodeInputs { id, mut inputs } => {
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
let referenced: Vec<NodeId> = inputs
.iter()
.filter_map(|slot| match slot.input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
})
.collect();
ensure_seen(registry, &referenced, mode)?;
write_node(registry, id, timestamp, mode, |node| {
merge_inputs(node, inputs, timestamp);
Ok(())
})?;
for referenced in referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
let referenced = match new_input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
if timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
ensure_seen(registry, &[id], mode)?;
if let Implementation::Network(network) = implementation {
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
}
write_node(registry, id, timestamp, mode, |node| {
if timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
}
Ok(())
})?;
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
write_node(registry, id, timestamp, mode, |node| {
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::SetNetworkExport { id, index, export } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
let referenced = match export {
Some(NodeInput::Node { id, .. }) => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_network(registry, id, timestamp, mode, |net| {
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
net.exports.resize(slot_idx + 1, ExportSlot::default());
}
net.exports.resize(
slot_idx + 1,
ExportSlot {
target: None,
timestamp: TimeStamp::ORIGIN,
},
);
}
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
let existing = &mut net.exports[slot_idx];
if timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::AddNetwork { id, network: contents } => {
if registry.networks.contains_key(&id) {
if idempotent {
return Ok(());
}
RegistryDelta::AddNetwork { id, network } => {
if live && registry.networks.contains_key(&id) {
return Err(CrdtError::NetworkAlreadyExists(id));
}
registry.networks.insert(id, contents);
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
}
RegistryDelta::RemoveNetwork { id, .. } => {
registry.networks.remove(&id);
RegistryDelta::RemoveNetwork { id, snapshot } => {
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
}
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
write_network(registry, id, timestamp, mode, |net| {
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::SetResourceHash { id, hash } => {
let entry = registry.resources.entry(id).or_default();
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
upsert_resource(registry, id, timestamp, |entry| {
if timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
});
}
RegistryDelta::AddSource { id, key, source } => {
let entry = registry.resources.entry(id).or_default();
let value = SourceValue { source, timestamp };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
upsert_resource(registry, id, timestamp, |entry| {
let value = SourceValue { source, timestamp, deleted: false };
entry.set_source(key, value);
});
}
RegistryDelta::RemoveSource { id, key } => {
if let Some(entry) = registry.resources.get_mut(&id) {
if force {
entry.force_remove_source(&key);
} else {
entry.remove_source(&key, timestamp);
}
}
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
upsert_resource(registry, id, timestamp, |entry| {
entry.remove_source(&key, timestamp);
});
}
RegistryDelta::AddResource { id, entry } => {
registry.resources.insert(id, entry);
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
}
RegistryDelta::RemoveResource { id, .. } => {
registry.resources.remove(&id);
RegistryDelta::RemoveResource { id, snapshot } => {
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
}
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
Some(_) => {}
None => {
registry.peer_users.insert(peer, user);
RegistryDelta::RegisterPeer { peer, user } => {
// The newest registration of a device wins, whatever order they land in.
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
}
},
}
RegistryDelta::ChangeDocumentAttribute { delta } => {
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
}
// Merge is a structural sync point only; it mutates no registry state.
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
Ok(())
}
}
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
/// before the node. No-op for ops that reference nothing absent.
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
if let NodeInput::Node { id: referenced, .. } = new_input {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_node_exists(target, *id)?;
/// An entity whose existence and every field are last-writer-wins on a timestamp.
pub(crate) trait Presence: Sized {
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
fn presence(&self) -> TimeStamp;
fn set_presence(&mut self, at: TimeStamp);
/// Stamps every field at `at`, the way an addition writes all of them.
fn stamp_all(&mut self, at: TimeStamp);
/// Folds `other` in, keeping whichever value of each field is newer.
fn merge(&mut self, other: Self);
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
/// Every field is at the origin, so the addition's values win.
fn placeholder() -> Self;
}
impl Presence for Node {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.added = at;
self.inputs_timestamp = at;
self.implementation_timestamp = at;
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
if other.added > self.added {
self.network = other.network;
self.added = other.added;
}
if other.implementation_timestamp > self.implementation_timestamp {
self.implementation = other.implementation;
self.implementation_timestamp = other.implementation_timestamp;
}
merge_inputs(self, other.inputs, other.inputs_timestamp);
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for Network {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Network::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
let len = self.exports.len().max(other.exports.len());
self.exports.resize_with(len, ExportSlot::default);
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
if incoming.timestamp > slot.timestamp {
*slot = incoming;
}
RegistryDelta::SetNodeInputs { id, inputs } => {
for slot in inputs {
if let NodeInput::Node { id: referenced, .. } = slot.input {
self.ensure_node_exists(target, referenced)?;
}
}
self.ensure_node_exists(target, *id)?;
}
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for ResourceEntry {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
ResourceEntry::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.hash_timestamp = at;
self.stamp_sources(at);
}
fn merge(&mut self, other: Self) {
if other.hash_timestamp > self.hash_timestamp {
self.hash = other.hash;
self.hash_timestamp = other.hash_timestamp;
}
self.merge_sources(other.sources, other.sources_timestamp);
self.presence = self.presence.max(other.presence);
}
}
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
slot.timestamp = at;
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
}
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
attributes.retain(|_, value| !value.deleted);
attributes.values_mut().for_each(|value| value.timestamp = at);
*floor = at;
}
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
/// write and survives. Where both hold a key, the newer entry wins.
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
attributes.retain(|_, value| value.timestamp >= other_floor);
for (key, value) in other {
match attributes.entry(key) {
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
Entry::Vacant(entry) if value.timestamp >= *floor => {
entry.insert(value);
}
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport {
id: network, export: export_target, ..
} => {
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_network_exists(target, *network)?;
}
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
_ => {}
}
Ok(())
}
*floor = (*floor).max(other_floor);
}
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
self.restore_node_from_history(target, node_id)?;
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
/// write and a per-slot write thus land the same in either order.
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
let (mut newer, shape, older) = if at > node.inputs_timestamp {
(other, at, std::mem::take(&mut node.inputs))
} else {
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
};
for (index, incoming) in older.into_iter().enumerate() {
if index >= newer.len() {
if slot_newest(&incoming) <= shape {
continue;
}
newer.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(())
}
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
if !self.registry_ref(target).networks.contains_key(&network_id) {
self.restore_network_from_history(target, network_id)?;
let slot = &mut newer[index];
if incoming.timestamp > slot.timestamp {
slot.input = incoming.input;
slot.timestamp = incoming.timestamp;
}
Ok(())
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
}
node.inputs = newer;
node.inputs_timestamp = shape;
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
/// capture the true pre-op value rather than the hot-polluted working state.
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
let registry = self.registry_ref(target);
Ok(match delta {
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
&RegistryDelta::SetNodeInputs { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
}
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
RegistryDelta::ChangeNodeInput {
id,
index: input_idx,
new_input: slot.input.clone(),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node.attributes()),
}
}
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
RegistryDelta::ChangeNodeInputAttribute {
id,
index,
delta: reverse_attribute_delta(delta, &input.attributes),
}
}
&RegistryDelta::SetNetworkExport { id, index, .. } => {
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
// since pre-forward there was no export to point at.
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
RegistryDelta::SetNetworkExport { id, index, export: export_target }
}
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
RegistryDelta::ChangeNetworkAttribute {
id,
delta: reverse_attribute_delta(delta, current),
}
}
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
delta: reverse_attribute_delta(delta, &registry.attributes),
},
// Registrations are append-only and not user-undoable; reverse is the same op,
// which applies as a no-op on the already-registered PeerId.
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
id,
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
},
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
// The slot already held a source: undo restores it.
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// The slot was empty: undo removes what this op added.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// Nothing to restore; reverse is a no-op removal.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
// Overwrote an existing entry: undo restores it.
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
None => RegistryDelta::RemoveResource {
id,
snapshot: ResourceEntry::default(),
},
},
&RegistryDelta::RemoveResource { id, .. } => {
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
RegistryDelta::AddResource { id, entry: snapshot }
}
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
})
/// The newest write the slot carries, its attributes included.
fn slot_newest(slot: &InputSlot) -> TimeStamp {
slot.attributes
.values()
.map(|value| value.timestamp)
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
}
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
/// edit the index is out of bounds.
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
if index >= node.inputs.len() {
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
return Err(CrdtError::InputIndexOutOfBounds(index));
}
if at <= node.inputs_timestamp {
return Ok(None);
}
let shape = node.inputs_timestamp;
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(node.inputs.get_mut(index))
}
/// The entity's content wherever it sits: live, or held by its tombstone.
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
}
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
/// whatever its presence.
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
let mark = dead.remove(&id).expect("checked above");
live.insert(id, mark.content);
}
}
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
// The placeholder holds only early writes: they land on the real content as if the addition came first.
let early = std::mem::replace(&mut mark.content, content);
mark.content.merge(early);
mark.placeholder = false;
} else if let Some(existing) = content_mut(live, dead, id) {
existing.merge(content);
} else {
live.insert(id, content);
}
settle(live, dead, id);
}
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
/// unless a newer removal holds it dead.
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
content.stamp_all(at);
fold(live, dead, id, content);
}
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
/// it arrives.
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
fold(live, dead, id, snapshot);
if let Some(mark) = dead.get_mut(&id) {
mark.at = mark.at.max(at);
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
let content = live.remove(&id).expect("checked above");
dead.insert(id, Tombstone { content, at, placeholder: false });
}
}
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
fn write<K: Hash + Eq + Copy, T: Presence>(
live: &mut HashMap<K, T>,
dead: &mut HashMap<K, Tombstone<T>>,
id: K,
at: TimeStamp,
mode: ApplyMode,
missing: impl FnOnce() -> CrdtError,
write: impl FnOnce(&mut T) -> Result<(), CrdtError>,
) -> Result<(), CrdtError> {
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
if unseen {
if mode == ApplyMode::Live {
return Err(missing());
}
dead.insert(
id,
Tombstone {
content: T::placeholder(),
at: TimeStamp::ORIGIN,
placeholder: true,
},
);
}
let content = content_mut(live, dead, id).expect("held above");
if let Err(error) = write(content) {
// A rejected op changes nothing, so the placeholder made for it goes too.
if unseen {
dead.remove(&id);
}
return Err(error);
}
content.set_presence(content.presence().max(at));
settle(live, dead, id);
Ok(())
}
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
match ids.iter().find(unseen) {
Some(&id) if mode == ApplyMode::Live => Err(CrdtError::TargetNodeDoesNotExist(id)),
_ => Ok(()),
}
}
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
}
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
}
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
registry.resources.insert(
id,
ResourceEntry {
presence: at,
..ResourceEntry::default()
},
);
}
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
f(entry);
entry.set_presence(entry.presence().max(at));
settle(&mut registry.resources, &mut registry.removed_resources, id);
}
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
@@ -455,13 +684,12 @@ pub(crate) enum RegistryTarget {
Snapshot,
}
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
/// How [`Document::apply_op_with`] treats what it finds.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApplyMode {
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
/// edit cannot mean either.
Live,
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
Idempotent,
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
Force,
}
+66 -43
View File
@@ -10,9 +10,12 @@ use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
use crate::{
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
ValueError, from_value, to_value,
};
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
@@ -40,7 +43,7 @@ impl NodePath {
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -52,7 +55,7 @@ impl NodePath {
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
let bytes = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -128,18 +131,18 @@ pub struct RuntimeConversion {
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
/// Paired with [`decode_declaration`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
let value = to_value(proto).map_err(|error| error.to_string())?;
postcard::to_stdvec(&value).map_err(|error| error.to_string())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
serde_json::from_value(value).map_err(|error| error.to_string())
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
from_value(&value).map_err(|error| error.to_string())
}
impl Registry {
@@ -189,7 +192,7 @@ impl Registry {
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
/// stored type-erased as [`Value`] so its on-disk shape can migrate freely. All
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
for id in resources.ids() {
@@ -217,12 +220,14 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -317,7 +322,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -333,10 +338,18 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -414,6 +427,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -446,9 +460,14 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -465,11 +484,7 @@ pub fn encode_context_features(context_features: &ContextDependencies) -> Result
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
@@ -517,14 +532,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, serde_json::Value::Bool(true), timestamp);
attributes.set(key, Value::Bool(true), timestamp);
}
}
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
&& !name.is_empty()
{
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
@@ -542,20 +557,25 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
node_network: &NodeNetwork,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
let Some(metadata) = ids.metadata else { return Ok(()) };
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
let pinned_order = metadata.pinned_order(network_path);
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
// what a peer converting the same input produces.
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
@@ -578,7 +598,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
if let Some(value) = value.filter(|s| !s.is_empty()) {
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
attributes.set(key, Value::Str(value.to_string()), timestamp);
}
};
@@ -600,7 +620,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
@@ -781,7 +801,7 @@ impl<'m> ScopedConversion<'m> {
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
@@ -804,18 +824,18 @@ impl<'m> ScopedConversion<'m> {
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(
&mut attributes,
self.ctx.metadata,
local_path,
owner_path.as_ref(),
network_id,
self.ctx.ids(local_path),
TimeStamp::ORIGIN,
)?;
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
}
@@ -838,7 +858,10 @@ pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId>
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
[(key, id)] if key == "Resource" => from_value(id).ok(),
_ => None,
},
_ => None,
}
}
@@ -850,8 +873,8 @@ mod resource_ref_shape {
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+43 -62
View File
@@ -3,21 +3,26 @@
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +32,9 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
history
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -39,6 +45,11 @@ impl History {
self.index.contains_key(&rev)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -51,10 +62,22 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -64,66 +87,24 @@ impl History {
self.deltas.iter()
}
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in &self.deltas {
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
pending_parents.insert(delta.id, in_history_parents);
for parent in delta.all_parents() {
if self.index.contains_key(&parent) {
children.entry(parent).or_default().push(delta.id);
}
}
}
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
order.push(rev);
for child in children.get(&rev).into_iter().flatten() {
let count = pending_parents.get_mut(child).expect("child is in history");
*count -= 1;
if *count == 0 {
ready.push(std::cmp::Reverse(*child));
}
}
}
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
self.index.clear();
for (position, rev) in order.iter().enumerate() {
if let Some(delta) = by_rev.remove(rev) {
self.index.insert(*rev, position);
self.deltas.push(delta);
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if seen.insert(rev)
&& let Some(delta) = self.get(rev)
{
stack.extend(delta.all_parents());
}
}
seen
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
@@ -142,7 +123,7 @@ impl History {
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
+4 -2
View File
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
@@ -119,9 +121,9 @@ pub(crate) fn compute_rev(parent: Option<Rev>, author: PeerId, timestamp: TimeSt
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
parents.sort_unstable();
parents.dedup();
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
}
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
};
hasher.update(&bytes);
let digest = hasher.finalize();
+5
View File
@@ -7,9 +7,11 @@ pub mod document;
pub mod history;
pub mod ids;
pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod session;
pub mod value;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -24,9 +26,11 @@ pub use document::*;
pub use history::History;
pub use ids::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use value::{Value, ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -40,6 +44,7 @@ pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod round_trip;
}
@@ -8,6 +8,8 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
use crate::Value;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
#[derive(Clone, Debug, PartialEq)]
@@ -52,11 +54,11 @@ pub struct InputMetadataEntry {
pub input_description: Option<String>,
pub widget_override: Option<String>,
/// Reassembled from `ui::input_data::<sub_key>` attributes.
pub input_data: HashMap<String, serde_json::Value>,
pub input_data: HashMap<String, Value>,
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
None
@@ -88,7 +90,7 @@ pub trait NodeMetadataSource {
None
}
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
HashMap::new()
}
+78 -9
View File
@@ -1,12 +1,30 @@
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -43,14 +61,26 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
}
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
}
}
@@ -61,6 +91,26 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: Value::Str("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -70,7 +120,7 @@ pub enum NodeInput {
index: u32,
},
Value {
value: serde_json::Value,
value: Value,
exposed: bool,
},
Scope(Cow<'static, str>),
@@ -92,10 +142,16 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
@@ -120,7 +176,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -154,6 +210,19 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+304
View File
@@ -0,0 +1,304 @@
use crate::{
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
Tombstone,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::hash::Hash;
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
/// applied as an op.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
/// tombstone behind.
Node {
id: NodeId,
live: Option<Node>,
removed: Option<Tombstone<Node>>,
},
Network {
id: NetworkId,
live: Option<Network>,
removed: Option<Tombstone<Network>>,
},
Resource {
id: ResourceId,
live: Option<ResourceEntry>,
removed: Option<Tombstone<ResourceEntry>>,
},
/// One field of a live node, and the node's presence, which every write moves.
NodeField {
id: NodeId,
presence: TimeStamp,
field: NodeField,
},
/// One field of a live network, and its presence.
NetworkField {
id: NetworkId,
presence: TimeStamp,
field: NetworkField,
},
DocumentAttribute {
key: String,
previous: Option<AttributeValue>,
},
PeerUser {
peer: PeerId,
previous: Option<PeerRegistration>,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
/// Only the presence moved, by a reference from another entity's op.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Input {
index: u32,
previous: InputSlot,
},
InputAttribute {
index: u32,
key: String,
previous: Option<AttributeValue>,
},
Inputs {
previous: Vec<InputSlot>,
inputs_timestamp: TimeStamp,
},
Implementation {
previous: Implementation,
implementation_timestamp: TimeStamp,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
/// Only the presence moved, by a node added to or implemented by it.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Exports {
previous: Vec<ExportSlot>,
},
}
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
let mut priors = Vec::new();
let node_input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => Some(*id),
_ => None,
};
match op {
RegistryDelta::AddNode { id, node } => {
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
priors.push(whole_node(registry, *id));
}
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
RegistryDelta::SetNodeInputs { id, inputs } => {
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
}));
priors.extend(
inputs
.iter()
.filter_map(|slot| node_input(&slot.input))
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
);
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::Input {
index: *index,
previous: slot.clone(),
})
}));
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
if let Implementation::Network(network) = implementation {
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
}
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
previous: node.implementation.clone(),
implementation_timestamp: node.implementation_timestamp,
}));
}
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
key: delta.key.clone(),
previous: node.attributes.get(&delta.key).cloned(),
})),
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::InputAttribute {
index: *index,
key: delta.key.clone(),
previous: slot.attributes.get(&delta.key).cloned(),
})
})),
RegistryDelta::SetNetworkExport { id, export, .. } => {
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
key: delta.key.clone(),
previous: network.attributes.get(&delta.key).cloned(),
}));
}
RegistryDelta::AddResource { id, .. }
| RegistryDelta::RemoveResource { id, .. }
| RegistryDelta::SetResourceHash { id, .. }
| RegistryDelta::AddSource { id, .. }
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
id: *id,
live: registry.resources.get(id).cloned(),
removed: registry.removed_resources.get(id).cloned(),
}),
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
peer: *peer,
previous: registry.peer_users.get(peer).copied(),
}),
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
key: delta.key.clone(),
previous: registry.attributes.get(&delta.key).cloned(),
}),
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
priors
}
/// Puts back what `priors` recorded, newest write first.
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
for prior in priors.iter().rev() {
match prior {
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
Prior::NodeField { id, presence, field } => {
let Some(node) = registry.node_instances.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
continue;
};
node.presence = *presence;
match field {
NodeField::Presence => {}
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
NodeField::Input { index, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
*slot = previous.clone();
}
}
NodeField::InputAttribute { index, key, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
put_attribute(&mut slot.attributes, key, previous.as_ref());
}
}
NodeField::Inputs { previous, inputs_timestamp } => {
node.inputs = previous.clone();
node.inputs_timestamp = *inputs_timestamp;
}
NodeField::Implementation { previous, implementation_timestamp } => {
node.implementation = previous.clone();
node.implementation_timestamp = *implementation_timestamp;
}
}
}
Prior::NetworkField { id, presence, field } => {
let Some(network) = registry.networks.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
continue;
};
network.presence = *presence;
match field {
NetworkField::Presence => {}
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
NetworkField::Exports { previous } => network.exports = previous.clone(),
}
}
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
Prior::PeerUser { peer, previous } => match previous {
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
None => _ = registry.peer_users.remove(peer),
},
}
}
}
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
Prior::Node {
id,
live: registry.node_instances.get(&id).cloned(),
removed: registry.removed_nodes.get(&id).cloned(),
}
}
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
Prior::Network {
id,
live: registry.networks.get(&id).cloned(),
removed: registry.removed_networks.get(&id).cloned(),
}
}
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
/// whole entity.
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
match registry.node_instances.get(&id) {
Some(node) => Prior::NodeField {
id,
presence: node.presence,
field: field(node),
},
None => whole_node(registry, id),
}
}
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
match registry.networks.get(&id) {
Some(network) => Prior::NetworkField {
id,
presence: network.presence,
field: field(network),
},
None => whole_network(registry, id),
}
}
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
match node.inputs.get(index as usize) {
Some(slot) => field(slot),
None => NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
},
}
}
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
match was_live {
Some(content) => _ = live.insert(id, content.clone()),
None => _ = live.remove(&id),
}
match was_removed {
Some(mark) => _ = dead.insert(id, mark.clone()),
None => _ = dead.remove(&id),
}
}
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
match previous {
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
None => _ = attributes.remove(key),
}
}
+56 -8
View File
@@ -1,7 +1,13 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
/// entity from it. The live maps hold only what exists.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -9,13 +15,55 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
/// the peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
/// ops against the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -85,10 +133,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.len() != b.len() {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
return false;
}
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -100,8 +148,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+135 -68
View File
@@ -1,4 +1,4 @@
use crate::{PeerId, TimeStamp};
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -11,13 +11,28 @@ pub struct SourceKey {
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: serde_json::Value,
pub source: Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
/// readers see it as absent.
#[serde(default)]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: Value::None,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -26,8 +41,13 @@ pub struct SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
/// deleted as of then, as with [`Attributes`](crate::Attributes).
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -39,12 +59,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self { sources, hash, hash_timestamp })
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
@@ -66,82 +102,107 @@ impl ResourceEntry {
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
/// The bytes themselves are persisted separately by the caller's byte store.
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The source body and timestamp stored under `key`, if any.
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
/// The live sources in precedence order, tombstones skipped.
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.find(&key) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.find(&key) {
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
_ => {}
}
_ => false,
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
}
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) => {
self.sources.remove(index);
true
}
_ => false,
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.sources.iter().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
)
})
self.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
}
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -225,15 +286,15 @@ mod tests {
}
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
/// than silently producing an unsound map key. MessagePack (the storage format) can carry a
/// than silently producing an unsound map key. Postcard (the storage format) can carry a
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
#[test]
fn priority_deserialize_validates_finiteness() {
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
}
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
@@ -248,20 +309,23 @@ mod tests {
peer: PeerId(1),
},
SourceValue {
source: serde_json::json!(priority),
source: Value::Float(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
let unsorted = serde_json::json!({
"sources": [source(2.), source(0.), source(1.)],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
let unsorted = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![source(2.), source(0.), source(1.)],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
}
@@ -278,20 +342,23 @@ mod tests {
(
key,
SourceValue {
source: serde_json::json!(body),
source: Value::Str(body.into()),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
let with_duplicates = serde_json::json!({
"sources": [entry(5, "newer"), entry(1, "older")],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let with_duplicates = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![entry(5, "newer"), entry(1, "older")],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
}
}
+306 -153
View File
@@ -2,7 +2,9 @@
use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use crate::{
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -27,22 +29,17 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
/// a working copy wants [`with_identity`](Self::with_identity).
pub fn with_peer(peer: PeerId) -> Self {
Self::with_identity(peer, UserId(peer.0))
}
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
/// and what undo and history authorship scope by.
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
Self {
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
},
document: Document::empty(peer, user),
remote_tips: HashMap::new(),
}
}
@@ -51,6 +48,22 @@ impl Session {
self.document.peer
}
pub fn user(&self) -> UserId {
self.document.user
}
/// The person a peer is registered to, if its registration has landed here.
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)
}
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
pub fn is_mine(&self, peer: PeerId) -> bool {
self.user_of(peer) == Some(self.document.user)
}
pub fn registry(&self) -> &Registry {
&self.document.working_registry
}
@@ -104,7 +117,7 @@ impl Session {
/// Used on a throwaway session clone at export time so the exported registry and history agree;
/// callers must guarantee the bytes are available in the export's resource store.
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let mut ops = Vec::new();
for id in ids {
@@ -140,25 +153,45 @@ impl Session {
///
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
/// `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 — registration rides a real edit.
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
/// 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> {
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
return Ok(Vec::new());
}
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
let user = UserId(self.document.peer.0);
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
let (peer, user) = (self.document.peer, self.document.user);
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
}
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
return Err(CrdtError::SequencesExhausted);
}
let sequence_before = self.document.last_hot_sequence;
let mut staged = Vec::with_capacity(pending.len());
for op in pending {
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence,
};
self.document.apply_hot_op(hot_op.clone())?;
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
// The run continues where it was, so no sequence goes unused.
self.document.last_hot_sequence = sequence_before;
if !staged.is_empty() {
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
self.document.resync_hot_timestamps();
self.document.rebuild_working();
}
return Err(error);
}
self.document.last_hot_sequence = sequence;
staged.push(hot_op);
}
Ok(staged)
@@ -166,19 +199,26 @@ impl Session {
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
///
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
/// equal the snapshot when there are none), so it is left untouched.
///
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
/// applied hot op) so duplicate structural inserts no-op rather than error.
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
}
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
/// retirement passes the op's own.
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
let target = RegistryTarget::Snapshot;
let ops = ops.into_iter();
let mut produced = Vec::with_capacity(ops.size_hint().0);
for op in ops {
for (op, authored_at) in ops {
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
@@ -186,10 +226,10 @@ impl Session {
self.document.redo_stack.clear();
}
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
let author = self.document.peer;
let author = timestamp.peer;
let delta = Delta::new(parent, author, timestamp, op, reverse);
let rev = delta.id;
@@ -213,7 +253,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -226,13 +266,11 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
}
@@ -240,8 +278,8 @@ impl Session {
/// Rebuild the registry from scratch by applying every delta in causal order.
/// `deltas` must be in causal order (every parent before its children).
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_peer(peer);
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -256,9 +294,21 @@ impl Session {
Ok(session)
}
/// Apply a hot op without going through the broadcast stream.
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
/// delivery must not put a retired op back in the hot log.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.apply_hot_op(hot_op)
self.document.replay_hot_op(hot_op)
}
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
pub fn settled_marks(&self) -> &SettledHotOps {
&self.document.settled
}
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
/// dropped, and the working registry re-derived without it.
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
self.document.absorb_settled(remote);
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -267,57 +317,52 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
/// deltas must arrive in causal order.
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
let mut absorbed: Vec<Delta> = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed.push(delta);
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
/// Folded over `head`'s ancestry only: an undone delta stays in the DAG for redo to find, and folding
/// all of history would restore work the user undid.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
let reachable = self.document.history.ancestors(self.document.head);
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
}
if absorbed.is_empty() {
return Ok(None);
}
self.document.history.merge(absorbed);
let tips = self.document.history.tips();
let timestamp = self.document.clock.tick();
let merge = Delta::merge(tips, self.document.peer, timestamp);
let merge_rev = merge.id;
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
// order without re-sorting the whole history.
self.document.history.push(merge);
self.document.head = Some(merge_rev);
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(Some(merge_rev))
Ok(scratch.working_registry)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
pub fn history_len(&self) -> usize {
self.document.history.len()
}
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
/// since a lagging op can arrive below the cutoff afterwards.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
/// authored at. Markers commit nothing. Ops not in the log are ignored.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
drained.push(hot_op);
} else {
remaining.push(hot_op);
}
}
self.document.hot_log = remaining;
/// One retired delta per hot op.
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
self.document.hot_log = kept;
self.document.resync_hot_timestamps();
self.document.settled.extend(drained.iter().map(HotOp::id));
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
let ops = drained
.into_iter()
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
self.commit_ops_authored_at(ops, true)
}
/// Promote every hot op stamped at or before `up_to`, whatever its author.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let ids = self.hot_ops_up_to(up_to);
self.retire_hot_ops(&ids)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
pub fn mark_interaction_end(&mut self, rev: Rev) {
@@ -328,38 +373,36 @@ impl Session {
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
let timestamp = self.document.clock.tick();
self.document.history.annotate(rev, key, value, timestamp)
}
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
///
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
/// interaction is not undoable, as opening a document starts with an empty undo history.
pub fn can_undo(&self) -> bool {
let Some(head) = self.document.head else { return false };
if self.document.last_broadcast_rev == Some(head) {
return false;
}
self.interaction_start_parent(head).is_some()
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
}
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
/// stop when the parent is an `interaction_end` boundary or the root.
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
let mut current = rev;
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
let history = &self.document.history;
let mut current = history.get(end)?;
let user = self.user_of(current.author);
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
return None;
}
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
loop {
let parent = self.document.history.get(current)?.parent?;
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
return Some(parent);
if silent && self.document.last_broadcast_rev == Some(current.id) {
return None;
}
let parent = history.get(current.parent?)?;
if boundary(parent) {
return Some(parent.id);
}
current = parent;
}
@@ -369,37 +412,22 @@ impl Session {
!self.document.redo_stack.is_empty()
}
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
if !self.can_undo() {
return Err(CrdtError::NothingToUndo);
}
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
// interaction's boundary (its `interaction_end` delta) or the root.
loop {
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta)?;
self.document.head = parent;
match parent {
None => break,
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
Some(_) => {}
}
self.document.revert_delta(&delta);
self.document.head = delta.parent;
}
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
// working registry (the next interaction's reverses are computed against it).
self.document.retired_snapshot = self.document.working_registry.clone();
// With ops hot, working is the rewound snapshot plus them.
if !self.document.hot_log.is_empty() {
self.document.rebuild_working();
}
self.document.redo_stack.push(checkpoint);
Ok(checkpoint)
}
@@ -419,23 +447,28 @@ impl Session {
forward.push(delta);
}
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
// at the same timestamp. Symmetric with `revert_delta`.
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
// them in again, a newer write merged in before them still winning over theirs.
let hot = !self.document.hot_log.is_empty();
for delta in forward.into_iter().rev() {
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
if !hot {
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
}
}
if hot {
self.document.rebuild_working();
}
self.document.head = Some(checkpoint);
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(checkpoint)
}
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_peer(peer);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
@@ -466,15 +499,7 @@ impl Session {
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
_ => {}
}
}
hashes.extend(self.document.history.resource_hashes());
hashes
}
@@ -540,7 +565,7 @@ impl Session {
}
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
/// test can observe a failure (e.g. `NotFoundInHistory`).
#[cfg(test)]
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
self.commit_ops(std::iter::once(op), false).map(|_| ())
@@ -553,6 +578,29 @@ impl Session {
pub fn next_node_counter(&self) -> u64 {
self.document.next_node_counter
}
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
/// sequence is spent twice.
pub fn last_hot_sequence(&self) -> HotSequence {
self.document.last_hot_sequence
}
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
/// the hot log carries any more.
pub fn clock_counter(&self) -> u64 {
self.document.clock.counter
}
/// Continue the Lamport clock after a load. Raises only, like observing an op.
pub fn restore_clock(&mut self, counter: u64) {
self.document.clock.counter = self.document.clock.counter.max(counter);
}
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
/// replaying a persisted hot log afterwards cannot lower it.
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
}
}
/// Errors from `Session::commit_from_runtime`.
@@ -578,10 +626,122 @@ impl Default for Session {
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
pub sequence: HotSequence,
}
impl HotOp {
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
pub fn id(&self) -> HotOpId {
HotOpId {
peer: self.timestamp.peer,
sequence: self.sequence,
}
}
}
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
impl HotSequence {
/// Before this author has written anything, covering no op.
pub const NONE: Self = Self(0);
/// The position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
pub fn next(self) -> Self {
Self(self.0.saturating_add(1))
}
}
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
/// receiver which prefix history covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: HotSequence,
}
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
/// late copy of a settled op is dropped wherever it lands.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettledHotOps {
pub settled_up_to: HashMap<PeerId, HotSequence>,
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
/// Sort and coalesce runs, joining any that touch or abut.
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
runs.sort_unstable();
runs.dedup_by(|(start, end), (_, last_end)| {
let joins = *start <= last_end.next();
if joins {
*last_end = (*last_end).max(*end);
}
joins
});
}
impl SettledHotOps {
/// Whether history already holds this hot op.
pub fn covers(&self, id: HotOpId) -> bool {
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|| self
.settled_beyond
.get(&id.peer)
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
}
/// Take on `remote`'s coverage as well as this one's.
pub(crate) fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.settled_up_to {
let through = self.settled_up_to.entry(peer).or_default();
*through = (*through).max(remote_through);
}
for (&peer, runs) in &remote.settled_beyond {
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
}
self.compact();
}
/// Record newly settled ops.
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
for id in retired {
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
}
self.compact();
}
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
fn compact(&mut self) {
for (&peer, runs) in &mut self.settled_beyond {
coalesce(runs);
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
let joined = runs.iter().take_while(|&&(start, end)| {
let joins = start <= through.next();
if joins {
through = through.max(end);
}
joins
});
let joined = joined.count();
runs.drain(..joined);
if through != HotSequence::NONE {
self.settled_up_to.insert(peer, through);
}
}
self.settled_beyond.retain(|_, runs| !runs.is_empty());
}
}
#[derive(Debug, thiserror::Error)]
pub enum CrdtError {
#[error("This peer has authored every hot op sequence there is")]
SequencesExhausted,
#[error("Target node {0} does not exist")]
TargetNodeDoesNotExist(NodeId),
#[error("Network {0} does not exist")]
@@ -592,10 +752,6 @@ pub enum CrdtError {
ExportSlotOutOfBounds(u32),
#[error("Delta {0} not found in history")]
NotFoundInHistory(Rev),
#[error("No history entry resurrects node {0}")]
NodeNotInHistory(NodeId),
#[error("No history entry resurrects network {0}")]
NetworkNotInHistory(NetworkId),
#[error("Nothing to undo")]
NothingToUndo,
#[error("Nothing to redo")]
@@ -604,9 +760,6 @@ pub enum CrdtError {
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
NetworkAlreadyExists(NetworkId),
/// PeerId is already registered to a different UserId.
#[error("Peer {0:?} is already registered to a different user")]
PeerRegistrationConflict(PeerId),
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
@@ -0,0 +1,165 @@
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(Value::from(serde_json::json!(value))),
},
}
}
pub(super) fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
/// the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
// are the authors' clocks.
let hot = |op, counter, peer| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
sequence: crate::HotSequence(1),
};
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
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: the next batch registers again, and the newer registration wins.
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));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut other = Session::with_peer(PeerId(2));
for delta in device.cloned_deltas().into_iter().rev() {
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
}
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_batch_past_the_last_sequence_is_refused_whole() {
let mut session = Session::with_peer(PeerId(1));
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
assert!(session.hot_log().is_empty());
}
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
#[test]
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
let op = crate::HotOp {
op: set_attribute("k", 1),
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let mut host = Session::with_peer(PeerId(1));
host.apply_hot_op(op.clone()).unwrap();
host.retire(op.timestamp).unwrap();
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
reopened.absorb_settled_marks(host.settled_marks());
reopened.apply_hot_op(op.clone()).unwrap();
assert!(reopened.hot_log().is_empty());
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
assert_eq!(reopened.history_len(), host.history_len());
}
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
/// registry stays the snapshot plus the hot log.
#[test]
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
let mut s = Session::with_peer(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
s.stage_ops([
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
},
RegistryDelta::AddNode { id: NodeId(1), node },
])
.unwrap();
let before = s.registry().clone();
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
}]);
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
}
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
/// or sent.
#[test]
fn a_refused_batch_stages_nothing() {
let mut s = Session::with_peer(PeerId(1));
s.stage_ops([RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
}])
.unwrap();
let hot_before = s.hot_log().len();
let refused = s.stage_ops([
set_attribute("lands", 1),
RegistryDelta::ChangeNodeInput {
id: NodeId(404),
index: 0,
new_input: NodeInput::Value {
value: Value::from(serde_json::json!(1)),
exposed: false,
},
},
]);
assert!(refused.is_err());
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
}
#[test]
fn settled_marks_round_trip_through_json() {
let mut marks = crate::SettledHotOps::default();
let id = |peer: u64, sequence: u64| HotOpId {
peer: PeerId(peer),
sequence: crate::HotSequence(sequence),
};
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
let json = serde_json::to_string(&marks).unwrap();
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
}
File diff suppressed because it is too large. Load diff
+19 -10
View File
@@ -7,7 +7,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
use graph_craft::graphene_compiler::Compiler;
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
/// Helper function to verify a NodeNetwork can be compiled successfully.
/// Note: This only works for complete networks with all inputs resolved.
@@ -530,7 +530,7 @@ fn resources_round_trip_through_from_runtime() {
assert_eq!(entry.sources.len(), 2, "both sources carried through");
// The chain iterates in priority order; decode bodies back to DataSource to compare.
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).expect("source body decodes")).collect();
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
// All source keys carry the document peer.
@@ -609,10 +609,9 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
}
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
/// 17-significant-digit mantissa.
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored
/// type-erased as a `Value`, so this guards against any precision loss in the f64
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
#[test]
fn node_input_f64_round_trips_bit_exact() {
use graph_craft::document::value::TaggedValue;
@@ -623,7 +622,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -640,8 +639,8 @@ fn node_input_f64_round_trips_bit_exact() {
let NodeInput::Value { tagged_value, .. } = input else {
panic!("expected a value input, got {input:?}")
};
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
let TaggedValue::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -659,7 +658,7 @@ fn duplicate_runtime_node_id_is_rejected() {
// 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, serde_json::json!(7), TimeStamp::ORIGIN);
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");
@@ -758,18 +757,28 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+38 -31
View File
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -38,7 +38,8 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
/// 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)?;
Ok((network, node_entries))
@@ -50,19 +51,7 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
let context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -74,15 +63,15 @@ impl Registry {
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
/// sorted by key) with bodies decoded from their type-erased `serde_json::Value` form back to
/// sorted by key) with bodies decoded from their type-erased `Value` form back to
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
/// `from_runtime`.
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in &entry.sources {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
if let Some(hash) = entry.hash {
@@ -103,6 +92,26 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
/// lands it under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -165,7 +174,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
@@ -173,8 +182,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -231,8 +240,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
})
.collect()
}
@@ -270,8 +278,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
@@ -291,8 +298,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -334,7 +340,9 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
// never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -345,14 +353,13 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: RuntimeNodeId(local_id),
node_id: runtime_node_id(*node_id, referenced),
output_index: *output_index as usize,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
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,
+265
View File
@@ -0,0 +1,265 @@
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
}
pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
serde_json::from_value(value.clone().into()).map_err(ValueError)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
use serde_json::Value as Json;
match value {
Json::Null => Value::None,
Json::Bool(boolean) => Value::Bool(boolean),
Json::Number(number) => {
if let Some(int) = number.as_i64() {
Value::Int(int.into())
} else if let Some(int) = number.as_u64() {
Value::Int(int.into())
} else {
Value::Float(number.as_f64().unwrap_or(f64::NAN))
}
}
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()),
}
}
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
use serde_json::Value as Json;
match value {
Value::None => Json::Null,
Value::Bool(boolean) => Json::Bool(boolean),
Value::Int(int) => match (i64::try_from(int), u64::try_from(int)) {
(Ok(int), _) => int.into(),
(_, Ok(int)) => int.into(),
(Err(_), Err(_)) => (int as f64).into(),
},
Value::Float(float) => float.into(),
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()),
}
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_postcard() {
let value = serde_json::json!({
"null": null,
"bools": [true, false],
"ints": [0, -1, i64::MIN, u64::MAX],
"floats": [1.5, -0.25, 1e300],
"str": "text",
"empty": { "array": [], "object": {} },
"nested": { "b": [{ "c": 1 }], "a": "z" },
});
let bytes = postcard::to_stdvec(&Value::from(value.clone())).unwrap();
let decoded: Value = postcard::from_bytes(&bytes).unwrap();
assert_eq!(serde_json::Value::from(decoded), value);
}
#[test]
fn round_trips_through_json_untagged() {
let json = serde_json::json!({ "a": [1, -2, 2.5, "s", null, true], "b": {}, "c": [] });
let value = Value::from(json.clone());
let text = serde_json::to_string(&value).unwrap();
assert_eq!(text, serde_json::to_string(&json).unwrap());
assert_eq!(serde_json::to_value(&value).unwrap(), json);
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value);
}
#[test]
fn json_object_keys_sort_and_last_duplicate_wins() {
let value: Value = serde_json::from_str(r#"{"b": 1, "a": 2, "b": 3}"#).unwrap();
assert_eq!(value, Value::Object(vec![("a".into(), Value::Int(2)), ("b".into(), Value::Int(3))]));
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Sample {
Unit,
Newtype(u8),
Tuple(i64, String),
Struct { flag: bool, nested: Option<Box<Sample>> },
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
samples: Vec<Sample>,
by_id: std::collections::BTreeMap<u32, f64>,
bytes: Vec<u8>,
letter: char,
unit: (),
big: u64,
}
fn record() -> Record {
Record {
samples: vec![
Sample::Unit,
Sample::Newtype(7),
Sample::Tuple(-3, "t".into()),
Sample::Struct {
flag: true,
nested: Some(Box::new(Sample::Unit)),
},
Sample::Struct { flag: false, nested: None },
],
by_id: [(2, 0.5), (10, -1.)].into(),
bytes: vec![0, 255],
letter: 'x',
unit: (),
big: u64::MAX,
}
}
#[test]
fn from_value_round_trips_serde_types() {
assert_eq!(from_value::<Record>(&to_value(&record()).unwrap()).unwrap(), record());
}
#[test]
fn number_variants_map_to_serde_json_numbers() {
let json = |value: Value| serde_json::Value::from(value);
assert_eq!(json(Value::Int(u64::MAX.into())), serde_json::json!(u64::MAX));
assert_eq!(json(Value::Int(-1)), serde_json::json!(-1));
assert_eq!(json(Value::Int(i128::MAX)), serde_json::json!(i128::MAX as f64));
assert_eq!(json(Value::Float(2.)), serde_json::json!(2.));
assert_eq!(Value::from(serde_json::json!(2.)), Value::Float(2.));
assert_eq!(Value::from(serde_json::json!(2)), Value::Int(2));
}
#[test]
fn postcard_tags_follow_declaration_order() {
let encode = |value: Value| postcard::to_stdvec(&value).unwrap();
assert_eq!(encode(Value::None), [0]);
assert_eq!(encode(Value::Bool(true)), [1, 1]);
assert_eq!(encode(Value::Int(-1)), [2, 1]);
assert_eq!(encode(Value::Float(0.)), [3, 0, 0, 0, 0, 0, 0, 0, 0]);
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]);
}
}
+6
View File
@@ -4,9 +4,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
+2 -2
View File
@@ -14,14 +14,14 @@ impl Editor {
environment: Environment,
uuid_random_seed: u64,
resource_storage: Arc<dyn ResourceStorage>,
working_copy_root: Option<std::path::PathBuf>,
document_store: Arc<dyn document_container::store::DocumentStore>,
mut application_io: PlatformApplicationIo,
wake: Wake,
) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
+4
View File
@@ -193,5 +193,9 @@ pub const UI_SCALE_DEFAULT: f64 = 1.;
pub const UI_SCALE_MIN: f64 = 0.5;
pub const UI_SCALE_MAX: f64 = 3.;
// DIALOGS
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
// ACTIONS
pub const BLEND_COUNT_PER_LAYER: usize = 10;
+6 -3
View File
@@ -89,16 +89,19 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
let mut s = Self::new(
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
Arc::new(document_container::store::MemoryStore::default()),
);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
+2
View File
@@ -19,3 +19,5 @@ pub mod node_graph_executor;
pub mod test_utils;
pub mod utility_traits;
pub mod utility_types;
pub use document_container::store as document_store;
@@ -1,6 +1,10 @@
use crate::consts::{MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG, MAX_UNSAVED_DOCUMENTS_IN_DIALOG};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use std::borrow::Cow;
use std::fmt::Write;
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
pub struct CloseAllDocumentsDialog {
pub unsaved_document_names: Vec<String>,
@@ -30,7 +34,26 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
impl LayoutHolder for CloseAllDocumentsDialog {
fn layout(&self) -> Layout {
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
let mut unsaved_list = "• ".to_string()
+ &self
.unsaved_document_names
.iter()
.take(MAX_UNSAVED_DOCUMENTS_IN_DIALOG)
.map(|name| {
if name.chars().count() > MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG {
Cow::Owned(name.chars().take(MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG).chain(std::iter::once('…')).collect())
} else {
Cow::Borrowed(name.as_str())
}
})
.collect::<Vec<_>>()
.join("\n• ");
let remaining = self.unsaved_document_names.len().saturating_sub(MAX_UNSAVED_DOCUMENTS_IN_DIALOG);
if remaining > 0 {
let s = if remaining == 1 { "" } else { "s" };
let _ = write!(unsaved_list, "\n... and {remaining} more document{s}");
}
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
@@ -118,22 +118,9 @@ pub enum FrontendMessage {
filename: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteState {
state: PersistedState,
},
TriggerPersistenceDeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerSavePreferences {
@@ -1,7 +1,5 @@
use std::path::PathBuf;
use graph_craft::application_io::resource::ResourceHash;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -12,9 +10,6 @@ pub struct DocumentInfo {
pub id: DocumentId,
pub name: String,
#[serde(default)]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
pub resources: Option<Box<[ResourceHash]>>,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
@@ -1,4 +1,5 @@
pub mod layout_widget;
pub mod tooltip_markdown;
pub mod widgets;
pub mod widget_prelude {
@@ -0,0 +1,78 @@
//! Tooltips render a subset of Markdown: `code` spans, fenced code blocks, `**bold**`, and `*italic*`, where a backslash makes a
//! following backslash, asterisk, or backtick literal. Text from outside the editor goes through these so it shows exactly as written.
/// Escapes text so its backslashes, asterisks, and backticks show as themselves rather than as formatting.
pub fn escape_markdown(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
if matches!(character, '\\' | '*' | '`') {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}
/// Wraps text in a code span that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within,
/// and a space pads the text where it would touch the fence or lose its own edge spaces to the span's trimming.
pub fn markdown_code_span(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run + 1);
let touches_fence = text.starts_with('`') || text.ends_with('`');
let loses_edge_spaces = text.starts_with(' ') && text.ends_with(' ') && text.contains(|character| character != ' ');
let padding = if touches_fence || loses_edge_spaces { " " } else { "" };
format!("{fence}{padding}{text}{padding}{fence}")
}
/// Wraps text in a fenced code block that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within.
/// The fences are lines of their own, so the block goes at the start of a line.
pub fn markdown_code_block(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run.max(2) + 1);
format!("{fence}\n{text}\n{fence}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escaped_text_holds_no_formatting() {
assert_eq!(escape_markdown("a*b*c"), "a\\*b\\*c");
assert_eq!(escape_markdown("`code`"), "\\`code\\`");
assert_eq!(escape_markdown("ends with \\"), "ends with \\\\");
assert_eq!(escape_markdown("<b>&amp;</b>"), "<b>&amp;</b>", "HTML is the tooltip's to escape");
}
#[test]
fn code_spans_contain_anything() {
assert_eq!(markdown_code_span("x"), "`x`");
assert_eq!(markdown_code_span("a`b"), "``a`b``");
assert_eq!(markdown_code_span("a``b`"), "``` a``b` ```");
assert_eq!(markdown_code_span("`"), "`` ` ``");
assert_eq!(markdown_code_span(" x "), "` x `");
assert_eq!(markdown_code_span(" "), "` `");
assert_eq!(markdown_code_span("a\\"), "`a\\`", "a backslash is literal inside a span");
assert_eq!(markdown_code_span("**<i>**"), "`**<i>**`");
assert_eq!(markdown_code_span(""), "");
}
#[test]
fn code_blocks_contain_anything() {
assert_eq!(markdown_code_block("x\n^"), "```\nx\n^\n```");
assert_eq!(markdown_code_block("```\n**<i>**"), "````\n```\n**<i>**\n````");
assert_eq!(markdown_code_block("`"), "```\n`\n```");
assert_eq!(markdown_code_block(""), "");
}
}
@@ -1,7 +1,7 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry};
use document_graph_storage::{Declarations, Registry, Value};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
@@ -29,6 +29,12 @@ pub struct DocumentHistory {
/// and extended on each staging, so a cursor rebuild never touches the byte store.
#[derivative(Debug = "ignore")]
declarations: Declarations,
/// Whether the next commit must convert the whole document rather than stage what the store recorded.
///
/// True when the working copy holds no baseline for a batch to apply to, and whenever the runtime has
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
/// part of the distance between the two.
needs_whole_document_stage: bool,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
@@ -95,10 +101,23 @@ impl DocumentHistory {
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
self.storage = Some(storage);
self.declarations = declarations;
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded and so cannot be described by the recorded batch.
pub fn require_whole_document_stage(&mut self) {
self.needs_whole_document_stage = true;
}
/// Detach the `Gdd` working copy, dropping its declaration cache with it.
pub fn clear_storage(&mut self) {
self.storage = None;
self.declarations.clear();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
@@ -113,21 +132,11 @@ impl DocumentHistory {
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>,
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
pub fn stage_snapshot(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, view_settings: BTreeMap<String, Value>, byte_store: &dyn ResourceStorage) {
let needs_whole_document_stage = self.needs_whole_document_stage;
let Some(storage) = self.storage.as_mut() else { return };
// A working copy that does not hold the document yet has no baseline for a batch of changes to apply
// to. Reading that from the working copy rather than from the caller means a path that mounts storage
// and then commits does not have to know which of the two cases it is in.
let staged = match storage.registry().node_instances.is_empty() {
let staged = match needs_whole_document_stage {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
// An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(Declarations::new()),
@@ -140,14 +149,17 @@ impl DocumentHistory {
}),
};
match staged {
Ok(declarations) => self.declarations.extend(declarations),
Ok(declarations) => {
self.declarations.extend(declarations);
self.needs_whole_document_stage = false;
}
Err(error) => {
log::error!("Storage snapshot staging failed: {error}");
return;
}
}
self.persist_view_state(interface, view_settings, legacy_document);
self.persist_view_state(interface, view_settings);
}
/// Converts the whole document and stages the difference from what the working copy holds.
@@ -184,9 +196,8 @@ impl DocumentHistory {
Ok(constructed.declarations.decoded)
}
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
/// dual-write soak validates the new format against.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
/// The parts of a commit that are not the graph: the per-peer and per-network view settings.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, Value>) {
let Some(storage) = self.storage.as_mut() else { return };
let network_view_settings = storage
@@ -203,10 +214,6 @@ impl DocumentHistory {
{
log::error!("Persisting per-network view settings failed: {error}");
}
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
@@ -32,6 +32,7 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_container::AnyContainer;
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
@@ -149,6 +150,10 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// The document's container in the document store. `None` for a document created this session until its store entry opens.
#[serde(skip)]
#[derivative(Debug = "ignore")]
pub(crate) container: Option<AnyContainer>,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -200,6 +205,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
container: None,
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -407,8 +413,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -564,6 +570,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(DocumentMessage::AbortTransaction);
self.node_graph_handler.drag_start = None;
self.node_graph_handler.select_if_not_dragged = None;
self.node_graph_handler.duplicated_in_drag = false;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
@@ -1834,6 +1841,12 @@ impl DocumentMessageHandler {
self.network_interface.validate_output_names(node_id, node, &path);
}
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
// so the next commit converts the whole document rather than staging the batch that follows them.
self.network_interface.discard_deltas();
self.history.require_whole_document_stage();
self.network_interface.load_structure();
}
@@ -2022,11 +2035,22 @@ impl DocumentMessageHandler {
self.history.set_storage(storage, declarations);
}
/// Detach the `Gdd` working copy.
pub fn clear_storage(&mut self) {
self.history.clear_storage();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
pub(crate) fn retire_storage_interaction(&mut self) {
self.history.retire_storage_interaction();
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded.
pub(crate) fn require_whole_document_stage(&mut self) {
self.history.require_whole_document_stage();
}
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
///
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
@@ -2038,20 +2062,19 @@ impl DocumentMessageHandler {
return;
}
let (view_settings, legacy_document) = self.storage_side_channels();
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
/// The per-peer view settings that ride along with either kind of staging.
fn storage_view_settings(&self) -> std::collections::BTreeMap<String, document_graph_storage::Value> {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
let view_settings = DocumentSettings {
DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
overlays_visibility: &self.overlays_visibility_settings,
@@ -2059,17 +2082,15 @@ impl DocumentMessageHandler {
snapping_state: &self.snapping_state,
collapsed: &self.collapsed,
}
.to_view_map();
(view_settings, self.serialize_document())
.to_view_map()
}
/// Restore `view_settings` map into the document.
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>) {
use document_graph_storage::attr::session::doc;
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, serde_json::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| serde_json::from_value(value.clone()).ok())
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| document_graph_storage::from_value(value).ok())
}
if let Some(value) = decode(view_settings, doc::PTZ) {
@@ -2092,11 +2113,15 @@ impl DocumentMessageHandler {
}
}
/// Move the `Gdd` undo/redo cursor and swap in the interface rebuilt from it. `had_oracle` records
/// whether the legacy snapshot already applied, so the rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
/// rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses),
Ok(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
@@ -2419,7 +2444,7 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
@@ -2427,7 +2452,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
@@ -2461,7 +2486,7 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
@@ -2469,7 +2494,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
@@ -2806,7 +2831,7 @@ impl DocumentMessageHandler {
if has_fill && has_stroke {
let (existing_index, new_index) = (0_i64, 1_i64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(existing_index), false))]);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2828,7 +2853,7 @@ impl DocumentMessageHandler {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(new_index), false))]);
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(flow), false)),
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
]);
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::F64(rotation), false),
NodeInput::value(TaggedValue::Number(rotation), false),
&[],
);
network_interface.set_input(
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
@@ -97,7 +97,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::I64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -109,7 +109,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
.expect("Auto-Tangents node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
let auto_tangents_id = NodeId::new();
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
@@ -157,13 +157,13 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.insert_node(shape_id, shape, &[]);
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
if include_stroke {
@@ -175,13 +175,14 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
}
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
// Ensure the transform node occurs after the stroke node.
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
}
}
@@ -193,14 +194,14 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
@@ -526,7 +527,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
false,
);
}
@@ -555,7 +556,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
NodeInput::value(TaggedValue::Number(fill * 100.), false),
false,
);
}
@@ -666,7 +667,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
@@ -690,7 +691,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -865,7 +866,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
@@ -873,11 +874,11 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -3,7 +3,7 @@ mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
mod storage_tests;
pub(crate) mod storage_tests;
pub mod data_panel;
pub mod graph_operation;
@@ -422,7 +422,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
let half_viewport = viewport.center_in_viewport_space().into_dvec2();
let start_offset = viewport_to_document.transform_vector2(self.mouse_position - half_viewport);
let end_offset = viewport_to_document.transform_vector2(ipp.mouse.position - half_viewport);
let angle = start_offset.angle_to(end_offset);
let angle = start_offset.try_angle_to(end_offset).unwrap_or(0.);
tilt_raw_not_snapped + angle
};
@@ -40,17 +40,30 @@ pub struct NodePropertiesContext<'a> {
impl NodePropertiesContext<'_> {
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
if let Some(widget_override) = &input_properties_row.widget_override {
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
} else {
None
}
let metadata = registry::NODE_METADATA.lock().unwrap();
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
match field.widget_override {
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
_ => None,
}
})?;
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
}
}
@@ -348,7 +361,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
@@ -369,14 +382,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::I64(0), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
@@ -425,7 +438,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
@@ -459,14 +472,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
@@ -479,7 +492,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::I64(10), false),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
@@ -811,14 +824,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
@@ -833,7 +846,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::I64(0), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
@@ -1097,6 +1110,11 @@ fn static_input_properties() -> InputProperties {
))])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
@@ -1350,7 +1368,7 @@ fn static_input_properties() -> InputProperties {
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform rotation input override".to_string());
};
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
@@ -1359,7 +1377,7 @@ fn static_input_properties() -> InputProperties {
.range_min(Some(-180.))
.range_max(Some(180.))
.on_update(node_properties::update_value_at_index(
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
node_id,
index,
))
@@ -1447,6 +1465,22 @@ fn static_input_properties() -> InputProperties {
"text_area".to_string(),
Box::new(|node_id, index, context| Ok(vec![LayoutGroup::row(node_properties::text_area_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context)))])),
);
map.insert(
// A math expression, flagged with a warning icon while it fails to parse
"math_expression".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, false))])
}),
);
map.insert(
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
"math_expression_or_reducer".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, true))])
}),
);
map.insert(
"text_font".to_string(),
Box::new(|node_id, index, context| {
@@ -60,6 +60,7 @@ pub enum NodeGraphMessage {
DisconnectInput {
input_connector: InputConnector,
},
DisconnectRootNode,
EnterNestedNetwork,
DuplicateSelectedNodes,
ExposeInput {
@@ -57,6 +57,8 @@ pub struct NodeGraphMessageHandler {
widgets: [LayoutGroup; 2],
/// Used to add a transaction for the first node move when dragging.
begin_dragging: bool,
/// Track if nodes were duplicated during the current drag via Alt-drag.
pub duplicated_in_drag: bool,
/// Used to prevent entering a nested network if the node is dragged after double clicking
node_has_moved_in_drag: bool,
/// If dragging the selected nodes, this stores the starting position both in viewport and node graph coordinates,
@@ -406,20 +408,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::DisconnectInput { input_connector } => {
network_interface.disconnect_input(&input_connector, selection_network_path);
}
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::DuplicateSelectedNodes => {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
// Copy the selected nodes
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
}
NodeGraphMessage::EnterNestedNetwork => {
// Do not enter the nested network if the node was dragged
@@ -796,6 +790,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.drag_start.is_some() {
self.drag_start = None;
self.select_if_not_dragged = None;
self.duplicated_in_drag = false;
responses.add(DocumentMessage::AbortTransaction);
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.selection_before_pointer_down.clone(),
@@ -1041,6 +1036,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.collect::<Vec<_>>();
self.begin_dragging = true;
self.node_has_moved_in_drag = false;
self.duplicated_in_drag = false;
self.update_node_graph_hints(responses);
}
@@ -1096,8 +1092,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting {
// Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
let mut disconnect_root_node = false;
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Update the frontend that the node is disconnected
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
@@ -1158,13 +1164,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.begin_dragging {
self.begin_dragging = false;
if ipp.keyboard.get(Key::Alt as usize) {
responses.add(NodeGraphMessage::DuplicateSelectedNodes);
// Duplicate nodes inline within the existing PointerDown transaction.
// This means a completed Alt-drag is one undo step, and aborting (right-click / Escape)
// rolls back both the duplication and the move with a single plain AbortTransaction.
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
// Duplicating sets a 2x2 offset, so shift the nodes back to the original position
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount {
graph_delta: IVec2::new(-2, -2),
rubber_band: false,
});
self.preview_on_mouse_up = None;
self.duplicated_in_drag = true;
}
}
@@ -1470,6 +1480,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.drag_start = None;
self.begin_dragging = false;
self.duplicated_in_drag = false;
self.box_selection_start = None;
self.wire_in_progress_from_connector = None;
@@ -1516,15 +1527,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Collect the distance to move the shaken nodes after the undo
let graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
if !self.duplicated_in_drag {
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
// Undo to the state of the graph before shaking
responses.add(DocumentMessage::AbortTransaction);
// Undo to the state of the graph before shaking (skip for Alt-drag to avoid removing the duplicates)
responses.add(DocumentMessage::AbortTransaction);
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
}
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
log::error!("Could not get selected nodes in ShakeNode");
@@ -1609,7 +1622,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
if !self.duplicated_in_drag {
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
@@ -2247,6 +2262,20 @@ impl NodeGraphMessageHandler {
common
}
fn duplicate_selected_nodes(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], responses: &mut VecDeque<Message>) {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
}
/// Send the cached layout to the frontend for the control bar at the top of the node panel
fn send_node_bar_layout(&self, responses: &mut VecDeque<Message>) {
responses.add(LayoutMessage::SendLayout {
@@ -2678,8 +2707,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None,
}));
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_preview);
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_root);
} else {
added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX),
@@ -2730,8 +2759,11 @@ impl NodeGraphMessageHandler {
log::error!("Could not get position for node: {node_id}");
continue;
};
// Asked of the preview itself rather than inferred from the export, which previewing does not rewire
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let previewed = is_export && !is_root_node;
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -2913,6 +2945,7 @@ impl Default for NodeGraphMessageHandler {
widgets: [LayoutGroup::row(Vec::new()), LayoutGroup::row(Vec::new())],
drag_start: None,
begin_dragging: false,
duplicated_in_drag: false,
node_has_moved_in_drag: false,
shift_without_push: false,
box_selection_start: None,
@@ -2944,6 +2977,7 @@ impl PartialEq for NodeGraphMessageHandler {
&& self.widgets == other.widgets
&& self.drag_start == other.drag_start
&& self.begin_dragging == other.begin_dragging
&& self.duplicated_in_drag == other.duplicated_in_drag
&& self.node_has_moved_in_drag == other.node_has_moved_in_drag
&& self.box_selection_start == other.box_selection_start
&& self.initial_disconnecting == other.initial_disconnecting
@@ -2,6 +2,7 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_block, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -24,7 +25,7 @@ use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -38,7 +39,9 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::MessagePart;
use std::path::PathBuf;
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -170,14 +173,19 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
pub multiline: bool,
pub progression: bool,
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -206,28 +214,25 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
match input.as_value()? {
TaggedValue::F64(value) => Some(*value),
TaggedValue::Number(value) => Some(*value),
_ => None,
}
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let NumberOptions {
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let ParameterOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
multiline,
progression,
unit,
display_decimal_places,
step,
} = options;
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
@@ -242,10 +247,8 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
@@ -259,12 +262,11 @@ pub(crate) fn property_from_type(
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info);
@@ -297,109 +299,98 @@ pub(crate) fn property_from_type(
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
Some("SignedPercentage") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
Some("Angle") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
Some("TextArea") => text_area_widget(default_info).into(),
use std::any::TypeId;
// For all other types, use TypeId-based matching
_ => {
use std::any::TypeId;
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) => match progression {
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
};
extra_widgets.push(widgets);
@@ -426,6 +417,60 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
widgets
}
/// A math expression's text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let Some(error) = math_expression_error(expression, accepts_reducers) else {
return text_widget(parameter_widgets_info);
};
// The 12px icon is padded to a checkbox's 16px so the field still lines up with the rows around it
parameter_widgets_info.blank_assist = false;
let mut widgets = start_widgets(&parameter_widgets_info);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Warning").tooltip_label("Invalid Math Expression").tooltip_description(error).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(expression.clone())
.on_update(parameter_widgets_info.update_value(|x: &TextInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// Why a math expression fails to parse, as tooltip Markdown, or `None` when it parses. Where the node applies a lone operator or
/// function name like `+` or `min` across its items, that counts as valid too. An error at a place in the expression repeats the
/// expression with carets under that place, as a compiler does.
fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<String> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
let error = math_parser::ast::Node::try_parse_from_str(expression).err()?;
// The quoted code may be the expression's own text, so it goes in a span nothing inside can close, and the prose is escaped
let messages = error.messages().iter().map(|message| {
let parts = message.parts().iter().map(|part| match part {
MessagePart::Text(text) => escape_markdown(text),
MessagePart::Code(code) => markdown_code_span(code),
});
let prose = parts.collect::<String>();
// The carets and their label line up under the expression's characters, with one caret where the span is empty, like at the end of the input
let Some(span) = message.span() else { return prose };
let indent = " ".repeat(expression.get(..span.start).map_or(0, |text| text.chars().count()));
let carets = "^".repeat(expression.get(span.start..span.end).map_or(0, |text| text.chars().count()).max(1));
format!("{prose}\n{}", markdown_code_block(&format!("{expression}\n{indent}{carets}\n{indent}error here")))
});
Some(messages.collect::<Vec<_>>().join("\n"))
}
pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -803,7 +848,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.widget_instance(),
]);
}
Some(&TaggedValue::F64(value)) => {
Some(&TaggedValue::Number(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
@@ -842,14 +887,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
.filter(|x| !x.is_empty())
.map(graphene_std::core_types::misc::parse_f64)
.collect::<Option<Vec<_>>>()
.map(TaggedValue::F64Array)
.map(TaggedValue::Numbers)
};
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
@@ -1004,7 +1049,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
let whole_part = x.trunc();
let fractional_part = x.fract();
@@ -1017,7 +1062,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.max(0.99999)
.value(Some(fractional_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -1029,7 +1074,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.is_integer(true)
.value(Some(whole_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
.on_commit(commit_value)
.widget_instance(),
])
@@ -1116,19 +1161,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
return vec![];
};
match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::I64(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::I64(x.value.unwrap().round() as i64)))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1137,7 +1182,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(dvec2.y))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1181,6 +1226,96 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
}
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(current) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return LayoutGroup::row(widgets);
};
// Every element type the node's rows accept at this input
let mut offered: Vec<Type> = Vec::new();
let implementation = parameter_widgets_info
.network_interface
.implementation(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path);
if let Some(DocumentNodeImplementation::ProtoNode(identifier)) = implementation
&& let Some(rows) = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)
{
for row in rows.keys() {
let Some(ty) = row.inputs.get(parameter_widgets_info.index) else { continue };
let element = wire_element(ty);
if !offered.contains(&element) {
offered.push(element);
}
}
}
let sections = type_choice_sections(&offered);
let entry_sections = sections
.iter()
.map(|section| {
section
.iter()
.map(|ty| {
let chosen = TaggedValue::from_type_or_none(ty);
MenuListEntry::new(ty.to_string())
.label(ty.to_string())
.on_update(parameter_widgets_info.update_value(move |_| chosen.clone()))
.on_commit(commit_value)
})
.collect()
})
.collect();
// The dropdown counts its selection across every section, since separators divide the entries without renumbering them
let current_element = wire_element(&current.ty());
let selected = sections.iter().flatten().position(|ty| *ty == current_element).map(|position| position as u32);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entry_sections).selected_index(selected).widget_instance(),
]);
LayoutGroup::row(widgets)
}
/// The element a wire type carries, peeling the `Item` or `List` rank a registry row or stored value wraps it in.
fn wire_element(ty: &Type) -> Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => (**element).clone(),
other => other.clone(),
}
}
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
],
];
let mut sections: Vec<Vec<Type>> = vocabulary.iter().map(|section| section.iter().filter(|ty| offered.contains(ty)).cloned().collect()).collect();
let mut unlisted: Vec<Type> = offered.iter().filter(|ty| !vocabulary.iter().any(|section| section.contains(ty))).cloned().collect();
unlisted.sort_by_key(|ty| ty.to_string());
sections.push(unlisted);
sections.retain(|section| !section.is_empty());
sections
}
pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button: ColorInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1699,7 +1834,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
let exposed = input.is_some_and(|input| input.is_exposed());
let value = input
.and_then(|input| input.as_value())
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None })
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
.unwrap_or(0.);
(exposed, value)
})
@@ -1822,7 +1957,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F64(scale.value(scale_position)).into(),
value: TaggedValue::Number(scale.value(scale_position)).into(),
}
.into()
}
@@ -1858,7 +1993,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
.value(Some(current))
.min_width(60)
.max_width(60)
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -1883,7 +2018,7 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
_ => HueSaturationRange::Master,
};
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::F64(value)) => *value as f32,
Some(TaggedValue::Number(value)) => *value as f32,
_ => 0.,
};
@@ -2097,7 +2232,7 @@ fn slider_row(
};
// An exposed input shows only its label and source
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
@@ -2159,7 +2294,7 @@ fn gradient_slider_row(
.ok()
.and_then(|document_node| document_node.inputs.get(input_index))
.and_then(|input| input.as_non_exposed_value())
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None });
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
// Only add the slider and number widgets when the input is not exposed
if let Some(current) = current {
@@ -2168,7 +2303,7 @@ fn gradient_slider_row(
max: value_max,
default: Some(default_value),
};
let value_at = move |position| TaggedValue::F64(slider.value(position));
let value_at = move |position| TaggedValue::Number(slider.value(position));
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(
@@ -2191,7 +2326,7 @@ fn gradient_slider_row(
.min_width(60)
.max_width(60)
.display_decimal_places(0)
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2613,7 +2748,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
Ok(document_node) => {
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::I64(x)) => x,
Some(&TaggedValue::Integer(x)) => x,
_ => 2,
};
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
@@ -2937,10 +3072,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
let mut options = ParameterOptions::default();
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
@@ -2953,16 +3085,18 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = NumberOptions {
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
default_type = field.default_type.clone();
}
@@ -2990,7 +3124,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.unwrap_or(concrete!(())),
};
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
});
layout.extend(row);
@@ -3613,3 +3747,53 @@ pub mod choice {
pub struct ForValue<W>(PhantomData<W>);
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::{item, list};
#[test]
fn wire_element_reads_every_spelling_down_to_the_element() {
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
}
// The element of a stored value and of the row that accepts it agree, which is what selects the dropdown entry
assert_eq!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(i64)));
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert_eq!(math_expression_error(expression, accepts_reducers), None, "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert_eq!(math_expression_error("sin(I)", true).as_deref(), Some("A matrix stands where a value is needed"));
}
#[test]
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting, and the expression
// repeats in a block below with labeled carets under the error's span
assert_eq!(math_expression_error("`abc", false).as_deref(), Some("`` `abc `` is not recognized\n```\n`abc\n^^^^\nerror here\n```"));
assert_eq!(
math_expression_error("7 % 3", false).as_deref(),
Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`\n```\n7 % 3\n ^\n error here\n```")
);
assert!(math_expression_error("(1", false).unwrap().ends_with("\n(1\n ^\n error here\n```"));
assert!(math_expression_error("πx @ 2", false).unwrap().ends_with("\nπx @ 2\n ^\n error here\n```"));
assert!(!math_expression_error("sin(I)", false).unwrap().contains('^'), "a sort error has no place to point at");
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = math_expression_error("2 * * 3", false).unwrap();
let prose = error.lines().next().unwrap();
assert!(prose.starts_with("Found `*`, expected ") && !prose.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
}
}
@@ -0,0 +1,215 @@
//! Document store lifecycle: discovery, session restore, legacy/storage reconciliation, mode changes, and removal.
use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::portfolio::document_storage_io::document_key;
use crate::messages::prelude::*;
use crate::test_utils::EditorTestUtils;
use document_container::{AnyContainer, AsyncContainer};
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
editor.editor.handle_message(message)
}
fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler {
&editor.editor.dispatcher.message_handlers.portfolio_message_handler
}
fn restart(editor: &mut EditorTestUtils, state: PersistedState) {
dispatch(editor, PortfolioMessage::DestroyAllDocuments);
dispatch(editor, PersistentStateMessage::LoadState { state });
}
fn new_document(editor: &mut EditorTestUtils, name: &str) -> DocumentId {
dispatch(editor, PortfolioMessage::NewDocumentWithName { name: name.into() });
portfolio(editor).active_document_id.unwrap()
}
async fn container(editor: &EditorTestUtils, document_id: DocumentId) -> AnyContainer {
portfolio(editor).document_store().open(document_key(document_id)).await.unwrap()
}
async fn stored_ids(editor: &EditorTestUtils) -> Vec<DocumentId> {
portfolio(editor).document_store().list().await.unwrap().into_iter().map(|key| DocumentId(key.0)).collect()
}
#[tokio::test]
async fn stored_documents_are_discovered_without_session_state() {
let mut editor = EditorTestUtils::create();
let one = new_document(&mut editor, "One");
let two = new_document(&mut editor, "Two");
restart(&mut editor, PersistedState::default());
let state = portfolio(&editor).persisted_state_snapshot();
let mut ids: Vec<_> = state.documents.iter().map(|info| info.id).collect();
ids.sort();
let mut expected = vec![one, two];
expected.sort();
assert_eq!(ids, expected);
assert_ne!(
state.documents[0].name, state.documents[1].name,
"names are not stored in the legacy file, so discovered documents get distinct generated ones"
);
assert_eq!(portfolio(&editor).documents.len(), 2);
assert!(portfolio(&editor).active_document().is_some());
}
#[tokio::test]
async fn session_state_restores_order_names_and_selection() {
let mut editor = EditorTestUtils::create();
new_document(&mut editor, "First");
let selected = new_document(&mut editor, "Second");
let state = portfolio(&editor).persisted_state_snapshot();
let expected: Vec<_> = state.documents.iter().map(|info| (info.id, info.name.clone())).collect();
restart(&mut editor, state);
let restored = portfolio(&editor).persisted_state_snapshot();
assert_eq!(restored.documents.iter().map(|info| (info.id, info.name.clone())).collect::<Vec<_>>(), expected);
assert_eq!(portfolio(&editor).active_document_id, Some(selected));
}
#[tokio::test]
async fn session_entries_without_stored_content_are_dropped() {
let mut editor = EditorTestUtils::create();
let kept = new_document(&mut editor, "Kept");
let mut state = portfolio(&editor).persisted_state_snapshot();
let mut ghost = state.documents[0].clone();
ghost.id = DocumentId(0xdead);
state.documents.push(ghost);
restart(&mut editor, state);
let ids: Vec<_> = portfolio(&editor).persisted_state_snapshot().documents.iter().map(|info| info.id).collect();
assert_eq!(ids, vec![kept]);
}
#[tokio::test]
async fn legacy_only_container_gets_storage() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(0xabc);
let container = container(&editor, id).await;
container.write("legacy.graphite", DocumentMessageHandler::default().serialize_document().as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_mode_reads_legacy_only_and_leaves_storage_files_alone() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Legacy");
let container = container(&editor, id).await;
assert!(!container.exists("manifest.json").await);
container.write("manifest.json", b"broken").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_none());
assert_eq!(container.read("manifest.json").await.unwrap().as_slice(), b"broken");
}
#[tokio::test]
async fn storage_only_container_recovers_and_writes_legacy() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Storage");
let container = container(&editor, id).await;
container.remove("legacy.graphite").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_wins_over_stale_storage_and_history_is_kept() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Changed");
let container = container(&editor, id).await;
let before = editor.active_document().serialize_document();
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
container.write("legacy.graphite", before.as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_undo(), "the stale stored state stays reachable as history");
}
#[tokio::test]
async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Undo");
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().document_network(), &network_before);
assert!(editor.active_document().storage().unwrap().can_redo());
assert!(editor.active_document().is_auto_saved(), "the rebuild completion autosaves the cursor's network");
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_redo(), "reopening identical content must not stage a new interaction");
assert!(!storage.can_undo());
}
#[tokio::test]
async fn closing_removes_the_stored_document() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Closed");
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, PortfolioMessage::CloseDocument { document_id: id });
assert!(stored_ids(&editor).await.is_empty());
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
}
#[tokio::test]
async fn storage_preference_attaches_and_drops_sessions() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Toggle");
let container = container(&editor, id).await;
assert!(editor.active_document().storage().is_none());
assert!(container.exists("legacy.graphite").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: true });
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
assert!(editor.active_document().storage().is_none());
}
#[tokio::test]
async fn unreadable_document_is_reported_and_kept_until_discarded() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(7);
container(&editor, id).await.write("legacy.graphite", b"not a document").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(!portfolio(&editor).documents.contains_key(&id));
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, FailedDocumentsMessage::DiscardFailedToLoadDocuments);
assert!(stored_ids(&editor).await.is_empty());
}
@@ -6,7 +6,7 @@
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry, to_value};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -342,26 +342,14 @@ fn document_settings_round_trip() {
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(to_value(&restored.render_mode).unwrap(), to_value(&document.render_mode).unwrap(), "render_mode");
assert_eq!(to_value(&restored.rulers_visible).unwrap(), to_value(&document.rulers_visible).unwrap(), "rulers_visible");
assert_eq!(to_value(&restored.document_ptz).unwrap(), to_value(&document.document_ptz).unwrap(), "document_ptz");
assert_eq!(
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
to_value(&restored.overlays_visibility_settings).unwrap(),
to_value(&document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(
serde_json::to_value(restored.snapping_state).unwrap(),
serde_json::to_value(document.snapping_state).unwrap(),
"snapping_state"
);
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
assert_eq!(to_value(&restored.snapping_state).unwrap(), to_value(&document.snapping_state).unwrap(), "snapping_state");
assert_eq!(to_value(&restored.collapsed).unwrap(), to_value(&document.collapsed).unwrap(), "collapsed");
}
@@ -4,6 +4,7 @@
//!
//! Shared fixtures live in [`test_support`].
mod lifecycle_tests;
mod metadata_tests;
mod round_trip_tests;
mod test_support;
pub(crate) mod test_support;
@@ -1,13 +1,13 @@
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId};
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
use graph_craft::application_io::resource::HashMapResourceStorage;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
@@ -158,9 +158,7 @@ async fn edit_after_open_commits_cleanly() {
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let source_network = source.network_interface.document_network().clone();
let source_view = StorageMetadataView::new(&source.network_interface);
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
@@ -210,9 +208,7 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Commit the active document's current runtime state as one interaction.
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
@@ -263,9 +259,7 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
@@ -334,7 +328,7 @@ async fn live_undo_shadows_storage_cursor() {
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_edit = editor.active_document().network_interface.document_network().clone();
@@ -373,9 +367,9 @@ async fn round_trip_document_settings() {
// The `ui::doc::*` view settings survived the persist/reopen cycle (in session.json, not the registry).
let settings = &round_trip.view_settings;
assert_eq!(settings.get(doc::RENDER_MODE), Some(&serde_json::to_value(RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&serde_json::to_value(false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&serde_json::to_value(&document.snapping_state).unwrap()), "snapping_state");
assert_eq!(settings.get(doc::RENDER_MODE), Some(&to_value(&RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&to_value(&false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&to_value(&document.snapping_state).unwrap()), "snapping_state");
}
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
@@ -387,15 +381,13 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
ptz.pan = glam::DVec2::new(-960., -540.);
ptz.set_zoom(0.459);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(ptz).unwrap())]);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), to_value(&ptz).unwrap())]);
gdd.set_view_settings(view_settings).expect("set_view_settings");
// Export to an in-memory archive, then reopen it from bytes into a fresh container.
@@ -410,7 +402,7 @@ async fn gdd_archive_round_trips_view_settings() {
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&serde_json::to_value(ptz).unwrap()),
Some(&to_value(&ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
@@ -437,9 +429,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -472,14 +462,14 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
}
/// Mirror the real "new document, draw a rect, press undo" flow: mount storage and capture the
/// new-document base as the mount-time snapshot (as `DocumentStorageMounted` does), then draw a rect
/// new-document base as the attach-time snapshot (as `StorageAttached` does), then draw a rect
/// (one `CommitTransaction` interaction) and undo. The shadow must reproduce the legacy-restored interface.
#[tokio::test]
async fn live_undo_new_document_draw_rect() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -569,7 +559,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.handle_message(paste_named_image()).await;
@@ -601,7 +591,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
@@ -674,10 +664,8 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
}
@@ -701,7 +689,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
})
.await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -769,7 +757,7 @@ async fn none_fill_survives_document_reopen() {
// Reopen through the editor's real open path, which runs the document migrations
let serialized = editor.active_document().serialize_document();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
@@ -792,7 +780,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
@@ -850,7 +838,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: EIGHT_INPUT_DOCUMENT.to_string(),
@@ -46,7 +46,7 @@ pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)
pub struct RoundTrip {
pub rebuilt: NodeNetworkInterface,
pub registry: document_graph_storage::Registry,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
pub view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
@@ -56,9 +56,7 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -447,7 +447,7 @@ impl NodeNetworkInterface {
}
/// Every input fed by each node output and each import of the network.
fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
pub(super) fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
let mut outward_wires = HashMap::new();
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in compute_outward_wires");
@@ -509,23 +509,72 @@ impl NodeNetworkInterface {
/// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully
/// rebuilt on the next read via `outward_wires()`).
pub(crate) fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) {
let Some(transient) = self.network_transient_mut(network_path) else {
return;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return;
let drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
unhook_outward_wire(outward_wires, input_connector, old_input);
hook_outward_wire(outward_wires, input_connector, new_input);
drained_outward_wire(outward_wires, old_input)
};
// Remove the input_connector from the old output's downstream list
if let Some(old_output) = OutputConnector::from_input(old_input)
&& let Some(connections) = outward_wires.get_mut(&old_output)
{
connections.retain(|c| c != input_connector);
if let Some(output) = drained {
self.delist_vacated_output(network_path, output);
}
}
/// The same update for a node whose whole input list was swapped.
pub(crate) fn update_outward_wires_for_inputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_inputs: &[NodeInput], new_inputs: &[NodeInput]) {
let drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
for (input_index, old_input) in old_inputs.iter().enumerate() {
unhook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), old_input);
}
for (input_index, new_input) in new_inputs.iter().enumerate() {
hook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), new_input);
}
old_inputs.iter().filter_map(|old_input| drained_outward_wire(outward_wires, old_input)).collect::<Vec<_>>()
};
for output in drained {
self.delist_vacated_output(network_path, output);
}
}
/// Drops an emptied entry for an output the network no longer has, which a fresh computation keys only while a wire still reaches it.
fn delist_vacated_output(&mut self, network_path: &[NodeId], output: OutputConnector) {
let still_exists = match output {
OutputConnector::Node { node_id, output_index } => output_index < self.number_of_outputs(&node_id, network_path),
OutputConnector::Import(import_index) => import_index < self.number_of_imports(network_path),
};
if still_exists {
return;
}
// Add the input_connector to the new output's downstream list
if let Some(new_output) = OutputConnector::from_input(new_input) {
outward_wires.entry(new_output).or_default().push(*input_connector);
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
outward_wires.remove(&output);
}
/// Lists or delists a node's outputs after their count changed, since every output is keyed even with no consumers.
pub(crate) fn update_outward_wires_for_outputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_output_count: usize, new_output_count: usize) {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
// A consumer still wired to a vanished output keeps the entry, as a fresh computation lists it too
for output_index in new_output_count..old_output_count {
let output = OutputConnector::node(*node_id, output_index);
if outward_wires.get(&output).is_some_and(Vec::is_empty) {
outward_wires.remove(&output);
}
}
for output_index in old_output_count..new_output_count {
outward_wires.entry(OutputConnector::node(*node_id, output_index)).or_default();
}
}
@@ -680,24 +729,26 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
}
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
/// is really connected to.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
/// When previewing, there may be a second path to the root node.
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
let root_node = match self.previewing(network_path) {
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
// The export already reaches it, so a second wire would land on top of the solid one
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
if Some(root_node.node_id) == current_export.node_id() {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
log::error!("Could not get input position for wire end in root node: {input:?}");
return None;
};
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -866,3 +917,24 @@ impl NodeNetworkInterface {
}
}
}
/// Drops `input_connector` from the consumers of the output that `input` was wired to.
fn unhook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input)
&& let Some(connections) = outward_wires.get_mut(&output)
{
connections.retain(|connection| connection != input_connector);
}
}
/// Adds `input_connector` to the consumers of the output that `input` is wired to.
fn hook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input) {
outward_wires.entry(output).or_default().push(*input_connector);
}
}
/// The output `input` was wired to, once it has lost its last consumer.
fn drained_outward_wire(outward_wires: &HashMap<OutputConnector, Vec<InputConnector>>, input: &NodeInput) -> Option<OutputConnector> {
OutputConnector::from_input(input).filter(|output| outward_wires.get(output).is_some_and(Vec::is_empty))
}
@@ -1,4 +1,4 @@
use super::{InputConnector, OutputConnector, Previewing, RootNode, TransactionStatus};
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeInput;
@@ -172,6 +172,31 @@ async fn connecting_an_export_is_never_cyclic() {
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
@@ -381,10 +406,8 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
assert_invariants(&editor, "after removing the added export");
}
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
#[tokio::test]
async fn previewing_leaves_the_export_alone() {
async fn toggle_preview_transitions_with_a_connected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -396,123 +419,212 @@ async fn previewing_leaves_the_export_alone() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node names it without touching the export
// Previewing a node remembers the artboard as the connection to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: node, output_index: 0 }
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
}
);
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Previewing a different node moves the preview, still without touching the export
network_interface.toggle_preview(artboard, &[]);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: artboard, output_index: 0 }
}
);
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
// Toggling the previewed node again ends the preview, leaving the export as it always was
network_interface.toggle_preview(artboard, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_invariants(&editor, "after cycling through the preview states");
}
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
/// that does not rewire the document.
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = network_interface.network_to_evaluate();
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
fn assert_interface_invariants(network_interface: &NodeNetworkInterface, context: &str) {
let violations = network_interface.validate_invariants();
assert!(violations.is_empty(), "Invariant violations {context}:\n{}", violations.join("\n"));
}
/// The previewed node is marked for the frontend so it can be highlighted. The mark comes from the
/// preview state itself, not from the export.
#[tokio::test]
async fn the_previewed_node_is_flagged_for_the_frontend() {
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
fn value_input() -> NodeInput {
NodeInput::value(TaggedValue::None, false)
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
/// A source feeding a node that feeds a consumer, with the outward wire cache loaded so every later mutation has to keep it current.
fn wired_interface() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) {
let (source, node, consumer) = (NodeId(1), NodeId(2), NodeId(3));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
network_interface.insert_node(
node,
NodeTemplate {
inputs: vec![value_input(), value_input()],
..Default::default()
},
&[],
);
network_interface.insert_node(
consumer,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 0), &[]);
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
assert!(network_interface.outward_wires(&[]).is_some());
assert_interface_invariants(&network_interface, "after wiring the fixture");
(network_interface, source, node, consumer)
}
let handler = NodeGraphMessageHandler::default();
let network_interface = &mut editor.active_document_mut().network_interface;
#[test]
fn replacing_inputs_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, source, node, _) = wired_interface();
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
handler
.collect_nodes(network_interface, &[])
.into_iter()
.filter(|node| node.previewed)
.map(|node| node.id)
.collect::<Vec<_>>()
let mut template = NodeTemplate {
inputs: vec![value_input(); 3],
..Default::default()
};
template.normalize_input_metadata();
network_interface.replace_inputs(&node, &[], &mut template);
assert_interface_invariants(&network_interface, "after replacing the inputs of a wired node");
// The wire returns at a new index, as a migration restores the inputs it keeps
network_interface.set_input(&InputConnector::node_at_index(node, 2), NodeInput::node(source, 0), &[]);
assert_interface_invariants(&network_interface, "after rewiring the source into the replaced node");
}
#[test]
fn replacing_an_implementation_keeps_its_outputs_listed_in_the_wire_cache() {
let (mut network_interface, _, node, _) = wired_interface();
let second_output = OutputConnector::node(node, 1);
// An implementation swap leaves the output names to the open path, so restore them as it does before validating
let swap_implementation = |network_interface: &mut NodeNetworkInterface, template: &mut NodeTemplate, context: &str| {
network_interface.replace_implementation(&node, &[], template);
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
assert_interface_invariants(network_interface, context);
};
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
swap_implementation(&mut network_interface, &mut template, "after giving a node a second output");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a gained output should be listed"
);
network_interface.toggle_preview(node, &[]);
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
network_interface.toggle_preview(node, &[]);
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
swap_implementation(&mut network_interface, &mut NodeTemplate::default(), "after taking the second output away");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"a lost output should be delisted"
);
}
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
/// node on its own, with a stack as the case that matters.
#[tokio::test]
async fn batched_positions_agree_with_resolving_each_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
// A vanished output keeps its entry while a consumer is still wired to it, so the entry has to go when that consumer leaves
#[test]
fn rewiring_off_a_vanished_output_delists_it_from_the_wire_cache() {
let (mut network_interface, source, node, consumer) = wired_interface();
let second_output = OutputConnector::node(node, 1);
for offset in 0..4 {
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
}
let restore_output_names = |network_interface: &mut NodeNetworkInterface| {
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
};
let network_interface = &editor.active_document().network_interface;
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
// Give the node a second output and move the consumer onto it
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
network_interface.replace_implementation(&node, &[], &mut template);
restore_output_names(&mut network_interface);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 1), &[]);
assert_interface_invariants(&network_interface, "after wiring a consumer to the second output");
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
let individually = node_ids
.iter()
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
.collect::<Vec<_>>();
// Taking that output away leaves the consumer dangling, which a fresh computation still lists
network_interface.replace_implementation(&node, &[], &mut NodeTemplate::default());
restore_output_names(&mut network_interface);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a vanished output should keep its entry while something is still wired to it"
);
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
for (node_id, position) in individually {
assert_eq!(
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
Some(position),
"Batched position disagrees for node {node_id}"
);
}
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(source, 0), &[]);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"the entry should go once the last consumer leaves a vanished output"
);
assert_interface_invariants(&network_interface, "after rewiring off a vanished output");
}
#[test]
fn inserting_and_deleting_nodes_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, _, node, _) = wired_interface();
network_interface.insert_node(NodeId(4), NodeTemplate::default(), &[]);
assert_interface_invariants(&network_interface, "after inserting a node while the cache is loaded");
network_interface.delete_nodes(vec![node], false, &[]);
assert_interface_invariants(&network_interface, "after deleting a wired node");
}
#[test]
fn adding_an_import_ahead_of_a_wired_input_keeps_the_loaded_wire_cache_exact() {
let (source, node) = (NodeId(1), NodeId(2));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
let network = NodeNetworkTemplate {
exports: vec![value_input()],
..Default::default()
};
let template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(network),
inputs: vec![value_input()],
output_names: vec![String::new()],
..Default::default()
};
network_interface.insert_node(node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
assert!(network_interface.outward_wires(&[]).is_some());
// Inserting ahead of the wired input moves that wire to index 1
network_interface.add_import(TaggedValue::None, true, 0, "", "", &[node]);
assert_interface_invariants(&network_interface, "after adding an import ahead of a wired input");
let consumers = network_interface.outward_wires(&[]).and_then(|wires| wires.get(&OutputConnector::node(source, 0)).cloned());
assert_eq!(consumers.as_deref(), Some([InputConnector::node_at_index(node, 1)].as_slice()));
}
@@ -4,7 +4,7 @@ use super::{InputMetadata, InputPersistentMetadata};
use document_graph_storage::attr::network as network_attr;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp, Value};
use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
@@ -124,8 +124,8 @@ pub fn construct_batch(
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
batch_removed_nodes.sort_by_key(|(id, _)| *id);
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
Ok(ConstructedOps { ops, declarations })
}
@@ -143,7 +143,7 @@ impl EditorDelta {
&self,
context: &ConversionContext,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
@@ -153,7 +153,9 @@ impl EditorDelta {
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
// Only what the previous implementation owned goes; the node stays so the addition below
// updates it in place and its `ui::*` attributes survive the swap.
construct_removals_below(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
@@ -166,7 +168,7 @@ impl EditorDelta {
id: context.resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
value: (!visible).then_some(Value::Bool(false)),
},
});
}
@@ -177,18 +179,26 @@ impl EditorDelta {
input_index,
input,
}) => {
let new_input = context.resolver.convert_input_at(input, network_path)?;
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &new_input, context, batch, ops)?;
ops.push(RegistryDelta::ChangeNodeInput {
id: context.resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: context.resolver.convert_input_at(input, network_path)?,
new_input,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
let export = input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?;
if let Some(export) = export.as_ref() {
construct_referenced_resource(None, export, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNetworkExport {
id: context.resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?,
export,
});
}
@@ -223,10 +233,15 @@ impl EditorDelta {
input: context.resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
attributes_timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
for slot in &inputs {
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &slot.input, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNodeInputs {
id: context.resolver.node_id(network_path, *node_id),
inputs,
@@ -265,7 +280,7 @@ impl EditorDelta {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(serde_json::Value::String),
value: reference.clone().map(Value::Str),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
@@ -287,8 +302,8 @@ impl EditorDelta {
}
}
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serde_json::Value, ConversionError> {
serde_json::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<Value, ConversionError> {
document_graph_storage::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
}
/// The attribute writes one metadata field makes, as the whole-document encoder would write them.
@@ -296,11 +311,11 @@ fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serd
/// A field set back to its unset value clears the attribute, since absence is how that encoder spells
/// unset. Clearing rather than writing a sentinel keeps the two paths producing the same registry.
fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMetadataChange) -> Result<Vec<RegistryDelta>, ConversionError> {
let node_attribute = |key: &str, value: Option<serde_json::Value>| RegistryDelta::ChangeNodeAttribute {
let node_attribute = |key: &str, value: Option<Value>| RegistryDelta::ChangeNodeAttribute {
id: global_id,
delta: AttributeDelta { key: key.to_string(), value },
};
let input_attribute = |key: &str, index: usize, value: Option<serde_json::Value>| {
let input_attribute = |key: &str, index: usize, value: Option<Value>| {
Ok::<_, ConversionError>(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: index.try_into().map_err(|_| ConversionError::IndexOverflow(index))?,
@@ -309,8 +324,8 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
};
// The empty string is the runtime's own sentinel for an unset name
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
let flag = |value: bool| value.then_some(Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| Value::Str(value.to_string()));
Ok(match change {
NodeMetadataChange::NodeType(node_type) => {
let position = position_from_runtime(node_type);
@@ -364,7 +379,39 @@ fn construct_structural_additions(
nodes.sort_by_key(|(id, _)| **id);
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
for (id, node) in added {
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes; a whole-slot assignment would drop the
// names and descriptions held for the slots that survive it.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
slot.attributes.extend(
previous
.attributes
.iter()
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
.map(|(key, value)| (key.clone(), value.clone())),
);
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -396,6 +443,31 @@ fn construct_structural_additions(
Ok(())
}
/// Stages the resource a value input references, so setting an input to an asset persists the entry
/// alongside the reference rather than leaving the registry pointing at something it does not hold.
fn construct_referenced_resource(
owner: Option<document_graph_storage::NodeId>,
input: &document_graph_storage::NodeInput,
context: &ConversionContext,
batch: &mut BatchRegistry,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let Some(id) = value_resource_ref(input) else { return Ok(()) };
if let Some(owner) = owner {
batch.record_input_resource(owner, id);
}
if batch.resource(id).is_some() {
return Ok(());
}
let Some(entry) = convert_resource_entry(context.resources, id, context.peer)? else {
return Ok(());
};
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
Ok(())
}
fn construct_metadata_snapshot(
network_path: &[NodeId],
node_id: NodeId,
@@ -439,11 +511,12 @@ fn construct_metadata_snapshot(
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let target = network_metadata.persistent_metadata.reference.clone().map(Value::Str);
// Read through the batch rather than the pre-batch registry: a `ReplaceNode` earlier in this
// batch rebuilds the network without a reference, so comparing against the old state would
// suppress the write and leave the rebuilt network missing it.
let current = batch
.working
.networks
.get(&network_id)
.network(network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
@@ -456,6 +529,22 @@ fn construct_metadata_snapshot(
});
}
// Restated alongside the reference, since a rebuild clears the network's attributes and the
// order would otherwise be lost for every nested network the snapshot covers.
let pinned_order: Vec<_> = network_metadata
.persistent_metadata
.pinned_node_order
.iter()
.map(|pinned| resolver.node_id(&nested_path, *pinned))
.collect();
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!pinned_order.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &pinned_order)).transpose()?,
},
});
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
@@ -496,37 +585,69 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
/// Emits the removal of a node and everything nested under it, recording what was removed so the
/// batch's resource liveness accounts for all of it at the end.
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
fn construct_removals(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, true, batch, batch_removed_nodes, ops)
}
/// Removes everything the node's implementation owns while leaving the node itself, for a swap that
/// keeps the node in place.
fn construct_removals_below(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, false, batch, batch_removed_nodes, ops)
}
fn construct_removals_with(
node_id: document_graph_storage::NodeId,
include_node: bool,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
let Some(snapshot) = batch.node(*id) else { continue };
if !include_node && *id == node_id {
continue;
}
let Some(snapshot) = batch.node(*id).cloned() else { continue };
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
// Kept by value: a replacement later in this batch re-adds the same ID with different content, so
// looking the node up again at the end would read what replaced it rather than what was removed.
batch_removed_nodes.push((*id, snapshot));
batch.record_removal(*id);
}
for id in &removed_networks {
let Some(snapshot) = batch.network(*id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
batch_removed_nodes.extend(removed_nodes);
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::NodeId, document_graph_storage::Node)], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
// A node this batch wrote an input on and then removed orphans whatever that write referenced, which
// the stored node does not mention.
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.filter_map(|id| batch.node(*id))
.flat_map(|node| {
.flat_map(|(id, _)| batch.input_resources.get(id).into_iter().flatten().copied())
.chain(batch_removed_nodes.iter().map(|(_, node)| node).flat_map(|node| {
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
}))
.collect();
candidates.sort();
candidates.dedup();
@@ -536,16 +657,18 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
if removed_node_set.contains(id) {
continue;
}
for (id, node) in batch.live_nodes() {
if let Implementation::ProtoNode(declaration) = node.implementation() {
still_referenced.insert(*declaration);
}
still_referenced.extend(node_value_resource_refs(node));
// What this batch wrote onto a node that survives it is a live reference, even though the stored
// node still carries the input it had before.
still_referenced.extend(batch.input_resources.get(&id).into_iter().flatten().copied());
}
for network in batch.working.networks.values() {
// The batch's own networks count too: one added earlier in it can export a resource the removal would
// otherwise see as orphaned.
for network in batch.working.networks.values().chain(batch.added_networks.values()) {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
@@ -573,6 +696,13 @@ struct BatchRegistry<'a> {
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
/// Nodes the batch has removed and not since re-added, so a lookup answers with the state the ops so
/// far have produced rather than the state the batch started from.
removed: HashSet<document_graph_storage::NodeId>,
/// Resources the batch's own input writes reference, keyed by the node written to. The stored node
/// still holds its pre-batch inputs, so liveness would otherwise miss both the reference these writes
/// create and the orphan they leave when that node is later removed.
input_resources: HashMap<document_graph_storage::NodeId, HashSet<ResourceId>>,
}
impl<'a> BatchRegistry<'a> {
@@ -587,15 +717,29 @@ impl<'a> BatchRegistry<'a> {
added_networks: HashMap::new(),
added_resources: HashMap::new(),
by_network,
removed: HashSet::new(),
input_resources: HashMap::new(),
}
}
/// Records that an input write on `owner` references `resource`.
fn record_input_resource(&mut self, owner: document_graph_storage::NodeId, resource: ResourceId) {
self.input_resources.entry(owner).or_default().insert(resource);
}
/// Records a node an earlier delta in this batch added, so a later one can read it back.
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
self.by_network.entry(node.network()).or_default().push(id);
self.removed.remove(&id);
self.added.insert(id, node);
}
/// Records a node this batch removed, so a later delta reading it back finds it gone.
fn record_removal(&mut self, id: document_graph_storage::NodeId) {
self.added.remove(&id);
self.removed.insert(id);
}
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
/// the network to remove alongside it.
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
@@ -609,9 +753,25 @@ impl<'a> BatchRegistry<'a> {
}
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
if self.removed.contains(&id) {
return None;
}
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
}
/// Every node the batch leaves in place, which is what the working registry held plus what the batch
/// added, less what it removed.
fn live_nodes(&self) -> impl Iterator<Item = (document_graph_storage::NodeId, &document_graph_storage::Node)> {
self.working
.node_instances
.keys()
.chain(self.added.keys())
.copied()
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|id| Some((id, self.node(id)?)))
}
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
}
@@ -680,8 +840,10 @@ impl NodeMetadataSource for InputMetadataSource<'_> {
self.persistent(input_index)?.widget_override.as_deref()
}
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
self.persistent(input_index).map(|metadata| metadata.input_data.clone()).unwrap_or_default()
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, Value> {
self.persistent(input_index)
.map(|metadata| metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
}
}
@@ -771,10 +933,10 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.map(|input| input.persistent_metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
}
@@ -78,7 +78,7 @@ async fn set_input_value_constructs_the_exact_diff_op() {
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
let input = NodeInput::value(TaggedValue::Number(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
@@ -337,7 +337,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
@@ -378,7 +378,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
@@ -452,7 +452,7 @@ async fn replaying_an_arity_change_reproduces_the_interface() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
@@ -576,3 +576,59 @@ async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
}
/// Swapping a node's implementation must not restate the node's own metadata: the swap did not write it,
/// and asserting it would overwrite whatever a concurrent peer set for the node's name, lock or pin.
#[tokio::test]
async fn swapping_an_implementation_leaves_the_node_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let working = convert(&editor);
let deltas = {
let interface = &mut editor.active_document_mut().network_interface;
interface.discard_deltas();
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(node, &[])) else {
panic!("the node should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
interface.take_deltas()
};
let ops = construct(&editor, &deltas, &working);
assert!(
ops.iter().any(|op| matches!(op, RegistryDelta::SetNodeImplementation { .. })),
"the swap should update the implementation in place"
);
assert!(
!ops.iter().any(|op| matches!(op, RegistryDelta::RemoveNode { .. })),
"the node itself should not be rebuilt, since that would clear the attributes it carries"
);
assert!(
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
"the node's own metadata should not be restated by a swap that did not write it"
);
// The slots that survive the swap keep the names and descriptions the registry holds for them.
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
_ => None,
}) else {
panic!("the swap should restate the slots")
};
let held: Vec<_> = working.node_instances[id]
.inputs()
.iter()
.take(inputs.len())
.flat_map(|slot| document_graph_storage::attributes::live(&slot.attributes).filter(|(key, _)| key.starts_with("ui::")))
.collect();
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
for (index, slot) in inputs.iter().enumerate() {
for (key, value) in document_graph_storage::attributes::live(&working.node_instances[id].inputs()[index].attributes).filter(|(key, _)| key.starts_with("ui::")) {
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
}
}
}
@@ -19,11 +19,12 @@ impl NodeNetworkInterface {
let other_persistent = &other_network_metadata.persistent_metadata;
*view.navigation = other_persistent.navigation_metadata.clone();
// The preview is this peer's and survives a rebuild, unless it names a node the rebuilt
// network no longer contains (e.g. after a storage undo), in which case there is nothing
// left to look at.
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
*view.previewing = match other_persistent.previewing {
Previewing::Yes { previewed } if !view.nodes.contains_key(&previewed.node_id) => Previewing::No,
Previewing::Yes {
root_node_to_restore: Some(root_node),
} if !view.nodes.contains_key(&root_node.node_id) => Previewing::No,
previewing => previewing,
};
@@ -61,10 +62,11 @@ impl NodeNetworkInterface {
self.edit_input_value(&InputConnector::node_at_index(*node_id, 1), &[], |value| {
let TaggedValue::VectorModification(modification) = value else {
log::error!("Path node {node_id} does not have a modification input");
return;
return false;
};
modification.modify(&modification_type);
modified = true;
true
});
if modified {
@@ -140,6 +142,7 @@ impl NodeNetworkInterface {
}
// Update the metadata for the encapsulating node
self.unload_outward_wires(&encapsulating_network_path);
self.unload_node_click_targets(&node_id, &encapsulating_network_path);
self.unload_all_nodes_bounding_box(&encapsulating_network_path);
if encapsulating_network_path.is_empty() && inserted_index <= 1 {
@@ -382,12 +385,16 @@ impl NodeNetworkInterface {
/// Replaces the implementation and corresponding metadata.
pub fn replace_implementation(&mut self, node_id: &NodeId, network_path: &[NodeId], new_template: &mut NodeTemplate) {
let (new_implementation, new_network_metadata) = std::mem::take(&mut new_template.implementation).into_parts();
let old_output_count = self.number_of_outputs(node_id, network_path);
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in replace_implementation");
return;
};
node.replace_implementation(new_implementation, new_network_metadata);
let new_output_count = self.number_of_outputs(node_id, network_path);
self.update_outward_wires_for_outputs(network_path, node_id, old_output_count, new_output_count);
}
/// Replaces the inputs and corresponding metadata.
@@ -399,7 +406,10 @@ impl NodeNetworkInterface {
log::error!("Could not get node {node_id} in replace_inputs");
return None;
};
Some(node.replace_inputs(new_inputs, new_input_metadata))
let old_inputs = node.replace_inputs(new_inputs.clone(), new_input_metadata);
self.update_outward_wires_for_inputs(network_path, node_id, &old_inputs, &new_inputs);
Some(old_inputs)
}
/// Used when opening an old document to add the persistent metadata for each input if it doesn't exist, which is where the name/description are saved.
@@ -726,6 +736,14 @@ impl NodeNetworkInterface {
let previous_entry = self.insert_node_entry(NodeLocator::new(node_id, network_path), node_template);
// A node inserted over another changes what its ID is fed by, which is simplest to relearn from scratch
if previous_entry.is_some() {
self.unload_outward_wires(network_path);
} else {
let output_count = self.number_of_outputs(&node_id, network_path);
self.update_outward_wires_for_outputs(network_path, &node_id, 0, output_count);
}
self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
self.unload_node_click_targets(&node_id, network_path);
@@ -820,19 +838,29 @@ impl NodeNetworkInterface {
// Prune this network's pinned display order down to the nodes that still exist
let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::<HashSet<_>>());
// Read from the network rather than from the removal, which reports a template that a node missing its metadata cannot form
let removed_nodes: HashSet<NodeId> = surviving_nodes.as_ref().map_or_else(HashSet::new, |surviving| delete_nodes.difference(surviving).copied().collect());
if let Some(surviving_nodes) = surviving_nodes
&& let Some(mut network) = self.network_mut(network_path)
{
network.retain_pinned(|node_id| surviving_nodes.contains(node_id));
}
// Purge the deleted nodes' cached wire paths, which the per-node unload can no longer reach
// Purge the removed nodes' cached wire paths, which the per-node unload can no longer reach
if let Some(network_metadata) = self.network_metadata(network_path) {
network_metadata
.transient_metadata
.wires
.borrow_mut()
.retain(|connector, _| connector.node_id().is_none_or(|node_id| !delete_nodes.contains(&node_id)));
.retain(|connector, _| connector.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
}
// Their outputs leave the outward wire cache with them
if let Some(transient) = self.network_transient_mut(network_path)
&& let Some(outward_wires) = transient.outward_wires.get_loaded_mut()
{
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
}
self.unload_all_nodes_bounding_box(network_path);
@@ -847,13 +875,8 @@ impl NodeNetworkInterface {
/// Removes all references to the node with the given id from the network, and reconnects the input to the node below.
pub fn remove_references_from_network(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
// A preview of the node being removed cannot outlive it. A preview of any other node is untouched:
// previewing does not rewire anything, so the reconnection below cannot invalidate it.
if matches!(self.previewing(network_path), Previewing::Yes { previewed } if previewed.node_id == *node_id)
&& let Some(mut network) = self.network_mut(network_path)
{
network.set_previewing(Previewing::No);
}
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
self.stop_previewing(network_path);
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
@@ -920,6 +943,34 @@ impl NodeNetworkInterface {
true
}
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
let Some(mut network) = self.network_mut(network_path) else {
log::error!("Could not get nested network_metadata in start_previewing_without_restore");
return;
};
network.set_previewing(Previewing::Yes { root_node_to_restore: None });
}
fn stop_previewing(&mut self, network_path: &[NodeId]) {
if let Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
} = self.previewing(network_path)
{
self.set_input(
&InputConnector::Export(0),
NodeInput::node(root_node_to_restore.node_id, root_node_to_restore.output_index),
network_path,
);
}
let Some(mut network) = self.network_mut(network_path) else {
log::error!("Could not get nested network_metadata in stop_previewing");
return;
};
network.set_previewing(Previewing::No);
}
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_display_name");
@@ -1113,19 +1164,87 @@ impl NodeNetworkInterface {
self.load_structure();
}
/// Renders `toggle_id` instead of the network's export, or stops doing so if it already is.
///
/// Per-peer and not a change to the document: the export keeps whatever it is wired to, and the
/// compile path substitutes the previewed node into the graph it evaluates, so no other peer sees it.
pub fn toggle_preview(&mut self, toggle_id: NodeId, network_path: &[NodeId]) {
let previewing = match self.previewing(network_path) {
Previewing::Yes { previewed } if previewed.node_id == toggle_id => Previewing::No,
_ => Previewing::Yes {
previewed: RootNode { node_id: toggle_id, output_index: 0 },
},
let Some(network) = self.nested_network(network_path) else {
return;
};
// If new_export is None then disconnect
let mut new_export = None;
let mut new_previewing_state = Previewing::No;
if let Some(export) = network.exports.first() {
// If there currently an export
if let NodeInput::Node { node_id, output_index, .. } = export {
let previous_export_id = *node_id;
let previous_output_index = *output_index;
// The export is clicked
if *node_id == toggle_id {
// If the current export is clicked and is being previewed end the preview and set either export back to root node or disconnect
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
new_export = root_node_to_restore.map(|root_node| root_node.to_connector());
new_previewing_state = Previewing::No;
}
// The export is clicked and there is no preview
else {
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
// The export is not clicked
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
// There is currently a dashed line being drawn
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
// There is also a solid line being drawn
if let Some(root_node_to_restore) = root_node_to_restore {
// If the node with the solid line is clicked, then start previewing that node without restore
if root_node_to_restore.node_id == toggle_id {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
} else {
// Root node to restore does not change
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
};
}
}
// There is a dashed line without a solid line.
else {
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
}
// Not previewing, there is no dashed line being drawn
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
}
// The primary export is disconnected, so preview the node with nothing to restore, which disconnects the export again when the preview ends
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
}
match new_export {
Some(new_export) => {
self.create_wire(&new_export, &InputConnector::Export(0), network_path);
}
None => {
self.disconnect_input(&InputConnector::Export(0), network_path);
}
}
let Some(mut network) = self.network_mut(network_path) else { return };
network.set_previewing(previewing);
network.set_previewing(new_previewing_state);
}
}
@@ -22,20 +22,6 @@ impl NodeNetworkInterface {
pub fn document_network(&self) -> &NodeNetwork {
self.network.network()
}
/// The document network as it should be evaluated, which is the document itself with the previewed
/// node substituted for the export.
pub fn network_to_evaluate(&self) -> NodeNetwork {
let mut network = self.document_network().clone();
if let Previewing::Yes { previewed } = self.previewing(&[])
&& let Some(export) = network.exports.first_mut()
{
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
network
}
/// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else {
@@ -8,14 +8,14 @@
use std::collections::{BTreeMap, HashMap};
use document_graph_storage::attr::session;
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position};
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
@@ -96,8 +96,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
self.input_persistent(network_path, local_id, input_index)?.widget_override.as_deref()
}
fn input_data(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
self.input_persistent(network_path, local_id, input_index).map(|p| p.input_data.clone()).unwrap_or_default()
fn input_data(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> HashMap<String, Value> {
self.input_persistent(network_path, local_id, input_index)
.map(|p| p.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
}
fn output_names(&self, network_path: &[NodeId], local_id: NodeId) -> Vec<String> {
@@ -124,14 +126,14 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
impl DocumentSettings<'_> {
/// Serialize the per-peer view settings into the `ui::doc::*`-keyed map persisted in `session.json`
/// (via `Gdd::set_view_settings`). A field that fails to serialize is skipped, not fatal.
pub fn to_view_map(&self) -> BTreeMap<String, serde_json::Value> {
pub fn to_view_map(&self) -> BTreeMap<String, Value> {
let entries = [
(session::doc::PTZ, serde_json::to_value(self.document_ptz)),
(session::doc::RENDER_MODE, serde_json::to_value(self.render_mode)),
(session::doc::OVERLAYS, serde_json::to_value(self.overlays_visibility)),
(session::doc::RULERS_VISIBLE, serde_json::to_value(self.rulers_visible)),
(session::doc::SNAPPING, serde_json::to_value(self.snapping_state)),
(session::doc::COLLAPSED, serde_json::to_value(self.collapsed)),
(session::doc::PTZ, to_value(self.document_ptz)),
(session::doc::RENDER_MODE, to_value(self.render_mode)),
(session::doc::OVERLAYS, to_value(self.overlays_visibility)),
(session::doc::RULERS_VISIBLE, to_value(&self.rulers_visible)),
(session::doc::SNAPPING, to_value(self.snapping_state)),
(session::doc::COLLAPSED, to_value(self.collapsed)),
];
entries
@@ -201,7 +203,7 @@ pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> Has
pub fn collect_network_view_settings(
interface: &NodeNetworkInterface,
network_ids: &HashMap<Vec<NodeId>, document_graph_storage::NetworkId>,
) -> BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, serde_json::Value>> {
) -> BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, Value>> {
let mut out = BTreeMap::new();
for (network_path, &network_id) in network_ids {
@@ -215,21 +217,28 @@ pub fn collect_network_view_settings(
// of `session.json` (the `if !settings.is_empty()` guard below skips it entirely).
let mut settings = BTreeMap::new();
if navigation.node_graph_ptz != default_navigation.node_graph_ptz
&& let Ok(value) = serde_json::to_value(navigation.node_graph_ptz)
&& let Ok(value) = to_value(&navigation.node_graph_ptz)
{
settings.insert(session::network::NAV_PTZ.to_string(), value);
}
if navigation.node_graph_to_viewport != default_navigation.node_graph_to_viewport
&& let Ok(value) = serde_json::to_value(navigation.node_graph_to_viewport)
&& let Ok(value) = to_value(&navigation.node_graph_to_viewport)
{
settings.insert(session::network::NAV_TRANSFORM.to_string(), value);
}
if navigation.node_graph_width != default_navigation.node_graph_width
&& let Ok(value) = serde_json::to_value(navigation.node_graph_width)
&& let Ok(value) = to_value(&navigation.node_graph_width)
{
settings.insert(session::network::NAV_WIDTH.to_string(), value);
}
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
&& let Ok(value) = to_value(&network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
if !settings.is_empty() {
out.insert(network_id, settings);
}
@@ -245,7 +254,7 @@ pub fn collect_network_view_settings(
pub fn apply_network_view_settings(
interface: &mut NodeNetworkInterface,
network_ids: &HashMap<Vec<NodeId>, document_graph_storage::NetworkId>,
network_view_settings: &BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, serde_json::Value>>,
network_view_settings: &BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, Value>>,
) {
for (network_path, network_id) in network_ids {
let Some(settings) = network_view_settings.get(network_id) else { continue };
@@ -254,20 +263,27 @@ pub fn apply_network_view_settings(
};
if let Some(value) = settings.get(session::network::NAV_PTZ)
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
&& let Ok(ptz) = from_value::<PTZ>(value)
{
navigation.node_graph_ptz = ptz;
}
if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
&& let Ok(transform) = serde_json::from_value(value.clone())
&& let Ok(transform) = from_value(value)
{
navigation.node_graph_to_viewport = transform;
}
if let Some(value) = settings.get(session::network::NAV_WIDTH)
&& let Ok(width) = serde_json::from_value(value.clone())
&& let Ok(width) = from_value(value)
{
navigation.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = from_value::<Previewing>(value)
&& let Some(mut network) = interface.network_mut(network_path)
{
network.set_previewing(previewing);
}
}
}
@@ -384,7 +400,7 @@ fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
input_name: entry.input_name.unwrap_or_default(),
input_description: entry.input_description.unwrap_or_default(),
widget_override: entry.widget_override,
input_data: entry.input_data,
input_data: entry.input_data.into_iter().map(|(key, value)| (key, value.into())).collect(),
},
}
}
@@ -96,6 +96,16 @@ impl NodeDeltas<'_> {
});
}
/// Records a snapshot for a node inside the network this one owns, for metadata that arrived with a
/// new nested network rather than describing this node.
fn snapshot_owned(&mut self, node_id: NodeId, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.owned_network_path(),
node_id,
metadata,
});
}
fn network_path(&self) -> Vec<NodeId> {
self.locator.network_path.to_vec()
}
@@ -293,7 +303,6 @@ impl NodeMut<'_> {
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
@@ -305,7 +314,6 @@ impl NodeMut<'_> {
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
@@ -347,13 +355,23 @@ impl NodeMut<'_> {
node: Box::new(self.node.clone()),
};
self.deltas.graph(delta);
let metadata = Box::new(self.metadata.clone());
self.deltas.snapshot(metadata);
// Only what the new implementation brought with it. A swap leaves the node's own metadata alone,
// and restating it would assert values this peer did not write, clobbering a concurrent rename.
let owned: Vec<_> = self
.metadata
.network_metadata
.iter()
.flat_map(|network_metadata| &network_metadata.persistent_metadata.node_metadata)
.map(|(child_id, child)| (*child_id, Box::new(child.persistent_metadata.clone())))
.collect();
for (child_id, metadata) in owned {
self.deltas.snapshot_owned(child_id, metadata);
}
}
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
@@ -362,7 +380,6 @@ impl NodeMut<'_> {
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
@@ -206,7 +206,7 @@ impl NodeNetworkInterface {
/// For a change expressed as an operation on the existing value rather than as a replacement of it,
/// which avoids copying the value out and back. The recorded delta still carries the whole result,
/// since the storage op is a whole-value write.
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue) -> bool) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in edit_input_value");
return false;
@@ -221,9 +221,18 @@ impl NodeNetworkInterface {
return false;
};
edit(&mut value);
// The edit reports whether it changed anything, rather than this comparing before and after.
// Comparing the values would mean copying one out, which is the copy this method exists to avoid,
// and comparing their memoized hashes would let a collision silently drop a real edit.
let changed = edit(&mut value);
drop(value);
// An edit that changes nothing still carries a timestamp, which would let it supersede a concurrent
// peer's real edit to the same input.
if !changed {
return true;
}
let input = slot.clone();
self.deltas.push(input_write_delta(connector, network_path, input));
true
@@ -338,16 +338,11 @@ impl RootNode {
}
}
/// Which node the node graph renders instead of the network's export.
///
/// Per-peer view state, not part of the document: the export keeps whatever it is wired to, and the
/// compile path substitutes the previewed node into the graph it evaluates. So previewing a node
/// changes nothing another peer would see.
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum Previewing {
Yes {
previewed: RootNode,
},
/// If there is a node to restore the connection to the export for, then it is stored in the option.
/// Otherwise, nothing gets restored and the primary export is disconnected.
Yes { root_node_to_restore: Option<RootNode> },
#[default]
No,
}
@@ -1,5 +1,6 @@
use super::{NodeNetworkInterface, NodeNetworkMetadata};
use super::{InputConnector, NodeNetworkInterface, NodeNetworkMetadata};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use std::collections::{HashMap, HashSet};
impl NodeNetworkInterface {
/// Checks the structural invariants between the document network and its parallel metadata tree at every nesting level.
@@ -9,8 +10,47 @@ impl NodeNetworkInterface {
pub fn validate_invariants(&self) -> Vec<String> {
let mut violations = Vec::new();
validate_network(self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
self.validate_outward_wires(&mut Vec::new(), &mut violations);
violations
}
/// A loaded outward wire cache must match a fresh computation from the network.
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, violations: &mut Vec<String>) {
let Some(network) = self.nested_network(path) else { return };
if let Some(computed) = self.compute_outward_wires(path)
&& let Some(network_metadata) = self.network_metadata(path)
{
network_metadata.transient_metadata.outward_wires.with_loaded(|cached| {
let outputs: HashSet<_> = cached.keys().chain(computed.keys()).collect();
for output in outputs {
let (cached_inputs, computed_inputs) = (cached.get(output), computed.get(output));
if cached_inputs.map(|inputs| wire_counts(inputs)) != computed_inputs.map(|inputs| wire_counts(inputs)) {
violations.push(format!(
"Outward wires of {output:?} in network {path:?} are cached as {cached_inputs:?} but the network holds {computed_inputs:?}"
));
}
}
});
}
for (node_id, node) in &network.nodes {
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
path.push(*node_id);
self.validate_outward_wires(path, violations);
path.pop();
}
}
}
}
/// How many times each input appears, since the cache lists an output's consumers in no particular order.
fn wire_counts(inputs: &[InputConnector]) -> HashMap<InputConnector, usize> {
let mut counts = HashMap::new();
for input in inputs {
*counts.entry(*input).or_insert(0) += 1;
}
counts
}
fn validate_network(network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: usize, violations: &mut Vec<String>) {
@@ -282,15 +282,19 @@ impl<'a, 'p> NetworkView<'a, 'p> {
}
/// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output.
///
/// Simply what the export is wired to: previewing renders a different node but does not rewire it.
pub fn root_node(&self) -> Option<RootNode> {
match self.network.exports.first() {
Some(NodeInput::Node { node_id, output_index, .. }) => Some(RootNode {
node_id: *node_id,
output_index: *output_index,
match &self.metadata.persistent_metadata.previewing {
Previewing::Yes { root_node_to_restore } => *root_node_to_restore,
Previewing::No => self.network.exports.first().and_then(|export| {
if let NodeInput::Node { node_id, output_index, .. } = export {
Some(RootNode {
node_id: *node_id,
output_index: *output_index,
})
} else {
None
}
}),
_ => None,
}
}
@@ -32,7 +32,7 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>",
),
("graphene_core::transform::Footprint", "graphene_core::transform::Footprint"),
("\"OptionalF64\":", "\"F64\":"),
("\"OptionalF64\":", "\"Number\":"),
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
("\"core_types::table::Table<", "\"core_types::list::List<"),
// The `GradientStops` type was renamed to `Gradient`; stale stored output names are cleared so the display falls back to the live type name
@@ -1185,9 +1185,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.collect();
for (node_id, network_path, old_inputs_count) in &transform_layers {
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
let _ = document.network_interface.outward_wires(network_path);
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
@@ -1205,8 +1202,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *old_inputs_count == 6 {
match old_inputs.get(2) {
Some(NodeInput::Value { tagged_value, exposed }) => {
if let TaggedValue::F64(radians) = *tagged_value.clone().into_inner() {
let degrees = NodeInput::value(TaggedValue::F64(radians.to_degrees()), *exposed);
if let TaggedValue::Number(radians) = *tagged_value.clone().into_inner() {
let degrees = NodeInput::value(TaggedValue::Number(radians.to_degrees()), *exposed);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), degrees, network_path);
}
}
@@ -1215,7 +1212,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// (which represented radians in the legacy format) reaches the now-degrees Rotation input correctly.
if let Some(multiply_node) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::multiply::IDENTIFIER)) {
let mut multiply_template = multiply_node.default_node_template();
multiply_template.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
multiply_template.inputs[1] = NodeInput::value(TaggedValue::Number(180. / PI), false);
let multiply_node_id = NodeId::new();
if let Some(transform_position) = document.network_interface.position(node_id, network_path) {
let multiply_position = transform_position + IVec2::new(-7, 1);
@@ -1250,7 +1247,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Image".into()))).then_some((*node_id, path)))
.collect();
for (node_id, network_path) in &image_layers {
let _ = document.network_interface.outward_wires(network_path);
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
@@ -1279,8 +1275,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.collect();
for (node_id, network_path, old_inputs) in &math_nodes {
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves wires from cache, as in the Transform pass above
let _ = document.network_interface.outward_wires(network_path);
let (operand_a, expression, operand_b) = (&old_inputs[0], &old_inputs[1], &old_inputs[2]);
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
@@ -1301,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
let inline_b_constant = match operand_b.as_value() {
Some(TaggedValue::F64(constant)) => Some(*constant),
Some(TaggedValue::Number(constant)) => Some(*constant),
_ => None,
};
let fx_expression = match &static_expression {
@@ -1336,7 +1330,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
} else {
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
let as_list_input = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::F64(value)) => NodeInput::value(TaggedValue::F64Array(vec![*value]), input.is_exposed()),
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
_ => input.clone(),
};
let Some(extend_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::graphic::extend::IDENTIFIER)) else {
@@ -1430,9 +1424,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.collect();
for (node_id, network_path) in &old_text_nodes {
// Pre-load `outward_wires` so the splice below resolves the original downstream wiring from cache rather than a mutated state.
let _ = document.network_interface.outward_wires(network_path);
// Convert the old node in place to the current `text` node (12 inputs), capturing its old inputs.
let Some(text_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER)) else {
continue;
@@ -1532,7 +1523,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.iter()
.filter_map(|&index| {
let NodeInput::Value { tagged_value, exposed } = node.inputs.get(index)? else { return None };
let TaggedValue::F64(value) = &**tagged_value else { return None };
let TaggedValue::Number(value) = &**tagged_value else { return None };
Some((*node_id, path.clone(), index, *value as i64, *exposed))
})
.collect::<Vec<_>>()
@@ -1541,21 +1532,22 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
for (node_id, network_path, index, integer, exposed) in fractional_value_inputs {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::I64(integer), exposed), &network_path);
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
document.network_interface.discard_deltas();
document.require_whole_document_stage();
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let lengths = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(lengths) => lengths.clone(),
TaggedValue::F64(length) => vec![*length],
TaggedValue::Numbers(lengths) => lengths.clone(),
TaggedValue::Number(length) => vec![*length],
TaggedValue::String(text) => graphene_std::core_types::misc::parse_f64_list(text),
_ => return None,
};
@@ -1566,8 +1558,8 @@ fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let values = match &*tagged_value.clone().into_inner() {
TaggedValue::F64Array(values) => values.clone(),
TaggedValue::F64(value) => vec![*value],
TaggedValue::Numbers(values) => values.clone(),
TaggedValue::Number(value) => vec![*value],
_ => return None,
};
Some(NodeInput::value(TaggedValue::BoxCorners(values), *exposed))
@@ -1636,6 +1628,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let mut inputs_count = node.inputs.len();
// The expression nodes gained an output-type input, a type witness the Properties panel edits. A node from before it
// takes the definition's default choice, Number, which is the output type every such node had.
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
let definition = resolve_document_node_type(&reference)?;
let mut template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
inputs_count = 3;
}
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
@@ -1655,8 +1661,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// A sub-node is kept if its input is exposed/wired (so the user can drive it from the graph) OR if its value differs from the default
let keep_blend_mode = blend_mode_input.is_exposed() || !matches!(blend_mode_input.as_value(), Some(TaggedValue::BlendMode(BlendMode::Normal)));
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
let keep_clip = clip_input.is_exposed() || !matches!(clip_input.as_value(), Some(TaggedValue::Bool(false)));
// Find the downstream connection so we can chain new nodes between this node and downstream
@@ -1802,7 +1808,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::F64(100.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::Number(100.), false), network_path);
inputs_count = 5;
}
@@ -2148,9 +2154,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
// Line height and character spacing were hardcoded to 1 in the era before they became inputs
let hardcoded_to_one = || NodeInput::value(TaggedValue::F64(1.), false);
let hardcoded_to_one = || NodeInput::value(TaggedValue::Number(1.), false);
// Zero is how an absent `Option<f64>` maximum reads to the split below
let unset_maximum = || NodeInput::value(TaggedValue::F64(0.), false);
let unset_maximum = || NodeInput::value(TaggedValue::Number(0.), false);
let upgraded_inputs = [
old_inputs[0].clone(),
@@ -2164,7 +2170,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
old_inputs
.get(8)
.cloned()
.unwrap_or_else(|| NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)),
.unwrap_or_else(|| NodeInput::value(TaggedValue::Number(TypesettingConfig::default().letter_tilt), false)),
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false),
old_inputs.get(9).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(false), false)),
];
@@ -2191,7 +2197,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// The old `Option<f64>` maximum becomes a bool plus a value, with zero standing in for the absent option.
// A wired maximum has no value to read, so it keeps its connection and counts as present.
let split_maximum = |input: &NodeInput| match input.as_value() {
Some(&TaggedValue::F64(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::F64(if maximum == 0. { 100. } else { maximum }), false)),
Some(&TaggedValue::Number(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::Number(if maximum == 0. { 100. } else { maximum }), false)),
_ => (true, input.clone()),
};
@@ -2314,7 +2320,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::F64(old_offset), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(old_offset), false), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[3].clone(), network_path);
}
@@ -2448,17 +2454,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let output_level = |index: usize, default: f64| match old_inputs.get(index).and_then(|input| input.as_value()) {
Some(TaggedValue::F64(percent)) => percent / 100.,
Some(TaggedValue::Number(percent)) => percent / 100.,
_ => default,
};
let (output_minimums, output_maximums) = (output_level(4, 0.), output_level(5, 1.));
for (index, input) in old_inputs.iter().take(6).enumerate() {
let input = match (index, input.as_value()) {
(2, Some(TaggedValue::F64(percent))) => {
(2, Some(TaggedValue::Number(percent))) => {
// The old node's midtones-to-gamma mapping, from https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
let midtones = output_minimums + (output_maximums - output_minimums) * percent / 100.;
let gamma = if midtones < 0.5 { 1. + 9. * (1. - midtones * 2.) } else { ((1. - midtones) * 2.).max(0.01) };
NodeInput::value(TaggedValue::F64(gamma.clamp(0.01, 9.99)), input.is_exposed())
NodeInput::value(TaggedValue::Number(gamma.clamp(0.01, 9.99)), input.is_exposed())
}
_ => input.clone(),
};
@@ -2513,7 +2519,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(0.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(0.), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
@@ -2568,7 +2574,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let new_spacing_value = NodeInput::value(TaggedValue::PointSpacingType(graphene_std::vector::misc::PointSpacingType::Separation), false);
let new_quantity_value = NodeInput::value(TaggedValue::I64(100), false);
let new_quantity_value = NodeInput::value(TaggedValue::Integer(100), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), new_spacing_value, network_path);
@@ -2587,9 +2593,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.input_from_connector(&InputConnector::Node { node_id: *node_id, input_index: 3 }, network_path)?;
if let NodeInput::Value { tagged_value, exposed } = quantity_value
&& let TaggedValue::F64(value) = **tagged_value
&& let TaggedValue::Number(value) = **tagged_value
{
let new_quantity_value = NodeInput::value(TaggedValue::I64(value as i64), *exposed);
let new_quantity_value = NodeInput::value(TaggedValue::Integer(value as i64), *exposed);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), new_quantity_value, network_path);
}
}
@@ -2637,7 +2643,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
node_path.push(*node_id);
document.network_interface.add_import(TaggedValue::None, false, 0, "Primary", "", &node_path);
document.network_interface.add_import(TaggedValue::I64(0), false, 1, "Loop Level", "TODO", &node_path);
document.network_interface.add_import(TaggedValue::Integer(0), false, 1, "Loop Level", "TODO", &node_path);
}
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
@@ -2684,7 +2690,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(1.), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(1.), false), network_path);
}
// Upgrade the "Read Position" node to add the "Loop Level" input
@@ -2698,7 +2704,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::I64(0), false), network_path);
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Integer(0), false), network_path);
}
// Migrate from the old source/target v1 "Morph" node to the new `List<Vector>`-based v2 "Morph" node.
@@ -2791,7 +2797,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
return None;
};
let mut subtract_template = subtract_def.default_node_template();
subtract_template.inputs[1] = NodeInput::value(TaggedValue::F64(1.), false);
subtract_template.inputs[1] = NodeInput::value(TaggedValue::Number(1.), false);
let subtract_id = NodeId::new();
// Create Divide node: old_progression / (N-1) → new progression
@@ -3233,6 +3239,40 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
mod tests {
use super::*;
/// Runs the upgrades with the root wire cache loaded, the state a migration meets after its first rewire, and asserts the interface they leave behind is consistent.
fn migrate(document: &mut DocumentMessageHandler) {
migrate_with_context(document, "the migration");
}
fn migrate_with_context(document: &mut DocumentMessageHandler, context: &str) {
assert!(document.network_interface.outward_wires(&[]).is_some());
document_migration_upgrades(document, false);
let violations = document.network_interface.validate_invariants();
assert!(violations.is_empty(), "{context} left the interface inconsistent:\n{}", violations.join("\n"));
}
// Real documents drive every migration at once, on wiring no synthetic fixture reproduces
#[test]
fn demo_artwork_migrates_to_a_consistent_interface() {
use crate::messages::portfolio::document::storage_tests::test_support::load_demo;
let demo_artwork = [
"changing-seasons.graphite",
"isometric-fountain.graphite",
"marbled-mandelbrot.graphite",
"painted-dreams.graphite",
"parametric-dunescape.graphite",
"procedural-string-lights.graphite",
"red-dress.graphite",
"valley-of-spires.graphite",
];
for file_name in demo_artwork {
let mut document = load_demo(file_name);
migrate_with_context(&mut document, &format!("migrating {file_name}"));
}
}
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
#[test]
fn removed_definition_swap_targets_resolve() {
@@ -3267,12 +3307,12 @@ mod tests {
NodeInput::scope("editor-api"),
NodeInput::value(TaggedValue::String("Lorem".into()), false),
NodeInput::value(TaggedValue::Font(Font::new("Lato".to_string(), "Regular (400)".to_string())), false),
NodeInput::value(TaggedValue::F64(48.), false),
NodeInput::value(TaggedValue::F64(1.5), false),
NodeInput::value(TaggedValue::F64(2.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Number(48.), false),
NodeInput::value(TaggedValue::Number(1.5), false),
NodeInput::value(TaggedValue::Number(2.), false),
NodeInput::value(TaggedValue::Number(0.), false),
NodeInput::value(TaggedValue::Number(0.), false),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::value(TaggedValue::Bool(false), false),
];
@@ -3298,7 +3338,7 @@ mod tests {
);
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let network = document.network_interface.document_network();
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
@@ -3318,29 +3358,97 @@ mod tests {
);
let input_value = |index: usize| text_node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::F64(48.)), "shape {shape} lost its size");
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::Number(48.)), "shape {shape} lost its size");
if shape >= 6 {
assert_eq!(
input_value(graphene_std::text::text::LineHeightInput::INDEX),
Some(TaggedValue::F64(1.5)),
Some(TaggedValue::Number(1.5)),
"shape {shape} lost its line height"
);
assert_eq!(
input_value(graphene_std::text::text::LetterSpacingInput::INDEX),
Some(TaggedValue::F64(2.)),
Some(TaggedValue::Number(2.)),
"shape {shape} lost its letter spacing"
);
}
if shape >= 9 {
assert_eq!(
input_value(graphene_std::text::text::LetterTiltInput::INDEX),
Some(TaggedValue::F64(10.)),
Some(TaggedValue::Number(10.)),
"shape {shape} lost its letter tilt"
);
}
}
}
// An expression node saved before the output-type witness input had only its value and expression inputs
#[test]
fn expression_nodes_gain_the_output_type_witness() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
&[],
);
migrate(&mut document);
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
let node = &document.network_interface.document_network().nodes[&node_id];
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(node.inputs.len(), 3);
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
}
// The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
#[test]
fn expression_nodes_gaining_the_witness_keep_their_upstream_wire() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
let (source_id, node_id) = (NodeId(1), NodeId(2));
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(node_id, 0), NodeInput::node(source_id, 0), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.inputs.len(), 3);
assert!(
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
"the upstream wire was dropped by the upgrade, leaving {:?}",
node.inputs.first()
);
// The wire has to survive in the outward direction too, since a stale cache is what orphans it
let outward_wires = document.network_interface.outward_wires(&[]).and_then(|wires| wires.get(&OutputConnector::node(source_id, 0)).cloned());
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(node_id, 0)].as_slice()));
}
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
#[test]
@@ -3398,16 +3506,21 @@ mod tests {
let inputs = vec![
NodeInput::node(source_a_id, 0),
NodeInput::value(TaggedValue::String("2 - 0.2A".into()), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::Number(0.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(node.inputs.len(), 2, "the old `B` input should be dropped");
assert_eq!(
node.inputs.len(),
3,
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
);
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
assert_eq!(node.inputs.get(2).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(0.)));
}
// A constant `B` inlines into the rewritten string as a parenthesized literal; an alias spelling of the old identifier also matches
@@ -3415,10 +3528,10 @@ mod tests {
let inputs = vec![
NodeInput::node(source_a_id, 0),
NodeInput::value(TaggedValue::String("sqrt(A + B) - B^2".into()), false),
NodeInput::value(TaggedValue::F64(3.), false),
NodeInput::value(TaggedValue::Number(3.), false),
];
let mut document = build_document("graphene_core::ops::MathNode", inputs);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
@@ -3437,7 +3550,7 @@ mod tests {
NodeInput::node(source_b_id, 0),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
@@ -3454,19 +3567,19 @@ mod tests {
// A wired expression cannot be inspected, so it splices too, wrapping unwired constant operands as one-item list values
{
let inputs = vec![
NodeInput::value(TaggedValue::F64(2.), true),
NodeInput::value(TaggedValue::Number(2.), true),
NodeInput::node(source_expression_id, 0),
NodeInput::value(TaggedValue::F64(5.), false),
NodeInput::value(TaggedValue::Number(5.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
let network = document.network_interface.document_network();
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::F64Array(vec![2.]), true)));
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::F64Array(vec![5.]), false)));
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::Numbers(vec![2.]), true)));
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::Numbers(vec![5.]), false)));
}
}
@@ -3479,7 +3592,7 @@ mod tests {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
node_template.inputs[1] = NodeInput::value(TaggedValue::F64(6.9), false);
node_template.inputs[1] = NodeInput::value(TaggedValue::Number(6.9), false);
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
@@ -3488,12 +3601,12 @@ mod tests {
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::I64(6)),
Some(TaggedValue::Integer(6)),
"the count truncates as the retired Floor did, so the document keeps drawing six"
);
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
@@ -3518,15 +3631,15 @@ mod tests {
panic!("Blend should be a network node")
};
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::F64(42.), false);
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let DocumentNodeImplementation::Network(inner) = &document.network_interface.document_network().nodes[&node_id].implementation else {
panic!("Blend should stay a network node")
};
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::F64(42.)));
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
@@ -3538,27 +3651,27 @@ mod tests {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type("Regex Find").expect("Regex Find should exist").default_node_template();
node_template.inputs[2] = NodeInput::value(TaggedValue::F64(1.6), false);
node_template.inputs[2] = NodeInput::value(TaggedValue::Number(1.6), false);
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Regex Find should be a network node")
};
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::F64(0.), false);
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
node.inputs.get(2).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::I64(1)),
Some(TaggedValue::Integer(1)),
"the match index truncates as the retired cast did"
);
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
panic!("Regex Find should stay a network node")
};
assert_eq!(inner.nodes[&NodeId(0)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::I64(0)));
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Integer(0)));
}
#[test]
@@ -3585,7 +3698,7 @@ mod tests {
document.network_interface.insert_node(image_id, image_template, &[]);
document.network_interface.set_input(&InputConnector::node_at_index(image_id, 0), legacy_input.clone(), &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let image_node = &document.network_interface.document_network().nodes[&image_id];
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
@@ -3616,7 +3729,7 @@ mod tests {
};
document.network_interface.insert_node(node_id, image_template, &[]);
document_migration_upgrades(&mut document, false);
migrate(&mut document);
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[1];
assert_eq!(migrated.as_value(), Some(&TaggedValue::TypeDefault(item!(Resource))), "the bare default should become the item default");
@@ -1,215 +1,359 @@
//! Asynchronous `.gdd` working-copy IO, spawned by `PortfolioMessageHandler` as `FutureMessage`s:
//! building/opening containers and opening `.gdd` archives into documents.
//! The `validate` flag is the `validate_storage_round_trip` preference; when
//! set, the registry build is compared against the legacy oracle (logged, not fatal) for the soak.
use document_container::AnyContainer;
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout};
use document_graph_storage::Declarations;
use graph_craft::application_io::resource::ResourceStorage;
use graph_craft::document::NodeNetwork;
//! Document store I/O spawned by `PortfolioMessageHandler` as `FutureMessage`s. A future writes only into a
//! container no registered document owns yet; the message loop is the sole writer once a document is
//! registered, and a completion for a document closed meanwhile removes the store entry.
use super::document::DocumentMessageHandler;
use super::document::diff_networks;
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::document::utility_types::error::EditorError;
use super::document::utility_types::network_interface::OutputConnector;
use super::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, build_interface_from_storage, network_ids_from_entries};
use super::document_migration::document_migration_string_preprocessing;
use super::document_migration::*;
use super::portfolio_message::PortfolioMessage;
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::messages::message::Message;
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
use crate::messages::resource_storage::ResourcesHandle;
use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
use document_container::{AnyContainer, AsyncContainer};
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
use document_graph_storage::{Declarations, PeerId};
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
use std::path::PathBuf;
use std::sync::Arc;
/// Build the container backend at `path` (folder on native, OPFS directory name on web) or in-memory
/// when `None`. Also returns whether an existing working copy was found (its `manifest.json` is present).
async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<(AnyContainer, bool), DocumentFormatError> {
let Some(path) = path else {
return Ok((AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new()), false));
};
#[derive(Clone)]
pub struct DocumentStoreHandle(Arc<dyn DocumentStore>);
#[cfg(not(target_family = "wasm"))]
{
use document_container::backends::folder::FolderBackend;
let exists = path.join("manifest.json").is_file();
let backend = if exists { FolderBackend::open(path)? } else { FolderBackend::create(path)? };
Ok((AnyContainer::Folder(backend), exists))
}
#[cfg(target_family = "wasm")]
{
use document_container::AsyncContainer;
use document_container::backends::opfs::OpfsBackend;
let directory_name = path
.to_str()
.ok_or(DocumentFormatError::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
let backend = OpfsBackend::open(directory_name).await?;
let exists = backend.exists("manifest.json").await;
Ok((AnyContainer::Opfs(backend), exists))
impl DocumentStoreHandle {
pub fn new(store: Arc<dyn DocumentStore>) -> Self {
Self(store)
}
}
/// Open the existing working copy at `path`, or create a fresh one bound to `peer` (in-memory when
/// `path` is `None`). Returns the working copy plus whether it was reopened (vs freshly created); only a
/// reopen has independently-stored state worth comparing against the legacy load.
pub(super) async fn build_or_open_working_copy(
path: Option<&std::path::Path>,
peer: document_graph_storage::PeerId,
document_uuid: u64,
version: String,
) -> Result<(GddV1, bool), DocumentFormatError> {
let (container, exists) = build_per_document_container(path).await?;
impl std::ops::Deref for DocumentStoreHandle {
type Target = dyn DocumentStore;
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
fn deref(&self) -> &(dyn DocumentStore + 'static) {
self.0.as_ref()
}
}
impl Default for DocumentStoreHandle {
fn default() -> Self {
Self(Arc::new(MemoryStore::default()))
}
}
impl std::fmt::Debug for DocumentStoreHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DocumentStoreHandle").finish_non_exhaustive()
}
}
pub(crate) fn document_key(document_id: DocumentId) -> DocumentKey {
DocumentKey(document_id.0)
}
pub(crate) fn legacy_path() -> &'static str {
GddV1Layout.legacy_path()
}
pub(super) async fn list_stored_documents(store: DocumentStoreHandle) -> Message {
let document_ids = match store.list().await {
Ok(keys) => Some(keys.into_iter().map(|key| DocumentId(key.0)).collect()),
Err(error) => {
log::error!("Listing the document store failed: {error}");
None
}
};
PortfolioMessage::StoredDocumentsListed { document_ids }.into()
}
pub(super) async fn load_stored_document(store: DocumentStoreHandle, document_id: DocumentId, resources: ResourcesHandle, reset_nodes: bool, legacy_only: bool) -> Message {
let (document, gdd) = match store.open(document_key(document_id)).await {
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes, legacy_only).await,
Err(error) => {
log::error!("Opening the stored document {document_id:?} failed: {error}");
(None, None)
}
};
let declarations = load_declarations(gdd.as_ref(), &resources).await;
PortfolioMessage::StoredDocumentLoaded {
document_id,
document: document.map(Box::new),
gdd: gdd.map(Box::new),
declarations,
}
.into()
}
/// Opens the container for a document created in this session.
pub(super) async fn attach_container(store: DocumentStoreHandle, document_id: DocumentId, resources: ResourcesHandle, legacy_only: bool) -> Message {
let container = match store.open(document_key(document_id)).await {
Ok(container) => container,
Err(error) => {
log::error!("Opening storage for {document_id:?} failed: {error}");
return PortfolioMessage::StorageAttached {
document_id,
container: None,
gdd: None,
declarations: Declarations::new(),
}
.into();
}
};
let gdd = if !legacy_only {
open_storage_or_fallback_to_legacy(container.clone(), document_id).await
} else {
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
None
};
Ok((gdd, exists))
let declarations = load_declarations(gdd.as_ref(), &resources).await;
PortfolioMessage::StorageAttached {
document_id,
container: Some(container),
gdd: gdd.map(Box::new),
declarations,
}
.into()
}
/// `FutureMessage` that opens a `.gdd` archive into a document, delivered via
/// [`PortfolioMessage::GddDocumentLoaded`]. See [`build_document_from_gdd`] for the build itself.
pub(super) async fn open_gdd_document(
working_copy_root: Option<std::path::PathBuf>,
/// Opens the storage of a document that already has its container.
pub(super) async fn open_storage(container: AnyContainer, document_id: DocumentId, resources: ResourcesHandle) -> Message {
let gdd = open_storage_or_fallback_to_legacy(container.clone(), document_id).await;
let declarations = load_declarations(gdd.as_ref(), &resources).await;
PortfolioMessage::StorageAttached {
document_id,
container: Some(container),
gdd: gdd.map(Box::new),
declarations,
}
.into()
}
pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_id: DocumentId) -> Message {
if let Err(error) = store.remove(document_key(document_id)).await {
log::error!("Removing the stored document {document_id:?} failed: {error}");
}
Message::NoOp
}
/// Materializes a `.gdd` archive into a fresh store container and loads it like a stored document.
pub(super) async fn open_document_file(
store: DocumentStoreHandle,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<std::path::PathBuf>,
document_path: Option<PathBuf>,
content: Vec<u8>,
store_handle: ResourcesHandle,
validate: bool,
resources: ResourcesHandle,
reset_nodes: bool,
legacy_only: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id, validate).await;
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
let materialized = async {
let mut container = store.open(document_key(document_id)).await.map_err(|error| error.to_string())?;
document_container::archive::open_auto(&content, &mut container).map_err(|error| error.to_string())?;
Ok::<_, String>(container)
}
.await;
let (document, gdd) = match materialized {
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes, legacy_only).await,
Err(error) => {
log::error!("Opening the document archive for {document_id:?} failed: {error}");
(None, None)
}
};
let declarations = load_declarations(gdd.as_ref(), &resources).await;
PortfolioMessage::DocumentFileLoaded {
document_id,
document_name,
document_path,
document: document.map(Box::new),
})
gdd: gdd.map(Box::new),
declarations,
}
.into()
}
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
/// Returns `None` only if neither the build nor the legacy fallback worked.
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
let (container, _exists) = match build_per_document_container(path).await {
Ok(result) => result,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build working copy container: {error}");
/// Builds the document from its legacy file, or from its storage when that file is missing or unreadable.
async fn load_from_container(container: AnyContainer, document_id: DocumentId, resources: &ResourcesHandle, reset_nodes: bool, legacy_only: bool) -> (Option<DocumentMessageHandler>, Option<GddV1>) {
let legacy = match container.read(legacy_path()).await {
Ok(bytes) => String::from_utf8(bytes.as_slice().to_vec())
.map_err(|error| error.to_string())
.and_then(|text| load_legacy_document(text, resources, reset_nodes).map_err(|error| error.to_string())),
Err(error) => Err(error.to_string()),
};
match legacy {
Ok(mut document) => {
document.set_auto_save_state(true);
document.container = Some(container.clone());
let gdd = if !legacy_only { open_storage_or_fallback_to_legacy(container, document_id).await } else { None };
(Some(document), gdd)
}
Err(legacy_error) => {
let gdd = match GddV1::open_in(container.clone(), GddV1Layout).await {
Ok(gdd) => gdd,
Err(storage_error) => {
log::error!("Loading {document_id:?} failed. Legacy: {legacy_error}. Storage: {storage_error}");
return (None, None);
}
};
log::warn!("Recovering {document_id:?} from storage because its legacy file could not load: {legacy_error}");
let Some(mut document) = build_document_from_storage(gdd, resources, document_id).await else {
return (None, None);
};
document.container = Some(container);
if legacy_only {
document.clear_storage();
}
(Some(document), None)
}
}
}
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId) -> Option<GddV1> {
match GddV1::open_in(container.clone(), GddV1Layout).await {
Ok(gdd) => return Some(gdd),
Err(DocumentFormatError::MissingManifest) => {}
// Container I/O and newer-format errors keep the existing files; anything else is broken data the legacy document replaces.
Err(error @ (DocumentFormatError::Container(_) | DocumentFormatError::Read(ReadError::Container(_)) | DocumentFormatError::UnsupportedVersion { .. })) => {
log::error!("Opening storage for {document_id:?} failed: {error}");
return None;
}
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
Err(error) => log::warn!("Storage for {document_id:?} is unusable and will be rebuilt from the legacy document: {error}"),
}
let version = GRAPHITE_GIT_COMMIT_HASH.to_string();
let created = async {
for path in container.list("").await? {
if path != legacy_path() {
container.remove(&path).await?;
}
}
};
GddV1::create_in(container, GddV1Layout, PeerId(generate_uuid()), document_id.0, version.clone(), version)
}
.await;
match created {
Ok(gdd) => Some(gdd),
Err(error) => {
log::error!("Creating storage for {document_id:?} failed: {error}");
None
}
}
}
// Extract archived resource bytes into the global cache so declarations + runtime resolve.
/// Decoded proto-node declarations for every node `gdd` or its history references, from the global cache.
async fn load_declarations(gdd: Option<&GddV1>, resources: &ResourcesHandle) -> Declarations {
match gdd {
Some(gdd) => gdd.declarations(resources).await,
None => Declarations::new(),
}
}
/// Storage session -> runtime interface. Resources stored in the container are hydrated into the global cache first.
async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, document_id: DocumentId) -> Option<DocumentMessageHandler> {
match gdd.resource_hashes().await {
Ok(hashes) => {
for hash in hashes {
match gdd.read_resource(&hash).await {
Ok(holder) => {
store_handle.store(holder.as_slice());
byte_store.store(holder.as_slice());
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to read resource {hash}: {error}"),
Err(error) => log::error!("Opening document {document_id:?}: failed to read resource {hash}: {error}"),
}
}
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
Err(error) => log::error!("Opening document {document_id:?}: failed to list resources: {error}"),
}
let legacy_document = gdd
.read_legacy_document()
.await
.and_then(|holder| String::from_utf8(holder.as_slice().to_vec()).ok())
.and_then(|serialized| DocumentMessageHandler::deserialize_document(&document_migration_string_preprocessing(serialized)).ok());
let declarations = gdd.declarations(store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => {
let network_ids = network_ids_from_entries(&network_entries);
match build_interface_from_storage(network, node_entries, network_entries) {
Ok(mut interface) => {
// Per-network view state lives in `session.json`, not the registry, so restore it here.
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
Some(interface)
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build interface: {error}");
None
}
}
}
let declarations = gdd.declarations(byte_store).await;
let (network, node_entries, network_entries) = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok(result) => result,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
None
log::error!("Opening document {document_id:?}: failed to convert registry to runtime: {error}");
return None;
}
};
// Soak compare against the legacy oracle, normalizing the benign generic-vs-resolved `call_argument`.
if let Some(interface) = interface {
if validate && let Some(legacy) = &legacy_document {
let mut built = interface.document_network().clone();
let mut oracle = legacy.network_interface.document_network().clone();
normalize_call_arguments_for_compare(&mut built);
normalize_call_arguments_for_compare(&mut oracle);
if built != oracle {
log::error!(
"Open-.gdd divergence for {document_id:?}: registry-built document differs from the embedded legacy blob\n{}",
diff_networks(&oracle, &built)
);
}
let network_ids = network_ids_from_entries(&network_entries);
let mut interface = match build_interface_from_storage(network, node_entries, network_entries) {
Ok(interface) => interface,
Err(error) => {
log::error!("Opening document {document_id:?}: failed to build interface: {error}");
return None;
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None));
}
};
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
if legacy_document.is_none() {
log::error!("Opening .gdd for {document_id:?}: no embedded legacy document to fall back to");
}
legacy_document
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
document.finalize_storage_load();
Some(document)
}
/// Soak check that the reopened `.gdd`'s stored registry, converted back to a runtime network, matches
/// the legacy load. Logs divergence only (legacy stays authoritative); runs once per open.
pub(super) fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, declarations: &Declarations, document_id: DocumentId) {
let mut candidate = match gdd.registry().to_runtime_with_metadata(declarations) {
Ok((network, _entries)) => network,
Err(error) => {
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
/// Deserializes a legacy `.graphite` document, running the migrations and importing its embedded resources.
pub(super) fn load_legacy_document(document_serialized_content: String, byte_store: &impl ResourceStorage, reset_node_definitions_on_open: bool) -> Result<DocumentMessageHandler, EditorError> {
// Upgrade the document being opened to use fresh copies of all nodes
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Upgrade resources from being referend by hash to beeing referened by ID
let (document_serialized_content, resource_hash_to_id_migration_map) = document_migration_replace_resources_referenced_by_hash(document_serialized_content);
let mut document = DocumentMessageHandler::deserialize_document(&document_serialized_content)?;
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
// Load the document's embedded resources into the resource storage
std::mem::take(&mut document.resources.embedded).into_iter().for_each(|(hash, resource)| {
let data: Arc<[u8]> = Arc::from(resource.as_ref());
if ResourceHash::from(data.as_ref()) != hash {
log::error!("Resource hash mismatch for resource with hash {hash}");
return;
}
};
byte_store.store(&data);
// Normalize the benign generic-vs-resolved `call_argument` on both sides before comparing.
let mut legacy = legacy_network.clone();
normalize_call_arguments_for_compare(&mut legacy);
normalize_call_arguments_for_compare(&mut candidate);
if candidate != legacy {
log::error!(
"Compare-on-open divergence for {document_id:?}: the reopened .gdd does not match the legacy load\n{}",
diff_networks(&legacy, &candidate)
);
}
}
/// Recursively rewrite a concrete `Context` `call_argument` back to the generic `T` storage authored, so
/// the generic-vs-resolved difference (recomputed during compilation) compares equal. Other types untouched.
fn normalize_call_arguments_for_compare(network: &mut NodeNetwork) {
use graph_craft::Type;
let context = graph_craft::concrete!(graphene_std::Context);
for node in network.nodes.values_mut() {
if node.call_argument == context {
node.call_argument = Type::Generic(std::borrow::Cow::Borrowed("T"));
// TODO: Eventually remove this document upgrade code
// Register any resources that were previously referenced by hash
if let Some(id) = resource_hash_to_id_migration_map.get(&hash)
&& !document.resources.registry.contains(id)
{
document.resources.registry.resolve(id, hash);
document.resources.registry.push_source_back(id, DataSource::Embedded);
}
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
normalize_call_arguments_for_compare(inner);
});
// Ensure each node has the metadata for its inputs
for (node_id, node, path) in document.network_interface.document_network().clone().recursive_nodes() {
document.network_interface.validate_input_metadata(node_id, node, &path);
document.network_interface.validate_output_names(node_id, node, &path);
}
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
document.network_interface.load_structure();
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
for layer in all_layers {
let Some((downstream_node, input_index)) = document
.network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(layer.to_node())))
.and_then(|outward_wires| outward_wires.first())
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))
else {
continue;
};
// If the downstream node is a layer and the input is the first input and the current layer is not in a stack
if input_index == 0 && document.network_interface.is_layer(&downstream_node, &[]) && !document.network_interface.is_stack(&layer.to_node(), &[]) {
// Ensure the layer is horizontally aligned with the downstream layer to prevent changing the layout of old files
let (Some(layer_position), Some(downstream_position)) = (document.network_interface.position(&layer.to_node(), &[]), document.network_interface.position(&downstream_node, &[])) else {
log::error!("Could not get position for layer {:?} or downstream node {} when opening file", layer.to_node(), downstream_node);
continue;
};
if layer_position.x == downstream_position.x {
document.network_interface.set_stack_position_calculated_offset(&layer.to_node(), &downstream_node, &[]);
}
}
}
document.network_interface.discard_deltas();
document.require_whole_document_stage();
Ok(document)
}
@@ -2,29 +2,26 @@ use crate::consts::FILE_EXTENSION;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, FileFilter};
use crate::messages::layout::utility_types::layout_widget::DialogLayoutHolder;
use crate::messages::portfolio::persistent_state::PersistentStateMessage;
use crate::messages::portfolio::document_storage_io::{DocumentStoreHandle, document_key, legacy_path, remove_stored_document};
use crate::messages::prelude::*;
use document_container::AsyncContainer;
#[derive(ExtractField)]
pub struct FailedDocumentsMessageContext<'a> {
pub document_ids: &'a mut VecDeque<DocumentId>,
pub document_store: &'a DocumentStoreHandle,
}
#[derive(Debug, Default, ExtractField)]
pub struct FailedDocumentsMessageHandler {
/// Pairs of `(info, raw serialized content)` for autosaved documents that failed to deserialize.
/// The info entries are folded back into `persisted_state_snapshot` so their on-disk autosave files survive garbage collection.
/// Stored documents that failed to load. Their store entries stay until explicitly discarded.
// TODO: Eventually remove this document upgrade code
failed_to_load_documents: HashMap<DocumentId, (DocumentInfo, String)>,
/// In-flight count of autosaved-document loads from the initial startup batch; the batched failure dialog fires when this hits 0.
// TODO: Eventually remove this document upgrade code
pending_initial_autosave_loads: usize,
failed_to_load_documents: HashMap<DocumentId, DocumentInfo>,
}
#[message_handler_data]
impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> for FailedDocumentsMessageHandler {
fn process_message(&mut self, message: FailedDocumentsMessage, responses: &mut VecDeque<Message>, context: FailedDocumentsMessageContext) {
let FailedDocumentsMessageContext { document_ids } = context;
let FailedDocumentsMessageContext { document_store } = context;
match message {
// TODO: Eventually remove this document upgrade code
@@ -32,19 +29,15 @@ impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> f
if self.failed_to_load_documents.is_empty() {
return;
}
let failed_document_names = self.failed_to_load_documents.values().map(|(info, _)| display_name_with_fallback(info)).collect();
let failed_document_names = self.failed_to_load_documents.values().map(display_name_with_fallback).collect();
let dialog = simple_dialogs::FailedToLoadDocumentsDialog { failed_document_names };
dialog.send_dialog_to_frontend(responses);
}
// TODO: Eventually remove this document upgrade code
FailedDocumentsMessage::DiscardFailedToLoadDocuments => {
let failed = std::mem::take(&mut self.failed_to_load_documents);
for document_id in failed.keys() {
document_ids.retain(|id| id != document_id);
responses.add(PersistentStateMessage::DeleteDocument { document_id: *document_id });
for document_id in std::mem::take(&mut self.failed_to_load_documents).into_keys() {
responses.add(remove_stored_document(document_store.clone(), document_id));
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(PersistentStateMessage::WriteState);
}
// TODO: Eventually remove this document upgrade code
FailedDocumentsMessage::DownloadFailedToLoadDocuments => {
@@ -52,60 +45,22 @@ impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> f
return;
}
let mut used_names = HashSet::new();
let files: Vec<(String, Vec<u8>)> = self
.failed_to_load_documents
.values()
.map(|(info, content)| {
let stem = sanitize_filename_stem(&info.name).unwrap_or_else(|| format!("document-{:x}", info.id.0));
// A name that was already given out, even as another document's numbered copy, takes the next free number
let mut unique = format!("{stem}.{FILE_EXTENSION}");
let mut copy_number = 1;
while !used_names.insert(unique.clone()) {
unique = format!("{stem} ({copy_number}).{FILE_EXTENSION}");
copy_number += 1;
}
(unique, content.as_bytes().to_vec())
})
.collect();
const FOLDER_NAME: &str = "Graphite Recovered Documents";
if files.len() == 1 {
let (filename, content) = files.into_iter().next().expect("just checked there's one entry");
responses.add(FrontendMessage::TriggerSaveFile {
name: filename,
folder: None,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![FILE_EXTENSION.into()],
mime_types: Vec::new(),
}],
content: serde_bytes::ByteBuf::from(content),
});
} else {
match build_recovery_zip(&files) {
Ok(zip_bytes) => responses.add(FrontendMessage::TriggerSaveFile {
name: format!("{FOLDER_NAME}.zip"),
folder: None,
filters: vec![FileFilter {
name: "Zip Archive".into(),
extensions: vec!["zip".into()],
mime_types: Vec::new(),
}],
content: serde_bytes::ByteBuf::from(zip_bytes),
}),
Err(e) => {
log::error!("Failed to build recovery zip: {e}");
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to download".to_string(),
description: format!("Could not bundle the failed documents for download.\n\n{e}"),
});
let files = recovery_file_names(self.failed_to_load_documents.values());
let store = document_store.clone();
responses.add(async move {
let mut entries = Vec::new();
for (document_id, filename) in files {
let content = match store.open(document_key(document_id)).await {
Ok(container) => container.read(legacy_path()).await.map(|bytes| bytes.as_slice().to_vec()),
Err(error) => Err(error),
};
match content {
Ok(bytes) => entries.push((filename, bytes)),
Err(error) => log::error!("Reading the stored document {document_id:?} for recovery failed: {error}"),
}
}
}
recovery_download(entries)
});
}
}
}
@@ -115,39 +70,8 @@ impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> f
impl FailedDocumentsMessageHandler {
// TODO: Eventually remove this document upgrade code
/// Keeps a document that failed to load, with its raw serialized content, so it can be offered for download.
pub(crate) fn record_failure(&mut self, document_id: DocumentId, info: DocumentInfo, serialized_content: String) {
self.failed_to_load_documents.insert(document_id, (info, serialized_content));
}
// TODO: Eventually remove this document upgrade code
/// Counts more autosaved documents of the startup batch whose loads the batched failure dialog waits for.
pub(crate) fn expect_autosave_loads(&mut self, count: usize) {
self.pending_initial_autosave_loads = self.pending_initial_autosave_loads.saturating_add(count);
}
// TODO: Eventually remove this document upgrade code
/// Whether documents failed to load and none of the startup batch is still loading, so the failure dialog is due.
pub(crate) fn has_failures_to_report(&self) -> bool {
self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty()
}
// TODO: Eventually remove this document upgrade code
/// The info of each document that failed to load.
pub(crate) fn failed_document_infos(&self) -> impl Iterator<Item = &DocumentInfo> {
self.failed_to_load_documents.values().map(|(info, _)| info)
}
// TODO: Eventually remove this document upgrade code
pub(crate) fn tick_autosave_load_progress(&mut self, responses: &mut VecDeque<Message>, failed: bool) {
if self.pending_initial_autosave_loads > 0 {
self.pending_initial_autosave_loads -= 1;
if self.has_failures_to_report() {
responses.add(FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog);
}
} else if failed {
responses.add(FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog);
}
pub(crate) fn record_failure(&mut self, document_id: DocumentId, info: DocumentInfo) {
self.failed_to_load_documents.insert(document_id, info);
}
}
@@ -160,6 +84,76 @@ fn display_name_with_fallback(info: &DocumentInfo) -> String {
}
}
// TODO: Eventually remove this document upgrade code
fn recovery_file_names<'a>(infos: impl Iterator<Item = &'a DocumentInfo>) -> Vec<(DocumentId, String)> {
let mut used_names = HashSet::new();
infos
.map(|info| {
let stem = sanitize_filename_stem(&info.name).unwrap_or_else(|| format!("document-{:x}", info.id.0));
// A name that was already given out, even as another document's numbered copy, takes the next free number
let mut unique = format!("{stem}.{FILE_EXTENSION}");
let mut copy_number = 1;
while !used_names.insert(unique.clone()) {
unique = format!("{stem} ({copy_number}).{FILE_EXTENSION}");
copy_number += 1;
}
(info.id, unique)
})
.collect()
}
// TODO: Eventually remove this document upgrade code
fn recovery_download(files: Vec<(String, Vec<u8>)>) -> Message {
const FOLDER_NAME: &str = "Graphite Recovered Documents";
if files.is_empty() {
return DialogMessage::DisplayDialogError {
title: "Failed to download".to_string(),
description: "None of the failed documents could be read from storage.".to_string(),
}
.into();
}
if files.len() == 1 {
let (filename, content) = files.into_iter().next().expect("just checked there's one entry");
return FrontendMessage::TriggerSaveFile {
name: filename,
folder: None,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![FILE_EXTENSION.into()],
mime_types: Vec::new(),
}],
content: serde_bytes::ByteBuf::from(content),
}
.into();
}
match build_recovery_zip(&files) {
Ok(zip_bytes) => FrontendMessage::TriggerSaveFile {
name: format!("{FOLDER_NAME}.zip"),
folder: None,
filters: vec![FileFilter {
name: "Zip Archive".into(),
extensions: vec!["zip".into()],
mime_types: Vec::new(),
}],
content: serde_bytes::ByteBuf::from(zip_bytes),
}
.into(),
Err(e) => {
log::error!("Failed to build recovery zip: {e}");
DialogMessage::DisplayDialogError {
title: "Failed to download".to_string(),
description: format!("Could not bundle the failed documents for download.\n\n{e}"),
}
.into()
}
}
}
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
// TODO: Eventually remove this document upgrade code
fn sanitize_filename_stem(name: &str) -> Option<String> {
@@ -229,25 +223,15 @@ mod tests {
use super::*;
#[test]
fn recovered_documents_sharing_a_name_with_a_numbered_copy_still_download() {
let mut handler = FailedDocumentsMessageHandler::default();
for (id, name) in [(1, "Art"), (2, "Art"), (3, "Art (1)")] {
let info = DocumentInfo {
id: DocumentId(id),
name: name.to_string(),
resources: None,
path: None,
is_saved: true,
};
handler.record_failure(DocumentId(id), info, "content".to_string());
}
fn recovered_documents_sharing_a_name_with_a_numbered_copy_get_distinct_file_names() {
let infos = [(1, "Art"), (2, "Art"), (3, "Art (1)")].map(|(id, name)| DocumentInfo {
id: DocumentId(id),
name: name.to_string(),
path: None,
is_saved: true,
});
let mut document_ids = VecDeque::new();
let mut responses = VecDeque::new();
let context = FailedDocumentsMessageContext { document_ids: &mut document_ids };
handler.process_message(FailedDocumentsMessage::DownloadFailedToLoadDocuments, &mut responses, context);
// A file name given out twice makes the archive fail to build, which shows an error dialog in place of the download
assert!(matches!(responses.front(), Some(Message::Frontend(FrontendMessage::TriggerSaveFile { .. }))));
let names: HashSet<_> = recovery_file_names(infos.iter()).into_iter().map(|(_, name)| name).collect();
assert_eq!(names.len(), 3);
}
}
@@ -97,7 +97,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
let Ok(document_serialized_content) = String::from_utf8(data) else {
return unsupported(responses);
};
responses.add(PortfolioMessage::OpenDocumentFile {
responses.add(PortfolioMessage::OpenLegacyDocumentFile {
document_name: name,
document_path,
document_serialized_content,
@@ -105,7 +105,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
return;
}
DataType::Gdd => {
responses.add(PortfolioMessage::OpenGddDocument {
responses.add(PortfolioMessage::OpenDocumentFile {
document_name: name,
document_path,
content: data,
@@ -202,24 +202,12 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
}
}
// The viewBox preserves the full canvas rather than the tighter bounding box of the rendered content
/// Determine the size of an SVG file (the viewBox is already applied by the SVG importer so can be ignored)
fn svg_canvas(svg: &str) -> Option<(IVec2, IVec2)> {
usvg::roxmltree::Document::parse(svg)
.ok()
.and_then(|document| {
let numbers: Vec<f64> = document
.root_element()
.attribute("viewBox")?
.split(|character: char| character.is_ascii_whitespace() || character == ',')
.filter_map(|number| number.parse().ok())
.collect();
let [x, y, width, height, ..] = numbers[..] else { return None };
Some((IVec2::new(x.round() as i32, y.round() as i32), IVec2::new(width.round() as i32, height.round() as i32)))
})
.or_else(|| {
let size = usvg::Tree::from_str(svg, &usvg::Options::default()).ok()?.size();
Some((IVec2::ZERO, IVec2::new(size.width().round() as i32, size.height().round() as i32)))
})
usvg::Tree::from_str(&svg, &usvg::Options::default()).ok().map(|tree| {
let size = tree.size();
(glam::IVec2::ZERO, glam::IVec2::new(size.width().round() as i32, size.height().round() as i32))
})
}
#[cfg(test)]
@@ -6,25 +6,5 @@ use crate::messages::prelude::*;
pub enum PersistentStateMessage {
ReadState,
WriteState,
LoadState {
state: PersistedState,
},
ReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
WriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
DeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
LoadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
LoadState { state: PersistedState },
}
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff. Show more