Compare commits

..
193 changed files with 4507 additions and 12179 deletions

No files matched your search

+5 -6
View File
@@ -1,7 +1,7 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
@@ -32,12 +32,11 @@ let
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchgit {
url = "https://github.com/Rust-GPU/rust-gpu";
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
};
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
Generated
+154 -163
View File
File diff suppressed because it is too large. Load diff
+6 -11
View File
@@ -53,7 +53,7 @@ default-members = [
resolver = "2"
[workspace.package]
rust-version = "1.98"
rust-version = "1.88"
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"
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
rmp-serde = "1.3"
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -172,6 +172,7 @@ 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"] }
@@ -181,12 +182,10 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
blake3 = "1.5"
@@ -240,12 +239,8 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
# 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 }
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", 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,15 +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
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +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
[lints]
workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
-3
View File
@@ -7,9 +7,6 @@ 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,9 +5,6 @@ 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,15 +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
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +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
[lints]
workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
-6
View File
@@ -5,15 +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
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+15 -8
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, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -99,13 +99,7 @@ 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),
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
wgpu_context.clone(),
wake,
);
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
Self {
render_state: None,
@@ -313,6 +307,19 @@ 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);
}
+52 -50
View File
@@ -1,9 +1,6 @@
use crate::wrapper::messages::PersistedState;
use crate::wrapper::messages::{DocumentId, 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,
@@ -16,13 +13,16 @@ pub(crate) fn read_state() -> PersistedState {
return PersistedState::default();
}
};
match ron::from_str(&data) {
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
PersistedState::default()
return PersistedState::default();
}
}
};
garbage_collect_document_files(&loaded);
loaded
}
pub(crate) fn write_state(state: PersistedState) {
@@ -37,6 +37,47 @@ 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 {
@@ -45,47 +86,8 @@ fn state_file_path() -> std::path::PathBuf {
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)
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
}
-6
View File
@@ -5,15 +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
[lints]
workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
-6
View File
@@ -5,15 +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
[lints]
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -44,6 +44,10 @@ 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,6 +69,18 @@ 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);
}
+2 -3
View File
@@ -10,7 +10,6 @@ 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;
@@ -33,7 +32,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
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 {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -44,7 +43,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
}
}
+11
View File
@@ -44,6 +44,13 @@ pub enum DesktopFrontendMessage {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceWritePreferences {
preferences: Preferences,
},
@@ -52,6 +59,9 @@ pub enum DesktopFrontendMessage {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -82,6 +92,7 @@ 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,15 +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
[lints]
workspace = true
[features]
default = []
zip = ["dep:zip"]
@@ -40,7 +34,6 @@ web-sys = { workspace = true, features = [
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemRemoveOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
@@ -6,7 +6,6 @@ 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::{Arc, Mutex};
use std::sync::Mutex;
#[derive(Clone, Default)]
#[derive(Default)]
pub struct MemoryBackend {
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
files: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryBackend {
+11 -67
View File
@@ -3,7 +3,6 @@
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;
@@ -41,33 +40,6 @@ 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>>,
}
@@ -105,6 +77,8 @@ 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;
}
}
@@ -265,12 +239,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 {
report_write_error("write", &path, &error);
log::error!("OPFS background write for {path} failed: {error:?}");
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
report_write_error("append", &path, &error);
log::error!("OPFS background append for {path} failed: {error:?}");
}
}
Mutation::Delete { path } => {
@@ -278,7 +252,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
report_write_error("delete", &path, &error);
log::error!("OPFS background delete for {path} failed: {error:?}");
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
@@ -289,11 +263,16 @@ 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 mut current = opfs_root().await?;
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()?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
@@ -304,37 +283,6 @@ 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();
@@ -525,7 +473,3 @@ 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,7 +12,6 @@
pub mod archive;
pub mod backends;
pub mod store;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
@@ -351,7 +350,6 @@ 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
@@ -1,145 +0,0 @@
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,15 +176,3 @@ 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"));
}
+1 -7
View File
@@ -5,15 +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
[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`
@@ -33,7 +27,7 @@ graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
+51 -33
View File
@@ -8,16 +8,18 @@ pub enum Codec {
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// 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,
/// 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,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
@@ -39,8 +41,8 @@ impl Codec {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::Postcard => "bin",
Codec::PostcardFrames => "frames",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
}
}
@@ -60,15 +62,15 @@ impl Codec {
output.push(b'\n');
Ok(())
}
Codec::Postcard => {
Codec::MessagePack => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
postcard::to_io(value, &mut *output)?;
rmp_serde::encode::write(output, value)?;
Ok(())
}
Codec::PostcardFrames => {
let payload = postcard::to_stdvec(value)?;
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(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);
@@ -89,11 +91,11 @@ impl Codec {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::Postcard => {
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::PostcardFrames => Box::new(PostcardFrameIter {
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
@@ -151,12 +153,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
}
}
struct PostcardFrameIter<'a, T> {
struct MessagePackFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
@@ -181,7 +183,7 @@ impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(postcard::from_bytes(frame).map_err(CodecError::from))
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
}
}
@@ -222,20 +224,31 @@ mod tests {
}
#[test]
fn postcard_round_trip_single() {
fn message_pack_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::Postcard.write_single(&frame).unwrap();
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn postcard_append_to_non_empty_errors() {
fn message_pack_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
let result = Codec::MessagePack.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() }];
@@ -250,13 +263,13 @@ mod tests {
}
#[test]
fn postcard_frames_round_trip() {
fn message_pack_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
@@ -264,27 +277,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 postcard_frames_detect_truncation() {
fn message_pack_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.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 postcard_frames_detect_truncated_length_prefix() {
fn message_pack_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.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::Postcard, Codec::PostcardFrames] {
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
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:?}");
@@ -302,7 +315,12 @@ mod tests {
#[test]
fn extensions_are_distinct() {
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
-3
View File
@@ -35,9 +35,6 @@ 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 },
+1 -4
View File
@@ -146,14 +146,11 @@ 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(),
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
+46 -42
View File
@@ -6,6 +6,7 @@
//!
//! 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"))]
@@ -13,10 +14,10 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -48,28 +49,30 @@ 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. 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. 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.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
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;
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;
/// 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` / `export` are async, since they
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// read.
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) 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: AnyContainer,
pub(crate) working: Arc<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
@@ -77,10 +80,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, document_graph_storage::Value>,
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::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, document_graph_storage::Value>>,
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -98,10 +101,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async 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)
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
}
}
@@ -121,14 +124,10 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`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.
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest 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 = 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()),
};
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
@@ -141,35 +140,32 @@ 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, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, user, registry)?
Session::bootstrap_from_registry(peer, registry)?
}
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, 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.
if let Some(rev) = session_state.last_broadcast_rev {
session.publish_up_to(rev);
}
// Every arm must continue this peer's authored-op count too.
session.restore_hot_sequence(session_state.next_hot_sequence);
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,
working: Arc::new(working),
layout,
manifest,
view_settings: session_state.view_settings,
@@ -179,15 +175,11 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async 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,
user_id: UserId(peer.0),
..Default::default()
};
let session_state = SessionState { peer_id: peer, ..Default::default() };
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
@@ -195,7 +187,7 @@ impl<L: Layout> Gdd<L> {
Ok(Self {
session,
working,
working: Arc::new(working),
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
@@ -266,13 +258,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, document_graph_storage::Value> {
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::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, document_graph_storage::Value>> {
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
&self.network_view_settings
}
@@ -295,8 +287,11 @@ 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) {
(self.working, self.layout)
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)
}
/// Resolve every proto-node declaration referenced by the registry or its history into a
@@ -327,7 +322,16 @@ impl<L: Layout> Gdd<L> {
declarations
}
/// Read the embedded legacy `.graphite` document, if present.
/// 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.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
+10 -11
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, Value};
use document_graph_storage::{HotOp, Rev, TimeStamp};
#[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: Value) -> Result<(), Error> {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
@@ -194,14 +194,11 @@ 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(),
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -209,16 +206,18 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// 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.
/// 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`).
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.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, document_graph_storage::Value>) -> Result<(), Error> {
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
@@ -234,7 +233,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, document_graph_storage::Value>>,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
self.persist_session_state()
+3 -2
View File
@@ -4,6 +4,7 @@
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
@@ -38,7 +39,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 {
if let AnyContainer::Folder(folder) = self.working.as_ref() {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
@@ -101,7 +102,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
}
}
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
+10 -21
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,17 +15,13 @@ 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)]
#[serde(default, skip_serializing_if = "Option::is_none")]
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.)
@@ -35,24 +31,17 @@ 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)]
pub view_settings: BTreeMap<String, Value>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_settings: BTreeMap<String, serde_json::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>>,
/// How many hot ops this peer has authored, feeding [`document_graph_storage::HotOp::sequence`]. A
/// reopen continues the run instead of reusing a spent sequence. Appended last: a positional codec
/// decodes these fields in declaration order.
#[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,
pub next_hot_sequence: HotSequence,
}
+69 -39
View File
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +82,9 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -97,7 +99,9 @@ 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()).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())
.await
.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:?}"));
@@ -112,7 +116,9 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.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.
@@ -138,7 +144,9 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.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 {
@@ -184,7 +192,9 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.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 {
@@ -214,7 +224,9 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -223,7 +235,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 postcard (`.bin`), manifest is JSON.
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
@@ -242,7 +254,9 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -267,7 +281,9 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -290,7 +306,9 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -320,7 +338,9 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -349,7 +369,9 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
@@ -373,7 +395,9 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -396,12 +420,14 @@ fn export_carries_resources() {
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::{NoMetadata, to_value};
use document_graph_storage::NoMetadata;
use graph_craft::application_io::resource::ResourceStorage;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
.await
.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.
@@ -448,8 +474,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 = to_value(&DataSource::Embedded).unwrap();
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
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 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");
});
@@ -466,7 +492,9 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
.await
.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";
@@ -507,7 +535,9 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -560,12 +590,14 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::Postcard);
assert_eq!(codecs.history, Codec::PostcardFrames);
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
@@ -581,7 +613,9 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -600,19 +634,11 @@ 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)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), 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)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
});
}
@@ -623,7 +649,9 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -636,8 +664,8 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
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 PostcardFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).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:?}"));
@@ -675,7 +703,9 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.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
@@ -1,108 +0,0 @@
// 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);
});
}
+1 -7
View File
@@ -5,15 +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
[lints]
workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
@@ -28,7 +22,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
+16 -37
View File
@@ -1,4 +1,4 @@
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
use crate::TimeStamp;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -8,54 +8,33 @@ 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 deleted key
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
/// A type-erased attribute value paired with the timestamp at which it was last set.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
timestamp,
deleted: true,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
}
}
/// 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)
}
pub type Attributes = BTreeMap<String, Value>;
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts `value` under `key`.
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::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<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
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);
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<(), ValueError> {
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
@@ -64,8 +43,8 @@ pub trait AttributesWrite {
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
}
}
@@ -87,6 +66,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
+47 -67
View File
@@ -1,15 +1,15 @@
use crate::{
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
Value, attr, compute_rev,
Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, 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 (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.
/// `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.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -18,22 +18,16 @@ pub struct Delta {
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
pub reverse: RegistryDelta,
/// 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)]
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
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: Vec<Prior>) -> Self {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
@@ -43,7 +37,6 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -61,10 +54,9 @@ impl Delta {
parent,
author,
timestamp,
reverse: Vec::new(),
reverse: kind.clone(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -79,16 +71,11 @@ 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, Value::Bool(true), timestamp);
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
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)
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
@@ -113,7 +100,8 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -166,12 +154,13 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
/// `snapshot` lets the reverse delta rebuild without re-walking history.
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -193,15 +182,16 @@ pub enum RegistryDelta {
AddSource {
id: ResourceId,
key: SourceKey,
source: Value,
source: serde_json::Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
/// registers again and the newest registration wins wherever it lands.
/// 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.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -216,52 +206,42 @@ 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(Value),
Other(serde_json::Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
pub value: Option<serde_json::Value>,
}
/// 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) {
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) {
let AttributeDelta { key, value } = delta;
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);
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);
}
}
}
}
+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.live_sources() {
for (key, _) in &from.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.live_sources() {
for (key, to_source) in &to.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 crate::attributes::live(from) {
if to.get(key).is_none_or(|value| value.deleted) {
for key in from.keys() {
if !to.contains_key(key) {
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 crate::attributes::live(to) {
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| 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, Value};
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
#[test]
fn test_compute_deltas_empty() {
@@ -287,7 +287,6 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -305,7 +304,11 @@ 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", Value::Float(640.), TimeStamp::ORIGIN);
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
@@ -338,10 +341,9 @@ mod tests {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("old".into()),
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -349,10 +351,9 @@ mod tests {
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("new".into()),
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
);
@@ -375,10 +376,9 @@ mod tests {
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::AttributeValue {
value: Value::Str("value".into()),
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
);
File diff suppressed because it is too large. Load diff
+31 -56
View File
@@ -10,12 +10,9 @@ 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, Value,
ValueError, from_value, to_value,
};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
@@ -43,7 +40,7 @@ impl NodePath {
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -55,7 +52,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 = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&("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]);
@@ -131,18 +128,18 @@ pub struct RuntimeConversion {
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
/// 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`].
/// 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`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = to_value(proto).map_err(|error| error.to_string())?;
postcard::to_stdvec(&value).map_err(|error| error.to_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())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
from_value(&value).map_err(|error| error.to_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())
}
impl Registry {
@@ -192,7 +189,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 [`Value`] so its on-disk shape can migrate freely. All
/// stored type-erased as `serde_json::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() {
@@ -220,14 +217,12 @@ 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 = 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(
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -322,7 +317,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, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -341,15 +336,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
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 {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -427,7 +414,6 @@ 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,
});
}
@@ -460,14 +446,10 @@ 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,
})
}
@@ -484,7 +466,11 @@ 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(to_value(value).map_err(map_serialization_error(key))?) };
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
@@ -532,14 +518,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, Value::Bool(true), timestamp);
attributes.set(key, serde_json::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, Value::Str(name.to_string()), timestamp);
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
@@ -567,7 +553,7 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
// 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, Value::Str(reference.to_string()), timestamp);
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
@@ -598,7 +584,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, Value::Str(value.to_string()), timestamp);
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
}
};
@@ -620,7 +606,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 = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
@@ -801,7 +787,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, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
@@ -827,15 +813,7 @@ impl<'m> ScopedConversion<'m> {
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 {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
registry.networks.insert(network_id, Network { exports, attributes });
Ok(())
}
@@ -858,10 +836,7 @@ 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::Object(fields), .. } => match fields.as_slice() {
[(key, id)] if key == "Resource" => from_value(id).ok(),
_ => None,
},
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
@@ -873,8 +848,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 = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
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());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+93 -34
View File
@@ -3,26 +3,21 @@
//! [`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. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
//! 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.
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
/// 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 {
@@ -32,9 +27,8 @@ 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 mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
history
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -45,9 +39,9 @@ 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
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.deltas.iter().any(|delta| delta.timestamp == timestamp)
}
pub fn len(&self) -> usize {
@@ -62,22 +56,10 @@ 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);
}
@@ -87,24 +69,101 @@ impl History {
self.deltas.iter()
}
/// 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).
///
/// Deterministic: two peers that absorb the same delta set end up with byte-identical history, not two
/// different valid orderings. Arrival order is erased.
pub 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> {
pub 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)
{
if !seen.insert(rev) {
continue;
}
if let Some(delta) = self.get(rev) {
stack.extend(delta.all_parents());
}
}
seen
}
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
self.ancestors([descendant]).contains(&ancestor)
}
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
/// so it can locate the divergence point within a factor of two of the true distance.
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
let mut samples = vec![tip];
let mut current = tip;
let mut distance = 0;
let mut next_sample_distance = 1;
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
current = parent;
distance += 1;
if distance == next_sample_distance {
samples.push(current);
next_sample_distance *= 2;
}
}
samples
}
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
let known = self.ancestors(known);
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
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();
tips.sort_unstable();
tips
}
@@ -123,7 +182,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: Value, timestamp: TimeStamp) -> bool {
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
+2 -4
View File
@@ -56,8 +56,6 @@ 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.
@@ -121,9 +119,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();
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
}
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
};
hasher.update(&bytes);
let digest = hasher.finalize();
-5
View File
@@ -7,11 +7,9 @@ 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;
@@ -26,11 +24,9 @@ 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::{
@@ -44,7 +40,6 @@ pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod round_trip;
}
@@ -8,8 +8,6 @@ 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)]
@@ -54,11 +52,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, Value>,
pub input_data: HashMap<String, serde_json::Value>,
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
None
@@ -90,7 +88,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, Value> {
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
HashMap::new()
}
+23 -50
View File
@@ -1,20 +1,9 @@
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, 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.
@@ -22,9 +11,6 @@ pub struct Node {
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,
}
@@ -65,22 +51,35 @@ impl Node {
/// `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 {
// `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`.
let slot = InputSlot {
input: NodeInput::Value {
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
};
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
inputs: vec![slot; inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
}
}
}
@@ -91,26 +90,6 @@ 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)]
@@ -120,7 +99,7 @@ pub enum NodeInput {
index: u32,
},
Value {
value: Value,
value: serde_json::Value,
exposed: bool,
},
Scope(Cow<'static, str>),
@@ -142,16 +121,10 @@ 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 {
@@ -176,7 +149,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -219,7 +192,7 @@ mod tests {
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");
let tagged: graph_craft::document::value::TaggedValue = serde_json::from_value(value.clone()).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
-304
View File
@@ -1,304 +0,0 @@
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),
}
}
+8 -56
View File
@@ -1,13 +1,7 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, 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>,
@@ -15,55 +9,13 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// 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>,
/// 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>,
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
@@ -133,10 +85,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
if a.len() != b.len() {
return false;
}
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -148,8 +100,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.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))
&& 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))
})
})
}
+69 -136
View File
@@ -1,4 +1,4 @@
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use crate::{PeerId, TimeStamp};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -11,28 +11,13 @@ pub struct SourceKey {
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub source: serde_json::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
@@ -41,13 +26,8 @@ impl 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,
}
@@ -59,22 +39,12 @@ 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 {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
let Raw { mut sources, 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.
@@ -87,13 +57,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
Ok(Self { sources, hash, hash_timestamp })
}
}
@@ -102,107 +66,82 @@ 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 = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = serde_json::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,
deleted: false,
},
)];
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The live source stored under `key`, if any; a tombstone is absent.
/// The source body and timestamp stored under `key`, if any.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
}
/// 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))
}
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)),
}
}
/// 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)),
_ => {}
}
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
}
/// 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);
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)),
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
/// 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) {
self.put(key, value);
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (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.
/// 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 {
if timestamp <= self.decided(key) {
return false;
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
}
_ => false,
}
}
/// 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,
}
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.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
self.sources.iter().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
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.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -286,15 +225,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. Postcard (the storage format) can carry a
/// than silently producing an unsound map key. MessagePack (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 = postcard::to_stdvec(&3.5_f64).unwrap();
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
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");
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");
}
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
@@ -309,23 +248,20 @@ mod tests {
peer: PeerId(1),
},
SourceValue {
source: Value::Float(priority),
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// 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,
};
// 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,
});
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
let entry: ResourceEntry = serde_json::from_value(unsorted).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");
}
@@ -342,23 +278,20 @@ mod tests {
(
key,
SourceValue {
source: Value::Str(body.into()),
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
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 with_duplicates = serde_json::json!({
"sources": [entry(5, "newer"), entry(1, "older")],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
}
}
+389 -217
View File
@@ -2,9 +2,7 @@
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, Value, to_value,
};
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -18,6 +16,9 @@ pub struct Session {
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
remote_tips: HashMap<PeerId, Rev>,
/// The registry the runtime was last built from or staged to. Local diffs are taken against it,
/// so edits peers applied to the working registry in the meantime are not diffed away.
runtime_base: Option<Registry>,
}
impl Session {
@@ -29,18 +30,27 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// 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).
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
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::empty(peer, user),
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
retired: RetiredHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
},
remote_tips: HashMap::new(),
runtime_base: None,
}
}
@@ -48,22 +58,6 @@ 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
}
@@ -90,11 +84,21 @@ impl Session {
resources: &graphene_resource::ResourceRegistry,
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
let base = self.runtime_base.as_ref().unwrap_or(&self.document.working_registry);
let ops = crate::delta::compute_deltas(base, &conversion.registry);
// The base moves only once the ops are staged, so a failure leaves the next diff covering them.
let hot_ops = self.stage_ops(ops)?;
self.runtime_base = Some(conversion.registry.clone());
Ok((hot_ops, conversion))
}
/// Record that the runtime now reflects the working registry, after the caller rebuilt it from there.
pub fn mark_runtime_current(&mut self) {
self.runtime_base = Some(self.document.working_registry.clone());
}
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
/// caller can key per-network, per-peer view state (`session.json`) by a stable id. Derived from the
/// network structure alone; resources/declarations are irrelevant to the ids.
@@ -117,7 +121,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 = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let mut ops = Vec::new();
for id in ids {
@@ -154,44 +158,29 @@ 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, 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.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
return Ok(Vec::new());
}
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 });
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 });
}
// 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);
// The counter advances only once the op is in the log, so a failure leaves no gap in the run.
let sequence = self.document.next_hot_sequence.next();
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence,
};
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;
self.document.apply_hot_op(hot_op.clone())?;
self.document.next_hot_sequence = sequence;
staged.push(hot_op);
}
Ok(staged)
@@ -199,8 +188,8 @@ 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*: 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
/// 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
/// 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.
///
@@ -212,7 +201,7 @@ impl Session {
/// [`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.
/// retirement passes the op's own; a coarsened delta passes the newest it fuses.
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();
@@ -226,7 +215,9 @@ impl Session {
self.document.redo_stack.clear();
}
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
// The reverse must read the pre-op value of a target that may have been concurrently removed.
self.document.ensure_referenced_exist(target, &op)?;
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
let author = timestamp.peer;
@@ -253,7 +244,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, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, 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);
@@ -266,20 +257,26 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
retired: RetiredHotOps::default(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
..Document::empty(peer, user)
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
},
remote_tips: HashMap::new(),
runtime_base: None,
}
}
/// 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, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
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);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -300,15 +297,40 @@ impl Session {
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
/// The hot ops a `retire(up_to)` call would drain. Sent with the deltas for peers to drop exactly
/// these; the cutoff alone doesn't transfer, a lagging op can arrive below it 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()
}
/// 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);
/// Drop hot ops another peer has retired without retiring them locally. Refolds like
/// [`absorb_retired_marks`](Self::absorb_retired_marks).
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Result<(), CrdtError> {
let before = self.document.hot_log.len();
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
// How a peer that did not retire these learns they are in history now.
self.document.mark_retired(retired.iter().copied());
if before != self.document.hot_log.len() {
self.refold_registries()?;
}
Ok(())
}
/// Which hot ops history already covers, for a peer catching up. See [`RetiredHotOps`].
pub fn retired_marks(&self) -> &RetiredHotOps {
&self.document.retired
}
/// See [`RetiredHotOps::absorb`]. A drop owes a refold, since the working registry holds the op's
/// effect in hot-log order where the snapshot holds it in canonical order.
pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), CrdtError> {
if self.document.absorb_retired(remote) {
self.refold_registries()?;
}
Ok(())
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -317,52 +339,152 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// 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)?;
}
Ok(scratch.working_registry)
}
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.
/// The retired snapshot as canonical history alone produces it, independent of arrival order and the
/// hot log. Folded on a clone, 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.
///
/// 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));
/// The clone's history grows with the replay, as it did when each delta first landed. Resurrection
/// takes the last removal in canonical order, and with the whole history in view that can be one past
/// the replay position, whose snapshot places the entity in a network the replay has not created yet.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(self.document.head);
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)
let mut folded = self.clone();
folded.document.retired_snapshot = Registry::default();
folded.document.history = History::new();
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
folded.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
folded.document.history.push(delta.clone());
}
Ok(folded.document.retired_snapshot)
}
/// Promote every hot op stamped at or before `up_to`, whatever its author.
/// Rebuild both registries from canonical history, then re-layer the hot tail. A full replay; callers
/// check it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
// Cleared only on the way out. The deltas are in history either way, and a failure here leaves the
// registries derived from an older one until something retries.
self.document.refold_owed = true;
self.document.retired_snapshot = self.snapshot_from_history()?;
// One left unapplicable is kept, not dropped: a later delta or hot op can still supply its referent.
self.document.working_registry = self.document.retired_snapshot.clone();
let mut failure = None;
for hot_op in std::mem::take(&mut self.document.hot_log) {
if let Err(error) = self.document.replay_hot_op(hot_op.clone()) {
self.document.hot_log.push(hot_op);
failure = failure.or(Some(error));
}
}
if let Some(error) = failure {
return Err(error);
}
self.document.refold_owed = false;
Ok(())
}
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
/// incoming tips with a [`RegistryDelta::Merge`].
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
let length_before = self.document.history.len();
// Each delta enters history before the next is applied, so a later delta in the batch that
// targets something an earlier one removed can resurrect it.
let mut absorbed_ids = HashSet::new();
let mut arrival_order = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
arrival_order.push(delta.id);
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
// Working is snapshot plus hot tail, so a delta lands on both; cloning would promote hot ops.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
absorbed_ids.insert(delta.id);
self.document.history.push(delta);
}
if absorbed_ids.is_empty() {
// Nothing new, but a refold left owed by an earlier failure is still the only way the registries
// catch up with the history they are derived from.
if self.document.refold_owed {
self.refold_registries()?;
}
return Ok(MergeOutcome::NoOp);
}
self.document.history.canonical_sort();
// The loop folds in arrival order, and concurrent ops do not all commute: a remove and a change to
// the same target resolve by whichever lands second.
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
let history = &self.document.history;
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
let outcome = match parents.as_slice() {
[tip] => MergeOutcome::FastForward(*tip),
_ => {
let timestamp = self.document.clock.tick();
let merge = Delta::merge(parents, self.document.peer, timestamp);
let merge_rev = merge.id;
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
self.document.history.push(merge);
MergeOutcome::Merged(merge_rev)
}
};
self.document.head = outcome.head();
// After `head`, since the fold is over its ancestry.
if !folded_in_canonical_order || self.document.refold_owed {
self.refold_registries()?;
}
Ok(outcome)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, each keeping the timestamp it was
/// authored at.
///
/// 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 ids = self.hot_ops_up_to(up_to);
self.retire_hot_ops(&ids)
// Hot-log order is causal, so the deltas commit in an order their references survive.
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
// Retiring by timestamp reorders against the hot-log order the working registry applied: past a
// skipped op, everything drained was applied here before it.
let mut skipped = false;
let mut reordered = false;
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
reordered |= skipped;
drained.push(hot_op);
} else {
skipped = true;
remaining.push(hot_op);
}
}
self.document.hot_log = remaining;
self.document.mark_retired(drained.iter().map(HotOp::id));
let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?;
// Structural ops have no timestamp to arbitrate, so the reorder changes the outcome.
if reordered {
self.refold_registries()?;
}
Ok(revs)
}
/// 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) {
@@ -373,36 +495,38 @@ 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: Value) -> bool {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
let timestamp = self.document.clock.tick();
self.document.history.annotate(rev, key, value, timestamp)
}
/// 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.
/// 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.
pub fn can_undo(&self) -> bool {
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
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()
}
/// 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;
/// 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;
loop {
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);
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);
}
current = parent;
}
@@ -412,22 +536,37 @@ impl Session {
!self.document.redo_stack.is_empty()
}
/// 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.
/// Silent-zone undo of one *interaction*: revert deltas back along first-parents until `head` reaches
/// the previous `interaction_end` boundary or the root. An interaction is a whole `commit_from_runtime`
/// batch, so the run reverts together. 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)?;
// The caller rebuilds the runtime from the rewound registry; until then diff against it directly.
self.runtime_base = None;
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
// 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)?;
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
self.document.revert_delta(&delta);
self.document.head = delta.parent;
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta.clone())?;
// Working is snapshot plus hot tail, so rewind both; copying would promote unretired hot ops.
self.document.revert_delta(RegistryTarget::Snapshot, 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(_) => {}
}
}
// 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)
}
@@ -437,6 +576,7 @@ impl Session {
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
self.runtime_base = None;
let mut forward = Vec::new();
let mut cursor = Some(checkpoint);
@@ -447,17 +587,12 @@ impl Session {
forward.push(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();
// 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`.
for delta in forward.into_iter().rev() {
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.force_apply_op(delta.kind.clone(), delta.timestamp)?;
// Both zones move together, for the same reason `undo` rewinds both.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Force)?;
}
self.document.head = Some(checkpoint);
@@ -466,9 +601,9 @@ impl Session {
/// 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, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_identity(peer, user);
let mut session = Self::with_peer(peer);
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();
@@ -480,6 +615,17 @@ impl Session {
self.document.history.iter()
}
/// Revs sampled at exponentially growing distances behind `head`, for a remote peer to locate what
/// this session is missing (see [`History::sample_chain`]).
pub fn known_revs(&self) -> Vec<Rev> {
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
}
/// Retired deltas not reachable from `known`, in replay order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
self.document.history.deltas_unknown_to(known)
}
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
@@ -499,7 +645,15 @@ 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();
hashes.extend(self.document.history.resource_hashes());
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
}
@@ -565,7 +719,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 failure (e.g. `NotFoundInHistory`).
/// test can observe a resurrection 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(|_| ())
@@ -579,27 +733,15 @@ impl Session {
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);
/// How many hot ops this peer has authored. Carried across a reload; no sequence is spent twice.
pub fn next_hot_sequence(&self) -> HotSequence {
self.document.next_hot_sequence
}
/// 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);
self.document.next_hot_sequence = self.document.next_hot_sequence.max(sequence);
}
}
@@ -620,18 +762,36 @@ impl Default for Session {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MergeOutcome {
NoOp,
FastForward(Rev),
Merged(Rev),
}
impl MergeOutcome {
/// The head after the merge, or `None` when nothing changed.
pub fn head(self) -> Option<Rev> {
match self {
Self::NoOp => None,
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
}
}
}
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
/// Position in its author's run, from 1 with no gaps. A watermark over it therefore means a contiguous
/// prefix; one over the Lamport counter cannot, since that skips on observing a higher remote stamp.
pub sequence: HotSequence,
}
impl HotOp {
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
/// Identifies the op for retirement, which tracks a contiguous prefix per author.
pub fn id(&self) -> HotOpId {
HotOpId {
peer: self.timestamp.peer,
@@ -650,9 +810,9 @@ 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.
/// The next position in the run.
pub fn next(self) -> Self {
Self(self.0.saturating_add(1))
Self(self.0 + 1)
}
}
@@ -664,84 +824,89 @@ pub struct HotOpId {
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.
/// Which hot ops history already covers: `retired_up_to` is each author's gap-free retired prefix, and
/// `unretired` the retired ops past it. Replicated, letting a peer catching up separate an op already in
/// history from one still owed to it.
#[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)>>,
pub struct RetiredHotOps {
pub retired_up_to: HashMap<PeerId, HotSequence>,
/// Retired ops sitting past their author's prefix, as inclusive runs. A gap that never fills pins the
/// prefix and everything later from that author lands here, so runs keep this proportional to the
/// number of gaps instead of the number of ops.
pub retired_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);
let mut merged: Vec<(HotSequence, HotSequence)> = Vec::with_capacity(runs.len());
for &(start, end) in runs.iter() {
match merged.last_mut() {
Some((_, last_end)) if start <= last_end.next() => *last_end = (*last_end).max(end),
_ => merged.push((start, end)),
}
joins
});
}
*runs = merged;
}
impl SettledHotOps {
impl RetiredHotOps {
/// 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)))
if self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through) {
return true;
}
self.retired_beyond
.get(&id.peer)
.is_some_and(|runs| runs.iter().any(|&(start, end)| id.sequence >= start && id.sequence <= end))
}
/// 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();
pub fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.retired_up_to {
let through = self.retired_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());
for (&peer, runs) in &remote.retired_beyond {
self.retired_beyond.entry(peer).or_default().extend(runs.iter().copied());
}
self.compact();
}
/// Record newly settled ops.
/// Record newly retired 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.retired_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.
/// Fold runs that continue their author's prefix into `retired_up_to`, leaving only those past a gap.
fn compact(&mut self) {
for (&peer, runs) in &mut self.settled_beyond {
for (&peer, runs) in &mut self.retired_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);
let mut through = self.retired_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
while runs.first().is_some_and(|&(start, _)| start <= through.next()) {
let (_, end) = runs.remove(0);
through = through.max(end);
}
if through != HotSequence::NONE {
self.settled_up_to.insert(peer, through);
self.retired_up_to.insert(peer, through);
}
}
self.settled_beyond.retain(|_, runs| !runs.is_empty());
self.retired_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")]
@@ -752,6 +917,10 @@ 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")]
@@ -760,6 +929,9 @@ 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 },
}
@@ -1,165 +0,0 @@
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
+7 -14
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, from_value};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// 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)| from_value(&v.source).expect("source body decodes")).collect();
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).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,9 +609,10 @@ 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::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.
/// A node-input `TaggedValue::Number` 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.
#[test]
fn node_input_f64_round_trips_bit_exact() {
use graph_craft::document::value::TaggedValue;
@@ -658,7 +659,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, crate::Value::Int(7), TimeStamp::ORIGIN);
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, serde_json::json!(7), TimeStamp::ORIGIN);
}
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
@@ -757,28 +758,20 @@ 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,
},
);
+30 -36
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, Value, from_value};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -51,7 +51,19 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
let context = ConversionContext::new(self, declarations);
// 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,
};
// 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`.
@@ -63,15 +75,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 `Value` form back to
/// sorted by key) with bodies decoded from their type-erased `serde_json::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.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
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()))?;
registry.push_source_back(id, decoded);
}
if let Some(hash) = entry.hash {
@@ -92,26 +104,6 @@ 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
@@ -174,7 +166,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.networks.get(&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));
@@ -182,8 +174,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 runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
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);
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -240,7 +232,8 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
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)))
})
.collect()
}
@@ -278,7 +271,8 @@ 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)?;
Some(runtime_node_id(storage_id, node))
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))
};
let pinned_order = attributes
@@ -298,7 +292,8 @@ 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, Value> = crate::attributes::live(attributes)
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -340,9 +335,7 @@ 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 } => {
// 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))?;
let referenced = registry.node_instances.get(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.
@@ -353,13 +346,14 @@ 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: runtime_node_id(*node_id, referenced),
node_id: RuntimeNodeId(local_id),
output_index: *output_index as usize,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
GraphCraftNodeInput::Value {
tagged_value: MemoHash::new(tagged_value),
exposed: *exposed,
-265
View File
@@ -1,265 +0,0 @@
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,15 +4,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
[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>,
document_store: Arc<dyn document_container::store::DocumentStore>,
working_copy_root: Option<std::path::PathBuf>,
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, document_store);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
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,9 +193,5 @@ 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;
+3 -6
View File
@@ -89,19 +89,16 @@ 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>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
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()),
Arc::new(document_container::store::MemoryStore::default()),
);
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
-2
View File
@@ -19,5 +19,3 @@ 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,10 +1,6 @@
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>,
@@ -34,26 +30,7 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
impl LayoutHolder for CloseAllDocumentsDialog {
fn layout(&self) -> Layout {
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}");
}
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
@@ -118,9 +118,22 @@ 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,5 +1,7 @@
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::*;
@@ -10,6 +12,9 @@ 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,5 +1,4 @@
pub mod layout_widget;
pub mod tooltip_markdown;
pub mod widgets;
pub mod widget_prelude {
@@ -1,78 +0,0 @@
//! 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, Value};
use document_graph_storage::{Declarations, Registry};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
@@ -112,12 +112,6 @@ impl DocumentHistory {
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.
@@ -132,7 +126,15 @@ 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, Value>, byte_store: &dyn ResourceStorage) {
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,
) {
let needs_whole_document_stage = self.needs_whole_document_stage;
let Some(storage) = self.storage.as_mut() else { return };
@@ -159,7 +161,7 @@ impl DocumentHistory {
}
}
self.persist_view_state(interface, view_settings);
self.persist_view_state(interface, view_settings, legacy_document);
}
/// Converts the whole document and stages the difference from what the working copy holds.
@@ -196,8 +198,9 @@ impl DocumentHistory {
Ok(constructed.declarations.decoded)
}
/// 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>) {
/// 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) {
let Some(storage) = self.storage.as_mut() else { return };
let network_view_settings = storage
@@ -214,6 +217,10 @@ 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,7 +32,6 @@ 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;
@@ -150,10 +149,6 @@ 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>,
@@ -205,7 +200,6 @@ 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,
@@ -413,8 +407,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(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::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::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -570,7 +564,6 @@ 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() {
@@ -2035,11 +2028,6 @@ 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();
@@ -2062,19 +2050,20 @@ impl DocumentMessageHandler {
return;
}
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
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);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// 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> {
/// 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) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
DocumentSettings {
let view_settings = DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
overlays_visibility: &self.overlays_visibility_settings,
@@ -2082,15 +2071,17 @@ impl DocumentMessageHandler {
snapping_state: &self.snapping_state,
collapsed: &self.collapsed,
}
.to_view_map()
.to_view_map();
(view_settings, self.serialize_document())
}
/// Restore `view_settings` map into the document.
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>) {
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
use document_graph_storage::attr::session::doc;
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())
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())
}
if let Some(value) = decode(view_settings, doc::PTZ) {
@@ -2113,15 +2104,11 @@ impl DocumentMessageHandler {
}
}
/// 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>) {
/// 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>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
Ok(rebuilt) => self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses),
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
@@ -2444,7 +2431,7 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, 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
@@ -2452,7 +2439,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
self.drive_storage_undo_redo(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.
@@ -2486,7 +2473,7 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, 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
@@ -2494,7 +2481,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
@@ -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_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
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);
}
if include_stroke {
@@ -175,14 +175,13 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
}
// 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")
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);
}
}
@@ -3,7 +3,7 @@ mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
pub(crate) mod storage_tests;
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.try_angle_to(end_offset).unwrap_or(0.);
let angle = start_offset.angle_to(end_offset);
tilt_raw_not_snapped + angle
};
@@ -1465,22 +1465,6 @@ 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| {
@@ -57,8 +57,6 @@ 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,
@@ -412,8 +410,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
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);
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
}
NodeGraphMessage::EnterNestedNetwork => {
// Do not enter the nested network if the node was dragged
@@ -790,7 +799,6 @@ 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(),
@@ -1036,7 +1044,6 @@ 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);
}
@@ -1164,17 +1171,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.begin_dragging {
self.begin_dragging = false;
if ipp.keyboard.get(Key::Alt as usize) {
// 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);
responses.add(NodeGraphMessage::DuplicateSelectedNodes);
// 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;
}
}
@@ -1480,7 +1483,6 @@ 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;
@@ -1527,17 +1529,15 @@ 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);
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;
// 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 (skip for Alt-drag to avoid removing the duplicates)
responses.add(DocumentMessage::AbortTransaction);
// Undo to the state of the graph before shaking
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");
@@ -1622,9 +1622,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
if !self.duplicated_in_drag {
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
}
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
@@ -2262,20 +2260,6 @@ 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 {
@@ -2945,7 +2929,6 @@ 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,
@@ -2977,7 +2960,6 @@ 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,7 +2,6 @@
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;
@@ -41,7 +40,6 @@ use graphene_std::vector::style::{
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> {
@@ -417,60 +415,6 @@ 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);
@@ -3766,34 +3710,4 @@ mod tests {
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}");
}
}
@@ -1,215 +0,0 @@
//! 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, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -342,14 +342,26 @@ fn document_settings_round_trip() {
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
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.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(
to_value(&restored.overlays_visibility_settings).unwrap(),
to_value(&document.overlays_visibility_settings).unwrap(),
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(),
"overlays"
);
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");
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");
}
@@ -4,7 +4,6 @@
//!
//! Shared fixtures live in [`test_support`].
mod lifecycle_tests;
mod metadata_tests;
mod round_trip_tests;
pub(crate) mod test_support;
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,
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! MessagePack 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, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
@@ -158,7 +158,9 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.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)
@@ -208,7 +210,9 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.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) {
@@ -259,7 +263,9 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
@@ -328,7 +334,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);
let byte_store = mount_in_memory_storage(&mut editor).await;
// 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();
@@ -367,9 +373,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(&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");
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");
}
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
@@ -381,13 +387,15 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.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(), to_value(&ptz).unwrap())]);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::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.
@@ -402,7 +410,7 @@ async fn gdd_archive_round_trips_view_settings() {
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&to_value(&ptz).unwrap()),
Some(&serde_json::to_value(ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
@@ -429,7 +437,9 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -462,14 +472,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 attach-time snapshot (as `StorageAttached` does), then draw a rect
/// new-document base as the mount-time snapshot (as `DocumentStorageMounted` 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);
let byte_store = mount_in_memory_storage(&mut editor).await;
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -559,7 +569,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);
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.handle_message(paste_named_image()).await;
@@ -591,7 +601,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);
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
@@ -664,8 +674,10 @@ 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.
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");
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");
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
}
@@ -689,7 +701,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
})
.await;
let byte_store = mount_in_memory_storage(&mut editor);
let byte_store = mount_in_memory_storage(&mut editor).await;
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -757,7 +769,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::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
@@ -780,7 +792,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
@@ -838,7 +850,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
.handle_message(PortfolioMessage::OpenDocumentFile {
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, document_graph_storage::Value>,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
@@ -56,7 +56,9 @@ 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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.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.
pub(super) fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
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,72 +509,23 @@ 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 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)
};
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 {
let Some(transient) = self.network_transient_mut(network_path) else {
return;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return;
};
// 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);
}
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();
// 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);
}
}
@@ -917,24 +868,3 @@ 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, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
use super::{InputConnector, 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;
@@ -447,184 +447,3 @@ async fn toggle_preview_transitions_with_a_connected_export() {
assert_invariants(&editor, "after cycling through the preview states");
}
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"));
}
fn value_input() -> NodeInput {
NodeInput::value(TaggedValue::None, false)
}
/// 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), &[]);
assert!(network_interface.outward_wires(&[]).is_some());
assert_interface_invariants(&network_interface, "after wiring the fixture");
(network_interface, source, node, consumer)
}
#[test]
fn replacing_inputs_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, source, node, _) = wired_interface();
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);
};
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"
);
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"
);
}
// 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);
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, &[]);
};
// 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");
// 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"
);
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, Value};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
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;
@@ -168,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(Value::Bool(false)),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
@@ -233,7 +233,6 @@ 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>>()?;
@@ -280,7 +279,7 @@ impl EditorDelta {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(Value::Str),
value: reference.clone().map(serde_json::Value::String),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
@@ -302,8 +301,8 @@ impl EditorDelta {
}
}
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:?}")))
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:?}")))
}
/// The attribute writes one metadata field makes, as the whole-document encoder would write them.
@@ -311,11 +310,11 @@ fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<Valu
/// 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<Value>| RegistryDelta::ChangeNodeAttribute {
let node_attribute = |key: &str, value: Option<serde_json::Value>| RegistryDelta::ChangeNodeAttribute {
id: global_id,
delta: AttributeDelta { key: key.to_string(), value },
};
let input_attribute = |key: &str, index: usize, value: Option<Value>| {
let input_attribute = |key: &str, index: usize, value: Option<serde_json::Value>| {
Ok::<_, ConversionError>(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: index.try_into().map_err(|_| ConversionError::IndexOverflow(index))?,
@@ -324,8 +323,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(Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| Value::Str(value.to_string()));
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()));
Ok(match change {
NodeMetadataChange::NodeType(node_type) => {
let position = position_from_runtime(node_type);
@@ -382,35 +381,15 @@ fn construct_structural_additions(
// 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();
match batch.node(id).is_some() {
true => {
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
}
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -511,7 +490,7 @@ 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(Value::Str);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
// 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.
@@ -840,10 +819,8 @@ 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, Value> {
self.persistent(input_index)
.map(|metadata| metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
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()
}
}
@@ -933,10 +910,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, Value> {
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
@@ -611,24 +611,4 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
!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}");
}
}
}
@@ -142,7 +142,6 @@ 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 {
@@ -385,16 +384,12 @@ 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.
@@ -406,10 +401,7 @@ impl NodeNetworkInterface {
log::error!("Could not get node {node_id} in replace_inputs");
return None;
};
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)
Some(node.replace_inputs(new_inputs, new_input_metadata))
}
/// 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.
@@ -736,14 +728,6 @@ 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);
@@ -838,29 +822,19 @@ 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 removed nodes' cached wire paths, which the per-node unload can no longer reach
// Purge the deleted 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| !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)));
.retain(|connector, _| connector.node_id().is_none_or(|node_id| !delete_nodes.contains(&node_id)));
}
self.unload_all_nodes_bounding_box(network_path);
@@ -8,7 +8,7 @@
use std::collections::{BTreeMap, HashMap};
use document_graph_storage::attr::session;
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position};
use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode;
@@ -96,10 +96,8 @@ 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, 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 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 output_names(&self, network_path: &[NodeId], local_id: NodeId) -> Vec<String> {
@@ -126,14 +124,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, Value> {
pub fn to_view_map(&self) -> BTreeMap<String, serde_json::Value> {
let entries = [
(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)),
(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)),
];
entries
@@ -203,7 +201,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, Value>> {
) -> BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, serde_json::Value>> {
let mut out = BTreeMap::new();
for (network_path, &network_id) in network_ids {
@@ -217,24 +215,24 @@ 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) = to_value(&navigation.node_graph_ptz)
&& let Ok(value) = serde_json::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) = to_value(&navigation.node_graph_to_viewport)
&& let Ok(value) = serde_json::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) = to_value(&navigation.node_graph_width)
&& let Ok(value) = serde_json::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)
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
@@ -254,7 +252,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, Value>>,
network_view_settings: &BTreeMap<document_graph_storage::NetworkId, BTreeMap<String, serde_json::Value>>,
) {
for (network_path, network_id) in network_ids {
let Some(settings) = network_view_settings.get(network_id) else { continue };
@@ -263,23 +261,23 @@ pub fn apply_network_view_settings(
};
if let Some(value) = settings.get(session::network::NAV_PTZ)
&& let Ok(ptz) = from_value::<PTZ>(value)
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
{
navigation.node_graph_ptz = ptz;
}
if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
&& let Ok(transform) = from_value(value)
&& let Ok(transform) = serde_json::from_value(value.clone())
{
navigation.node_graph_to_viewport = transform;
}
if let Some(value) = settings.get(session::network::NAV_WIDTH)
&& let Ok(width) = from_value(value)
&& let Ok(width) = serde_json::from_value(value.clone())
{
navigation.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = from_value::<Previewing>(value)
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
&& let Some(mut network) = interface.network_mut(network_path)
{
network.set_previewing(previewing);
@@ -400,7 +398,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.into_iter().map(|(key, value)| (key, value.into())).collect(),
input_data: entry.input_data,
},
}
}
@@ -303,6 +303,7 @@ 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;
@@ -314,6 +315,7 @@ 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
}
@@ -372,6 +374,7 @@ impl NodeMut<'_> {
/// 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;
@@ -380,6 +383,7 @@ 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();
@@ -1,6 +1,5 @@
use super::{InputConnector, NodeNetworkInterface, NodeNetworkMetadata};
use super::{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.
@@ -10,47 +9,8 @@ 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>) {
@@ -1185,6 +1185,9 @@ 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();
@@ -1247,6 +1250,7 @@ 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();
@@ -1275,6 +1279,8 @@ 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`
@@ -1424,6 +1430,9 @@ 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;
@@ -3239,40 +3248,6 @@ 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() {
@@ -3338,7 +3313,7 @@ mod tests {
);
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
let network = document.network_interface.document_network();
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
@@ -3397,7 +3372,7 @@ mod tests {
},
&[],
);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
// 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];
@@ -3408,47 +3383,6 @@ mod tests {
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]
@@ -3509,7 +3443,7 @@ mod tests {
NodeInput::value(TaggedValue::Number(0.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
@@ -3531,7 +3465,7 @@ mod tests {
NodeInput::value(TaggedValue::Number(3.), false),
];
let mut document = build_document("graphene_core::ops::MathNode", inputs);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
@@ -3550,7 +3484,7 @@ mod tests {
NodeInput::node(source_b_id, 0),
];
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
@@ -3572,7 +3506,7 @@ mod tests {
NodeInput::value(TaggedValue::Number(5.), false),
];
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
let extend_id = find_extend(&document);
@@ -3601,7 +3535,7 @@ mod tests {
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
@@ -3634,7 +3568,7 @@ mod tests {
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
let DocumentNodeImplementation::Network(inner) = &document.network_interface.document_network().nodes[&node_id].implementation else {
panic!("Blend should stay a network node")
@@ -3659,7 +3593,7 @@ mod tests {
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, &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(
@@ -3698,7 +3632,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(), &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
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");
@@ -3729,7 +3663,7 @@ mod tests {
};
document.network_interface.insert_node(node_id, image_template, &[]);
migrate(&mut document);
document_migration_upgrades(&mut document, false);
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,359 +1,215 @@
//! 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.
//! 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;
use super::document::DocumentMessageHandler;
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::diff_networks;
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::*;
use super::document_migration::document_migration_string_preprocessing;
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;
#[derive(Clone)]
pub struct DocumentStoreHandle(Arc<dyn DocumentStore>);
impl DocumentStoreHandle {
pub fn new(store: Arc<dyn DocumentStore>) -> Self {
Self(store)
}
}
impl std::ops::Deref for DocumentStoreHandle {
type Target = dyn DocumentStore;
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
}
/// 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));
};
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,
#[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))
}
.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
/// 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?;
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
} else {
None
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
};
let declarations = load_declarations(gdd.as_ref(), &resources).await;
PortfolioMessage::StorageAttached {
document_id,
container: Some(container),
gdd: gdd.map(Box::new),
declarations,
}
.into()
Ok((gdd, exists))
}
/// 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,
/// `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>,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
document_path: Option<std::path::PathBuf>,
content: Vec<u8>,
resources: ResourcesHandle,
reset_nodes: bool,
legacy_only: bool,
store_handle: ResourcesHandle,
validate: bool,
) -> Message {
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 {
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 {
document_id,
document_name,
document_path,
document: document.map(Box::new),
gdd: gdd.map(Box::new),
declarations,
}
.into()
})
}
/// 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}");
/// 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}");
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),
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Creating storage for {document_id:?} failed: {error}");
None
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
}
}
}
};
/// 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> {
// Extract archived resource bytes into the global cache so declarations + runtime resolve.
match gdd.resource_hashes().await {
Ok(hashes) => {
for hash in hashes {
match gdd.read_resource(&hash).await {
Ok(holder) => {
byte_store.store(holder.as_slice());
store_handle.store(holder.as_slice());
}
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 read resource {hash}: {error}"),
}
}
}
Err(error) => log::error!("Opening document {document_id:?}: failed to list resources: {error}"),
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
}
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 document {document_id:?}: failed to convert registry to runtime: {error}");
return None;
}
};
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;
}
};
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
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 mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
document.finalize_storage_load();
Some(document)
}
/// 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);
// 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);
}
});
// 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, &[]);
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
}
}
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
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)
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None));
}
document.network_interface.discard_deltas();
document.require_whole_document_stage();
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
}
Ok(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}");
return;
}
};
// 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"));
}
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
normalize_call_arguments_for_compare(inner);
}
}
}
@@ -2,26 +2,29 @@ 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::document_storage_io::{DocumentStoreHandle, document_key, legacy_path, remove_stored_document};
use crate::messages::portfolio::persistent_state::PersistentStateMessage;
use crate::messages::prelude::*;
use document_container::AsyncContainer;
#[derive(ExtractField)]
pub struct FailedDocumentsMessageContext<'a> {
pub document_store: &'a DocumentStoreHandle,
pub document_ids: &'a mut VecDeque<DocumentId>,
}
#[derive(Debug, Default, ExtractField)]
pub struct FailedDocumentsMessageHandler {
/// Stored documents that failed to load. Their store entries stay until explicitly discarded.
/// 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.
// TODO: Eventually remove this document upgrade code
failed_to_load_documents: HashMap<DocumentId, DocumentInfo>,
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,
}
#[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_store } = context;
let FailedDocumentsMessageContext { document_ids } = context;
match message {
// TODO: Eventually remove this document upgrade code
@@ -29,15 +32,19 @@ 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(display_name_with_fallback).collect();
let failed_document_names = self.failed_to_load_documents.values().map(|(info, _)| display_name_with_fallback(info)).collect();
let dialog = simple_dialogs::FailedToLoadDocumentsDialog { failed_document_names };
dialog.send_dialog_to_frontend(responses);
}
// TODO: Eventually remove this document upgrade code
FailedDocumentsMessage::DiscardFailedToLoadDocuments => {
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));
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 });
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(PersistentStateMessage::WriteState);
}
// TODO: Eventually remove this document upgrade code
FailedDocumentsMessage::DownloadFailedToLoadDocuments => {
@@ -45,22 +52,60 @@ impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> f
return;
}
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}"),
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}"),
});
}
}
recovery_download(entries)
});
}
}
}
}
@@ -70,8 +115,39 @@ impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> f
impl FailedDocumentsMessageHandler {
// TODO: Eventually remove this document upgrade code
pub(crate) fn record_failure(&mut self, document_id: DocumentId, info: DocumentInfo) {
self.failed_to_load_documents.insert(document_id, info);
/// 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);
}
}
}
@@ -84,76 +160,6 @@ 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> {
@@ -223,15 +229,25 @@ mod tests {
use super::*;
#[test]
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,
});
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());
}
let names: HashSet<_> = recovery_file_names(infos.iter()).into_iter().map(|(_, name)| name).collect();
assert_eq!(names.len(), 3);
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 { .. }))));
}
}
@@ -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::OpenLegacyDocumentFile {
responses.add(PortfolioMessage::OpenDocumentFile {
document_name: name,
document_path,
document_serialized_content,
@@ -105,7 +105,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
return;
}
DataType::Gdd => {
responses.add(PortfolioMessage::OpenDocumentFile {
responses.add(PortfolioMessage::OpenGddDocument {
document_name: name,
document_path,
content: data,
@@ -202,12 +202,24 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
}
}
/// Determine the size of an SVG file (the viewBox is already applied by the SVG importer so can be ignored)
// The viewBox preserves the full canvas rather than the tighter bounding box of the rendered content
fn svg_canvas(svg: &str) -> Option<(IVec2, IVec2)> {
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))
})
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)))
})
}
#[cfg(test)]
@@ -6,5 +6,25 @@ use crate::messages::prelude::*;
pub enum PersistentStateMessage {
ReadState,
WriteState,
LoadState { state: PersistedState },
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,
},
}
@@ -32,6 +32,21 @@ impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for P
self.loaded = true;
responses.add(PortfolioMessage::LoadPersistedState { state });
}
PersistentStateMessage::ReadDocument { document_id } => {
responses.add(FrontendMessage::TriggerPersistenceReadDocument { document_id });
}
PersistentStateMessage::WriteDocument { document_id, document } => {
responses.add(FrontendMessage::TriggerPersistenceWriteDocument { document_id, document });
}
PersistentStateMessage::DeleteDocument { document_id } => {
responses.add(FrontendMessage::TriggerPersistenceDeleteDocument { document_id });
}
PersistentStateMessage::LoadDocument { document_id, document } => {
responses.add(PortfolioMessage::LoadDocumentContent {
document_id,
document_serialized_content: document,
});
}
}
}
@@ -2,7 +2,6 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::PersistentStateMessage;
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::prelude::*;
use document_container::AnyContainer;
use std::path::PathBuf;
#[impl_message(Message, Portfolio)]
@@ -46,76 +45,70 @@ pub enum PortfolioMessage {
DeleteDocument {
document_id: DocumentId,
},
/// Delivers an asynchronously-built `Gdd` working copy, with the proto-node declarations its history
/// references, into its document. Emitted by the mount future spawned in `load_document`. The `mounted`
/// payload is non-serializable and a clone carries none (`clone_to_none`), so it travels exactly once.
/// `reopened` is true when an existing working copy was opened: the persisted cursor is trusted as-is
/// and the mount-time re-commit is skipped, since re-committing would stack a spurious interaction on
/// the restored cursor and make the first undo a no-op.
DocumentStorageMounted {
document_id: DocumentId,
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
mounted: Option<Box<(document_format::GddV1, document_graph_storage::Declarations)>>,
},
DestroyAllDocuments,
EditorPreferences,
GarbageCollectResources,
ResolveResources,
ResolveDocumentResources {
document_id: DocumentId,
},
ResolveResources,
LoadPersistedState {
state: PersistedState,
},
StoredDocumentsListed {
document_ids: Option<Vec<DocumentId>>,
},
StoredDocumentLoaded {
LoadDocumentContent {
document_id: DocumentId,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
document: Option<Box<DocumentMessageHandler>>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<Box<document_format::GddV1>>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
declarations: document_graph_storage::Declarations,
document_serialized_content: String,
},
NewDocumentWithName {
name: String,
},
OpenLegacyDocumentFile {
NextDocument,
OpenDocumentFile {
document_name: Option<String>,
document_path: Option<PathBuf>,
document_serialized_content: String,
},
OpenDocumentFile {
/// Open a `.gdd` document container (archive bytes), building the runtime from its stored registry.
OpenGddDocument {
document_name: Option<String>,
document_path: Option<PathBuf>,
content: Vec<u8>,
},
DocumentFileLoaded {
/// Delivers a document built asynchronously from a `.gdd` archive (registry → runtime, working copy
/// mounted) into the portfolio. Travels once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
GddDocumentLoaded {
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
document: Option<Box<DocumentMessageHandler>>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<Box<document_format::GddV1>>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
declarations: document_graph_storage::Declarations,
},
StorageUpdated,
StorageAttached {
LoadDocument {
document_id: DocumentId,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
container: Option<AnyContainer>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<Box<document_format::GddV1>>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
declarations: document_graph_storage::Declarations,
document_name: Option<String>,
document_path: Option<PathBuf>,
document_is_auto_saved: bool,
document_is_saved: bool,
document_serialized_content: String,
},
NextDocument,
PrevDocument,
CenterLayers {
layers: Vec<LayerNodeIdentifier>,
},
PrevDocument,
ReorderDocument {
document_id: DocumentId,
new_index: usize,
@@ -155,7 +148,8 @@ pub enum PortfolioMessage {
UpdateOpenDocumentsList,
}
/// Clone helper for non-serializable payloads: a cloned completion message carries none.
/// Clone helper for non-serializable payloads: a cloned message carries none of the `Gdd` working copy,
/// its declarations, or the built document.
fn clone_to_none<T>(_: &Option<T>) -> Option<T> {
None
}
@@ -2,7 +2,7 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
use super::utility_types::PanelType;
use crate::application::{Editor, generate_uuid};
use crate::consts::DEFAULT_DOCUMENT_NAME;
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
@@ -12,22 +12,19 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document_storage_io::{
DocumentStoreHandle, attach_container, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, open_storage, remove_stored_document,
};
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::messages::portfolio::document_migration::*;
use crate::messages::portfolio::document_storage_io::{build_or_open_working_copy, compare_storage_against_runtime, open_gdd_document};
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::resource_storage::ResourcesHandle;
use crate::messages::tool::utility_types::{HintData, ToolType};
use crate::messages::viewport::ToPhysical;
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
use document_container::AsyncContainer;
use document_format::GddV1;
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::renderer::Quad;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::vec;
@@ -46,7 +43,10 @@ pub struct PortfolioMessageContext<'a> {
#[derive(Debug, Default, ExtractField)]
pub struct PortfolioMessageHandler {
pub documents: HashMap<DocumentId, DocumentMessageHandler>,
loading_documents: HashMap<DocumentId, DocumentInfo>,
unloaded_documents: HashMap<DocumentId, DocumentInfo>,
/// Background eager loads whose trailing `SelectDocument` should be suppressed to keep focus on the user's active doc.
// TODO: Eventually remove this document upgrade code
pending_eager_loads: HashSet<DocumentId>,
document_ids: VecDeque<DocumentId>,
pub(crate) active_document_id: Option<DocumentId>,
failed_documents: FailedDocumentsMessageHandler,
@@ -57,10 +57,9 @@ pub struct PortfolioMessageHandler {
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
pub workspace: WorkspaceMessageHandler,
document_store: DocumentStoreHandle,
working_copy_root: Option<PathBuf>,
/// Number of documents not fully loaded. While nonzero, resource GC is skipped.
pending_opens: usize,
restore_select: Option<DocumentId>,
store_unavailable: bool,
}
#[message_handler_data]
@@ -106,7 +105,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.persistent_state.process_message(message, responses, context);
}
PortfolioMessage::FailedDocuments(message) => {
let context = FailedDocumentsMessageContext { document_store: &self.document_store };
let context = FailedDocumentsMessageContext { document_ids: &mut self.document_ids };
self.failed_documents.process_message(message, responses, context);
}
PortfolioMessage::Fonts(message) => {
@@ -129,9 +128,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Messages
PortfolioMessage::Init => {
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
responses.add(PersistentStateMessage::ReadState);
// Initialize the frontend with environment information
@@ -139,6 +135,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
platform: Editor::environment().into(),
});
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
// Before loading any documents, initially prepare the welcome screen buttons layout
responses.add(PortfolioMessage::RequestWelcomeScreenButtonsLayout);
@@ -192,16 +191,18 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::AutoSaveActiveDocument => {
if let Some(document_id) = self.active_document_id
&& self.documents.contains_key(&document_id)
&& let Some(document) = self.active_document_mut()
{
document.set_auto_save_state(true);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
}
PortfolioMessage::AutoSaveAllDocuments => {
for document_id in self.document_ids.iter() {
if let Some(document) = self.documents.get(document_id)
if let Some(document) = self.documents.get_mut(document_id)
&& !document.is_auto_saved()
{
document.set_auto_save_state(true);
responses.add(PortfolioMessage::AutoSaveDocument { document_id: *document_id });
}
}
@@ -209,23 +210,15 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::GarbageCollectResources);
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let validate = preferences.validate_storage_round_trip;
let Some(document) = self.documents.get_mut(&document_id) else { return };
let Some(container) = document.container.clone() else { return };
match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
Ok(()) => {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.set_auto_save_state(true);
}
Err(error) => {
document.set_auto_save_state(false);
log::error!("Autosave of {document_id:?} failed: {error}");
responses.add(DialogMessage::DisplayDialogError {
title: "Autosave is not working".to_string(),
description: format!("Save your documents manually to avoid losing changes.\n\n{error}"),
});
}
}
document.commit_storage_snapshot(&resource_storage.resources_mut(), validate);
responses.add(PersistentStateMessage::WriteDocument {
document_id,
document: document.serialize_document(),
});
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
@@ -245,8 +238,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
HintData::clear_layout(responses);
}
for document_id in self.document_ids.iter().copied().collect::<Vec<_>>() {
responses.add(remove_stored_document(self.document_store.clone(), document_id));
for document_id in &self.document_ids {
responses.add(PersistentStateMessage::DeleteDocument { document_id: *document_id });
}
responses.add(PortfolioMessage::DestroyAllDocuments);
@@ -271,7 +264,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Actually delete the document (delay to delete document is required to let the document and properties panel messages above get processed)
responses.add(PortfolioMessage::DeleteDocument { document_id });
responses.add(remove_stored_document(self.document_store.clone(), document_id));
responses.add(PersistentStateMessage::DeleteDocument { document_id });
// Send the new list of document tab names
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
@@ -299,11 +292,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PortfolioMessage::DeleteDocument { document_id } => {
let document_index = self.document_index(document_id);
self.documents.remove(&document_id);
self.loading_documents.remove(&document_id);
self.unloaded_documents.remove(&document_id);
self.document_ids.remove(document_index);
if self.restore_select == Some(document_id) {
self.restore_select = None;
}
if self.document_ids.is_empty() {
self.active_document_id = None;
@@ -319,24 +309,51 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::DocumentStorageMounted { document_id, reopened, mounted } => {
let Some(document) = self.documents.get_mut(&document_id) else {
// Document was closed before its working copy finished mounting.
return;
};
let Some(mounted) = mounted else {
log::error!("DocumentStorageMounted for {document_id:?} arrived without its payload");
return;
};
let (gdd, declarations) = *mounted;
document.set_storage(gdd, declarations);
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
}
PortfolioMessage::DestroyAllDocuments => {
// Empty the list of internal document data
self.documents.clear();
self.loading_documents.clear();
self.unloaded_documents.clear();
self.document_ids.clear();
self.active_document_id = None;
self.restore_select = None;
responses.add(MenuBarMessage::SendLayout);
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::EditorPreferences => self.executor.update_editor_preferences(preferences.editor_preferences()),
PortfolioMessage::GarbageCollectResources => {
// The resources of documents that are not loaded yet are unknown, so GC waits for every load and for a successful store listing.
if !self.persistent_state.loaded() || self.pending_opens > 0 || !self.loading_documents.is_empty() || self.store_unavailable {
if !self.persistent_state.loaded() {
// We don't know what can be safely garbage collected
return;
}
if self.pending_opens > 0 {
// A document not fully loaded, skip garbage collection.
return;
}
let mut used_resources = HashSet::new();
for (id, info) in self.unloaded_documents.iter() {
if let Some(resources) = &info.resources {
used_resources.extend(resources.iter());
} else {
responses.add(PersistentStateMessage::ReadDocument { document_id: *id });
return;
}
}
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
@@ -380,97 +397,70 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
workspace_layout: _,
} = state;
// TODO: Eventually remove this document upgrade code
let mut newly_unloaded_ids = Vec::new();
for info in documents {
if !self.document_ids.contains(&info.id) {
self.document_ids.push_back(info.id);
self.loading_documents.insert(info.id, info);
}
if !self.documents.contains_key(&info.id) && !self.unloaded_documents.contains_key(&info.id) {
// TODO: Eventually remove this document upgrade code
newly_unloaded_ids.push(info.id);
self.unloaded_documents.insert(info.id, info);
}
}
self.restore_select = current_document;
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(list_stored_documents(self.document_store.clone()));
}
PortfolioMessage::StoredDocumentsListed { document_ids } => {
let Some(stored) = document_ids else {
self.store_unavailable = true;
Self::storage_error("The stored documents could not be listed, so they cannot be opened.".to_string(), responses);
return;
};
let stored: HashSet<_> = stored.into_iter().collect();
// Session entries without stored content are dropped; stored documents the session does not know are appended.
self.document_ids.retain(|id| stored.contains(id) || self.documents.contains_key(id));
self.loading_documents.retain(|id, _| stored.contains(id));
for document_id in stored {
if !self.document_ids.contains(&document_id) {
self.document_ids.push_back(document_id);
self.loading_documents.insert(
document_id,
DocumentInfo {
id: document_id,
name: String::new(),
path: None,
is_saved: false,
},
);
let select_document_id = current_document.filter(|id| self.document_ids.contains(id)).or_else(|| self.document_ids.front().copied());
// Eagerly load every autosaved doc on startup so deserialization failures can be reported in one batched dialog at the end.
// The active doc's read is deferred to the `SelectDocument` below, but is still counted.
// TODO: Eventually remove this document upgrade code
self.failed_documents.expect_autosave_loads(newly_unloaded_ids.len());
// TODO: Eventually remove this document upgrade code
for document_id in &newly_unloaded_ids {
if Some(*document_id) != select_document_id {
self.pending_eager_loads.insert(*document_id);
responses.add(PersistentStateMessage::ReadDocument { document_id: *document_id });
}
}
for document_id in self.loading_documents.keys().copied().collect::<Vec<_>>() {
self.pending_opens += 1;
responses.add(load_stored_document(
self.document_store.clone(),
document_id,
resource_storage.resources_mut(),
reset_node_definitions_on_open,
!preferences.save_as_gdd,
));
if let Some(document_id) = select_document_id {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
PortfolioMessage::StoredDocumentLoaded {
document_id,
document,
gdd,
declarations,
} => {
self.pending_opens = self.pending_opens.saturating_sub(1);
let Some(info) = self.loading_documents.remove(&document_id) else {
// Closed while loading.
responses.add(remove_stored_document(self.document_store.clone(), document_id));
return;
};
match document.map(|boxed| *boxed) {
Some(mut document) => {
// The legacy file carries no name, so a document the session does not know gets a fresh one.
document.name = if info.name.trim().is_empty() {
self.generate_new_document_name(Some(document_id))
} else {
info.name
};
document.path = info.path;
document.set_save_state(info.is_saved);
self.load_document(document, document_id, resource_storage.resources_mut(), !preferences.save_as_gdd, responses);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
}
None => {
self.document_ids.retain(|id| *id != document_id);
self.failed_documents.record_failure(document_id, info);
if self.active_document_id == Some(document_id) {
self.active_document_id = None;
}
}
}
if self.active_document().is_none() {
self.select_after_load(responses);
}
if self.pending_opens == 0 {
// TODO: Eventually remove this document upgrade code
else if self.failed_documents.has_failures_to_report() {
responses.add(FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog);
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
PortfolioMessage::LoadDocumentContent {
document_id,
document_serialized_content,
} => {
let Some(info) = self.unloaded_documents.remove(&document_id) else {
log::error!("Tried to load content for non existent document");
return;
};
responses.add(PortfolioMessage::LoadDocument {
document_id,
document_name: Some(info.name),
document_path: info.path,
document_is_auto_saved: true,
document_is_saved: info.is_saved,
document_serialized_content,
});
// Suppress auto-select for startup eager loads to keep focus on the user's active doc
// TODO: Eventually remove this document upgrade code
// TODO: (But keep the inner logic unconditionally, just remove the condition)
if !self.pending_eager_loads.remove(&document_id) {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::NewDocumentWithName { name } => {
let mut new_document = DocumentMessageHandler::default();
@@ -484,105 +474,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
}
self.load_document(new_document, document_id, resource_storage.resources_mut(), !preferences.save_as_gdd, responses);
self.load_document(new_document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::OpenLegacyDocumentFile {
document_name,
document_path,
document_serialized_content,
} => {
let mut document = match load_legacy_document(document_serialized_content, &resource_storage.resources_mut(), reset_node_definitions_on_open) {
Ok(document) => document,
Err(error) => {
log::error!("{error}");
let document_name = opened_document_name(document_name, document_path.as_deref());
simple_dialogs::FailedToOpenDocumentDialog { document_name }.send_dialog_to_frontend(responses);
return;
}
};
let document_id = DocumentId(generate_uuid());
document.set_save_state(true);
document.name = self.resolve_document_name(opened_document_name(document_name, document_path.as_deref()), None);
document.path = document_path;
self.load_document(document, document_id, resource_storage.resources_mut(), !preferences.save_as_gdd, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
responses.add(AppWindowMessage::Focus);
}
PortfolioMessage::OpenDocumentFile {
document_name,
document_path,
content,
} => {
let document_id = DocumentId(generate_uuid());
// Suppress resource GC until the open completes
self.pending_opens += 1;
responses.add(open_document_file(
self.document_store.clone(),
document_id,
document_name,
document_path,
content,
resource_storage.resources_mut(),
reset_node_definitions_on_open,
!preferences.save_as_gdd,
));
}
PortfolioMessage::DocumentFileLoaded {
document_id,
document_name,
document_path,
document,
gdd,
declarations,
} => {
self.pending_opens = self.pending_opens.saturating_sub(1);
let Some(mut document) = document.map(|boxed| *boxed) else {
let document_name = opened_document_name(document_name, document_path.as_deref());
simple_dialogs::FailedToOpenDocumentDialog { document_name }.send_dialog_to_frontend(responses);
responses.add(remove_stored_document(self.document_store.clone(), document_id));
return;
};
document.set_save_state(true);
document.name = self.resolve_document_name(opened_document_name(document_name, document_path.as_deref()), None);
document.path = document_path;
self.load_document(document, document_id, resource_storage.resources_mut(), !preferences.save_as_gdd, responses);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::StorageUpdated => {
for (&document_id, document) in &mut self.documents {
match (preferences.save_as_gdd, document.storage().is_some(), document.container.clone()) {
(true, false, Some(container)) => responses.add(open_storage(container, document_id, resource_storage.resources_mut())),
(false, true, _) => document.clear_storage(),
_ => {}
}
}
}
PortfolioMessage::StorageAttached {
document_id,
container,
gdd,
declarations,
} => {
let Some(document) = self.documents.get_mut(&document_id) else {
// Closed while its storage was opening.
responses.add(remove_stored_document(self.document_store.clone(), document_id));
return;
};
let Some(container) = container else {
Self::storage_error("The document's storage could not be opened, so it will not be autosaved.".to_string(), responses);
return;
};
document.container = Some(container);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
self.save_if_needed(document_id, responses);
}
PortfolioMessage::NextDocument => {
if let Some(active_document_id) = self.active_document_id {
let current_index = self.document_index(active_document_id);
@@ -592,13 +486,229 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::SelectDocument { document_id: next_id });
}
}
PortfolioMessage::PrevDocument => {
if let Some(active_document_id) = self.active_document_id {
let len = self.document_ids.len();
let current_index = self.document_index(active_document_id);
let prev_index = (current_index + len - 1) % len;
let prev_id = self.document_ids[prev_index];
responses.add(PortfolioMessage::SelectDocument { document_id: prev_id });
PortfolioMessage::OpenDocumentFile {
document_name,
document_path,
document_serialized_content,
} => {
let document_id = DocumentId(generate_uuid());
responses.add(PortfolioMessage::LoadDocument {
document_id,
document_name,
document_path,
document_is_auto_saved: false,
document_is_saved: true,
document_serialized_content,
});
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::OpenGddDocument {
document_name,
document_path,
content,
} => {
let document_id = DocumentId(generate_uuid());
// Suppress resource GC until the open completes
self.pending_opens += 1;
responses.add(open_gdd_document(
self.working_copy_root.clone(),
document_id,
document_name,
document_path,
content,
resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
));
}
PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
document_path,
document,
} => {
self.pending_opens = self.pending_opens.saturating_sub(1);
let Some(mut document) = document.map(|boxed| *boxed) else {
let name = document_name
.filter(|name| !name.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_default();
simple_dialogs::FailedToOpenDocumentDialog { document_name: name }.send_dialog_to_frontend(responses);
return;
};
document.finalize_storage_load();
document.set_save_state(true);
let name = document_name
.filter(|name| !name.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string());
document.name = self.resolve_document_name(name, None);
document.path = document_path;
// The working copy is already mounted (we opened the .gdd), so skip the async re-mount.
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
responses.add(MenuBarMessage::SendLayout);
}
PortfolioMessage::LoadDocument {
document_id,
document_name,
document_path,
document_is_auto_saved,
document_is_saved,
document_serialized_content,
} => {
// 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);
// Deserialize the document
let document = DocumentMessageHandler::deserialize_document(&document_serialized_content);
// Display an error to the user if the document could not be opened
let mut document = match document {
Ok(document) => document,
Err(e) => {
log::error!("{e}");
// TODO: Eventually remove this document upgrade code
// TODO: (Only the `if` branch, the `else` branch's manual-open dialog stays)
if document_is_auto_saved {
let name = document_name.unwrap_or_default();
let info = DocumentInfo {
id: document_id,
name,
resources: None,
path: document_path,
is_saved: document_is_saved,
};
self.document_ids.retain(|id| id != &document_id);
self.failed_documents.record_failure(document_id, info, document_serialized_content);
if self.active_document_id == Some(document_id) {
self.active_document_id = None;
if let Some(next_id) = self.document_ids.front().copied() {
responses.add(PortfolioMessage::SelectDocument { document_id: next_id });
}
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
self.failed_documents.tick_autosave_load_progress(responses, true);
} else {
let name = document_name
.filter(|n| !n.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|p| p.file_stem()).map(|s| s.to_string_lossy().into_owned()))
.unwrap_or_default();
let dialog = simple_dialogs::FailedToOpenDocumentDialog { document_name: name };
dialog.send_dialog_to_frontend(responses);
}
return;
}
};
// 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;
}
responses.add(ResourceStorageMessage::Store { data });
// 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);
}
});
// 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, &[]);
}
}
}
// Everything above is how the document arrives rather than an edit to it, so what those 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 instead of staging the batch that follows them.
document.network_interface.discard_deltas();
document.require_whole_document_stage();
// Set the save state of the document based on what's given to us by the caller to this message
document.set_auto_save_state(document_is_auto_saved);
document.set_save_state(document_is_saved);
let document_name_from_path = document_path.as_ref().and_then(|path| {
if path.extension().is_some_and(|extension| extension == FILE_EXTENSION || extension == GDD_FILE_EXTENSION) {
path.file_stem().map(|stem| stem.to_string_lossy().to_string())
} else {
None
}
});
let candidate_name = match (document_name, document_path, document_name_from_path) {
(Some(name), _, None) => name,
(_, Some(path), Some(name)) => {
document.path = Some(path);
name
}
(_, _, Some(name)) => name,
_ => String::new(),
};
document.name = self.resolve_document_name(candidate_name, None);
// Load the document into the portfolio so it opens in the editor
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(AppWindowMessage::Focus);
// TODO: Eventually remove this document upgrade code
if document_is_auto_saved {
self.failed_documents.tick_autosave_load_progress(responses, false);
}
}
PortfolioMessage::CenterLayers { layers } => {
@@ -706,6 +816,15 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
PortfolioMessage::PrevDocument => {
if let Some(active_document_id) = self.active_document_id {
let len = self.document_ids.len();
let current_index = self.document_index(active_document_id);
let prev_index = (current_index + len - 1) % len;
let prev_id = self.document_ids[prev_index];
responses.add(PortfolioMessage::SelectDocument { document_id: prev_id });
}
}
PortfolioMessage::ReorderDocument { document_id, new_index } => {
let new_index = new_index.min(self.document_ids.len().saturating_sub(1));
let Some(current_index) = self.document_ids.iter().position(|&id| id == document_id) else {
@@ -780,6 +899,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
layout_target: LayoutTarget::StatusBarInfo,
});
}
PortfolioMessage::RenameDocument { new_name } => {
let resolved_name = self.resolve_document_name(new_name, self.active_document_id);
responses.add(DocumentMessage::RenameDocument { new_name: resolved_name });
}
PortfolioMessage::SelectDocument { document_id } => {
// Auto-save the document we are leaving
let mut node_graph_open = false;
@@ -793,12 +916,18 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
node_graph_open = document.is_graph_overlay_open();
}
if self.loading_documents.contains_key(&document_id) {
if self.unloaded_documents.contains_key(&document_id) {
let already_selected = self.active_document_id == Some(document_id);
self.active_document_id = Some(document_id);
self.restore_select = Some(document_id);
responses.add(MenuBarMessage::SendLayout);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
if !already_selected {
responses.add(PersistentStateMessage::ReadDocument { document_id });
}
return;
}
@@ -809,7 +938,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Set the new active document ID
self.active_document_id = Some(document_id);
self.restore_select = None;
responses.add(MenuBarMessage::SendLayout);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
@@ -841,10 +969,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PropertiesPanelMessage::Clear);
}
}
PortfolioMessage::RenameDocument { new_name } => {
let resolved_name = self.resolve_document_name(new_name, self.active_document_id);
responses.add(DocumentMessage::RenameDocument { new_name: resolved_name });
}
PortfolioMessage::SubmitDocumentExport {
name,
file_type,
@@ -973,10 +1097,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
Ok(message) => responses.add_front(message),
}
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
responses.add(MenuBarMessage::SendLayout);
}
PortfolioMessage::ToggleRulers => {
if let Some(document) = self.active_document_mut() {
document.rulers_visible = !document.rulers_visible;
@@ -1033,13 +1153,8 @@ impl PortfolioMessageHandler {
Self { executor, ..Default::default() }
}
pub fn set_document_store(&mut self, store: Arc<dyn document_container::store::DocumentStore>) {
self.document_store = DocumentStoreHandle::new(store);
}
#[cfg(test)]
pub(crate) fn document_store(&self) -> DocumentStoreHandle {
self.document_store.clone()
pub fn set_working_copy_root(&mut self, root: Option<PathBuf>) {
self.working_copy_root = root;
}
pub fn document(&self, document_id: DocumentId) -> Option<&DocumentMessageHandler> {
@@ -1072,8 +1187,16 @@ impl PortfolioMessageHandler {
}
pub fn persisted_state_snapshot(&self) -> PersistedState {
let mut documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
// Keep failed-to-load docs referenced in `state.documents` so their autosave files survive `garbage_collect_document_files`
// TODO: Eventually remove this document upgrade code
for info in self.failed_documents.failed_document_infos() {
documents.push(info.clone());
}
PersistedState {
documents: self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect(),
documents,
current_document: self.active_document_id,
workspace_layout: Some(self.workspace.panel_layout.clone()),
}
@@ -1112,12 +1235,19 @@ impl PortfolioMessageHandler {
if new_number == 1 { untitled.to_string() } else { format!("{untitled} {new_number}") }
}
fn load_document(&mut self, mut new_document: DocumentMessageHandler, document_id: DocumentId, resources: ResourcesHandle, legacy_only: bool, responses: &mut VecDeque<Message>) {
fn load_document(
&mut self,
mut new_document: DocumentMessageHandler,
document_id: DocumentId,
resource_storage: &ResourceStorageMessageHandler,
validate: bool,
responses: &mut VecDeque<Message>,
) {
let is_new_document = !self.document_ids.contains(&document_id);
if is_new_document {
self.document_ids.push_back(document_id);
}
self.loading_documents.remove(&document_id);
self.unloaded_documents.remove(&document_id);
new_document.update_layers_panel_control_bar_widgets(
self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document,
responses,
@@ -1140,60 +1270,67 @@ impl PortfolioMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
if self.documents[&document_id].container.is_none() {
responses.add(attach_container(self.document_store.clone(), document_id, resources, legacy_only));
} else {
self.save_if_needed(document_id, responses);
// Mount the per-document `Gdd` working copy asynchronously.
//
// Only mount for legacy loads: a `.gdd` open already mounted its working copy
// and remounting would overwrite it and drop that history state.
if self.documents.get(&document_id).and_then(|document| document.storage()).is_none() {
let legacy_network = self
.documents
.get(&document_id)
.map(|document| document.network_interface.document_network().clone())
.unwrap_or_default();
responses.add(Self::mount_document_storage(
self.working_copy_root.clone(),
document_id,
legacy_network,
resource_storage.resources(),
validate,
));
}
}
/// Installs the storage session and stages the current network so a session that fell behind the legacy
/// document catches up. Identical content stages nothing.
fn attach_storage(
&mut self,
/// With a configured root the working copy lives at `<root>/<id_hex>`; without one it is in-memory.
///
/// On a *reopen* (existing working copy), the freshly-read `.gdd` is converted back to a runtime
/// network and compared against `legacy_network` before
/// the working copy attaches. It validates the `.gdd` *read* path.
fn mount_document_storage(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
gdd: Option<Box<GddV1>>,
declarations: Declarations,
resource_storage: &ResourceStorageMessageHandler,
preferences: &PreferencesMessageHandler,
) {
let (Some(document), Some(gdd)) = (self.documents.get_mut(&document_id), gdd) else { return };
document.set_storage(*gdd, declarations);
document.require_whole_document_stage();
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
legacy_network: graph_craft::document::NodeNetwork,
byte_store: Box<dyn graph_craft::application_io::resource::LoadResource>,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:016x}", document_id.0)));
let editor_version = crate::application::GRAPHITE_GIT_COMMIT_HASH.to_string();
let peer = document_graph_storage::PeerId(generate_uuid());
fn save_if_needed(&self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
if let Some(document) = self.documents.get(&document_id)
&& document.container.is_some()
&& !document.is_auto_saved()
{
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
}
let future = async move {
let (gdd, reopened) = match build_or_open_working_copy(path.as_deref(), peer, document_id.0, editor_version).await {
Ok(result) => result,
Err(error) => {
log::error!("Failed to mount document storage for {document_id:?}: {error}");
return Message::NoOp;
}
};
/// Selects the restored document once it is loaded, or the first document when it failed or the session named none.
fn select_after_load(&mut self, responses: &mut VecDeque<Message>) {
let target = self.restore_select.filter(|id| self.document_ids.contains(id)).or_else(|| self.document_ids.front().copied());
let Some(target) = target else {
self.restore_select = None;
return;
let declarations = gdd.declarations(byte_store.as_ref()).await;
if validate && reopened {
compare_storage_against_runtime(&gdd, &legacy_network, &declarations, document_id);
}
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
mounted: Some(Box::new((gdd, declarations))),
})
};
if self.documents.contains_key(&target) {
self.restore_select = None;
responses.add(PortfolioMessage::SelectDocument { document_id: target });
} else {
self.restore_select = Some(target);
}
future.into()
}
fn storage_error(description: String, responses: &mut VecDeque<Message>) {
responses.add(DialogMessage::DisplayDialogError {
title: "Document storage failed".to_string(),
description,
});
}
/// Returns an iterator over the open documents in order.
pub fn ordered_document_iterator(&self) -> impl Iterator<Item = &DocumentMessageHandler> {
self.document_ids.iter().filter_map(|id| self.document(*id))
@@ -1234,9 +1371,10 @@ impl PortfolioMessageHandler {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
resources: Some(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()).collect::<Vec<_>>().into_boxed_slice()),
})
} else {
self.loading_documents.get(&document_id).cloned()
self.unloaded_documents.get(&document_id).cloned()
}
}
@@ -1267,10 +1405,3 @@ impl PortfolioMessageHandler {
path
}
}
/// The name an opened file gets: the given name, else the file stem of its path, else empty so the portfolio generates one.
fn opened_document_name(name: Option<String>, path: Option<&Path>) -> String {
name.filter(|name| !name.trim().is_empty())
.or_else(|| path.and_then(Path::file_stem).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_default()
}
@@ -94,7 +94,6 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
});
responses.add(FrontendMessage::UpdateUIScale { scale: self.ui_scale });
responses.add(ToolMessage::RefreshToolShelf);
responses.add(PortfolioMessage::StorageUpdated);
}
PreferencesMessage::ResetToDefaults => {
responses.add(PreferencesMessage::Load { preferences: Self::default() });
@@ -145,7 +144,6 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
}
PreferencesMessage::SaveAsGdd { enabled } => {
self.save_as_gdd = enabled;
responses.add(PortfolioMessage::StorageUpdated);
}
PreferencesMessage::ToggleShowStoragePreferences => {
self.show_storage_preferences = !self.show_storage_preferences;
-1
View File
@@ -61,7 +61,6 @@ pub use crate::messages::tool::tool_messages::text_tool::{TextToolMessage, TextT
// Helper/miscellaneous
pub use crate::messages::portfolio::document::utility_types::misc::DocumentId;
pub use graphene_std::core_types::FallibleVec2Operations;
pub use graphite_proc_macros::*;
pub use std::collections::{HashMap, HashSet, VecDeque};
@@ -1,7 +1,6 @@
use crate::consts::{COMPASS_ROSE_ARROW_CLICK_TARGET_ANGLE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::FallibleVec2Operations;
use std::f64::consts::FRAC_PI_2;
#[derive(Clone, Default, Debug)]
@@ -57,9 +56,7 @@ impl CompassRose {
return CompassRoseState::None;
}
let Some(angle) = (mouse - self.compass_center).try_angle_to(DVec2::from_angle(angle)).map(f64::abs) else {
return CompassRoseState::None;
};
let angle = (mouse - self.compass_center).angle_to(DVec2::from_angle(angle)).abs();
let resolved_angle = (FRAC_PI_2 - angle).abs();
let angular_width = COMPASS_ROSE_ARROW_CLICK_TARGET_ANGLE.to_radians();
@@ -12,7 +12,6 @@ use glam::{DAffine2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::ParameterRef;
use graphene_std::core_types::FallibleVec2Operations;
use std::collections::VecDeque;
use std::f64::consts::FRAC_PI_2;
@@ -86,8 +85,7 @@ impl RadiusHandle {
return;
};
let viewport = document.metadata().transform_to_viewport(layer);
let vector = viewport.inverse().transform_point2(mouse_position);
let Some(angle) = vector.try_angle_to(DVec2::X) else { return };
let angle = viewport.inverse().transform_point2(mouse_position).angle_to(DVec2::X);
let point_position = viewport.transform_point2(calculate_circle_point_position(angle, radius.abs()));
let center = viewport.transform_point2(DVec2::ZERO);
@@ -12,7 +12,6 @@ use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate
use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::FallibleVec2Operations;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -151,13 +150,11 @@ impl SpiralTurns {
let viewport = document.metadata().transform_to_viewport(layer);
let center = viewport.transform_point2(DVec2::ZERO);
let current_mouse_vector = viewport.inverse().transform_vector2(input.mouse.position - center);
let previous_mouse_vector = viewport.inverse().transform_vector2(self.previous_mouse_position - center);
let Some(angle_delta) = current_mouse_vector.try_angle_to(previous_mouse_vector).map(f64::to_degrees) else {
self.previous_mouse_position = input.mouse.position;
return;
};
let angle_delta = viewport
.inverse()
.transform_vector2(input.mouse.position - center)
.angle_to(viewport.inverse().transform_vector2(self.previous_mouse_position - center))
.to_degrees();
// Skip update if angle calculation produced NaN or infinity (can happen when mouse is at center)
// Also skip very small angle changes to reduce jitter near center
@@ -169,16 +169,12 @@ impl SweepAngleGizmo {
let bold_radius = final_point.distance(center);
let Some(angle) = initial_vector.try_angle_to(final_vector).map(f64::to_degrees) else {
warn!("Cannot take angle for sweep gizmo");
return;
};
let initial_point_layer = viewport.inverse().transform_point2(initial_point);
let final_point_layer = viewport.inverse().transform_point2(final_point);
let Some(display_angle) = final_point_layer.try_angle_to(initial_point_layer).map(f64::to_degrees) else {
warn!("Cannot take angle for sweep gizmo");
return;
};
let angle = initial_vector.angle_to(final_vector).to_degrees();
let display_angle = viewport
.inverse()
.transform_point2(final_point)
.angle_to(viewport.inverse().transform_point2(initial_point))
.to_degrees();
let text = format!("{}°", format_rounded(display_angle, 2));
const FONT_SIZE: f64 = 12.;
@@ -199,11 +195,11 @@ impl SweepAngleGizmo {
};
let viewport = document.metadata().transform_to_viewport(layer);
let layer_previous_mouse = viewport.inverse().transform_point2(self.previous_mouse_position);
let layer_mouse = viewport.inverse().transform_point2(input.mouse.position);
let Some(angle_delta) = layer_previous_mouse.try_angle_to(layer_mouse).map(f64::to_degrees) else {
return;
};
let angle_delta = viewport
.inverse()
.transform_point2(self.previous_mouse_position)
.angle_to(viewport.inverse().transform_point2(input.mouse.position))
.to_degrees();
let angle = self.total_angle_delta + angle_delta;
let Some(node_id) = graph_modification_utils::get_arc_id(layer, &document.network_interface) else {
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more